jsimport {init, exec} from '/api/code/programming-notes/Scrapbox-Google-API/script.js';
// 初期化
const clientId = 'xxxxx';
const clientSecret = 'yyyyy';
const refreshToken = 'zzzzz';
init({clientId, clientSecret, refreshToken});
// 使う
(async () => {
const res = await exec('/calendar/v3/users/me/calendarList');
console.log(await res.json());
})();
script.jsimport {refreshToken as refresh} from '../ScrapboxからGoogle_APIのAccess_Tokenを取得する/script.js';
script.jslet _auth;
export function init({clientId, clientSecret, refreshToken}) {
_auth = {clientId, clientSecret, refreshToken};
}
script.jsexport async function exec(pathname, options = {}) {
return await fetch(`https://www.googleapis.com${pathname}`, {
headers: {
Authorization: `Bearer ${await accessToken()}`,
},
...options,
});
}
script.jsasync function accessToken() {
// 有効期限の1分前になったら更新する
if ((_auth.expiresIn ?? 0) - new Date().getTime() < 1000 * 60) {
const {access_token, expires_in} = await refresh(_auth);
_auth.expiresIn = new Date().getTime() + expires_in * 1000;
_auth.accessToken = access_token;
}
return _auth.accessToken;
}