使用谷歌API的异步认证
我有以下代码:
async function initApi() {
const googleKey = await readJSON(appRoot + '/secrets/google-auth.json');
const jwt = new google.auth.JWT(
googleKey.client_email, null, googleKey.private_key, scopes);
return jwt.authorize();
}
const calendar = {
events: events,
api: google.calendar({
version: 'v3',
auth: this.jwt
}),
list: async function() {
await this.api.calendarList.list();
},
};
module.exports = async () => Object.assign(calendar, { jwt: await initApi() });
我不断收到“错误需要登录”。然而,jwt
当我登录的结果解析蛮好的访问令牌:
const Calendar = require('./above-code.js');
Calendar().then(c => console.log(c.jwt));
// { access_token: ... }
Calendar().then(c => console.log(c.list());
// Error: login required
我不明白为什么。这是推动我绝对疯了。我希望把我的笔记本电脑出一个窗口。
我究竟做错了什么?这是使用async
和await
与module.exports
最好的模式?有没有更好的办法只有返回对象,所以我可以打电话Calendar.list()
并得到结果,而不必经过我目前做的只是得到的API,并直接调用方法跳火圈?例如。:
const Calendar = require('./above-code.js');
await Calendar.list();
回答如下:
您添加jwt
的对象,而不是作为一个独立的变量,所以它应该是:
google.calendar({
version: 'v3',
auth: this.jwt //here
}),
Object.assign(calendar, { jwt: 'value' });
它相当于calendar.jwt = 'value'
。你是指,如果它是这样完成的:
let jwt = 'value';
google.calendar({
version: 'v3',
auth: jwt //here
}),