이번 글에서는 구글 console에서 받은 token 값을 활용한 구글 캘린더를 가져와 볼 예정이다.
token과 refresh token 가져오는 법 및 권한 설정은
https://startedev-jay.tistory.com/19
위의 글을 보고 오면 된다.
token 값이 있다면 사용하는 방식이 어렵지는 않기에 매우 간단히 정리해보려고 한다.
우선 라이브러리를 다운받아준다.
사용할 라이브러리는 googleapis 와 google-auth-library이다.
#npm 다운로드
npm install googleapis google-auth-library @types/googleapis @types/google-auth-library --save
#yarn 다운로드
yarn add googleapis google-auth-library @types/googleapis @types/google-auth-library
만약 typescript를 사용하지 않는다면 @types라이브러리들은 추가하지 않아도 된다.
@Injectable()
export class WeeklyService {
constructor() {}
// google 캘린더
private readonly calendar = google.calendar("v3");
async getEvents(accessToken: string, calendarId: string, start: Date, end: Date) {
const auth = new OAuth2Client();
auth.setCredentials({ access_token: accessToken });
// const events = await this.calendar.events;
const events = await this.calendar.events.list({
auth,
calendarId,
timeMin: start.toISOString(),
timeMax: end.toISOString(),
singleEvents: true,
orderBy: "startTime",
});
return events.data.items;
}
}
위의 코드처럼 사용해주면 된다.
accessToken은 기존에 받아놓은 token값을 사용하면 되고, 만료될수 있기에 refresh token을 사용하여 불러올때마다새로 token을 받아서 주는 것도 좋은 방법이다.
calendarId는 가져오려는 캘린더의 설정에 들어가는 캘린더 통합 아래에 캘린더 ID를 확인 할 수 있다.
start와 end 는 가져오려는 캘린더 일정의 기간이다.
list에서 사용할수 있는 옵션들은
auth: 필수 매개변수로, 인증정보
calendarId: 필수 매개변수로, 캘린더 ID
timeMin: 선택적 매개변수로, 검색할 캘린더의 최소 시작시간
timeMax: 선택적 매개변수로, 검색할 캘린더의 최대 종료시간
singleEvents: 선택적 매개변수로, 특정 기간동안의 캘린더 일정을 단일 일정으로 분해할지 여부를 지정, 기본값은 false
orderBy: 선택적 매개변수로, 결과의 정렬 순서 지정(startTime, updated) 사용 가능, 기본값은 startTime
maxResults: 선택적 매개변수로, 최대 일정 수를 지정, 기본값은 250
들이 있다.
가져오고 난 후 events.data.items 에 배열 형태로 출력된다.