Scrapbox-Google-API
使い方
code:js
import {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());
})();
dependencies
code:script.js
import {refreshToken as refresh} from '../ScrapboxからGoogle_APIのAccess_Tokenを取得する/script.js';
初期化
code:script.js
let _auth;
export function init({clientId, clientSecret, refreshToken}) {
_auth = {clientId, clientSecret, refreshToken};
}
APIを叩く
code:script.js
export async function exec(pathname, options = {}) {
return await fetch(https://www.googleapis.com${pathname}, {
headers: {
Authorization: Bearer ${await accessToken()},
},
...options,
});
}
内部用
access tokenを取得する
有効期限が切れそうだったら更新する
code:script.js
async 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;
}