Skip to content

Commit

Permalink
Revise getAccessToken
Browse files Browse the repository at this point in the history
  • Loading branch information
changhc committed Dec 29, 2019
1 parent 7968268 commit 7149347
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 34 deletions.
49 changes: 20 additions & 29 deletions src/fbClient.js
Original file line number Diff line number Diff line change
Expand Up @@ -178,37 +178,28 @@ export async function replyToComment(commentId, msg) {
* @param {undefined}
* @returns {Promise} Promise wrapping a request for long-lived tokens
*/
export function getLongLivedPageAccessToken() {
return new Promise((resolve, reject) => {
if (process.env.APP_ID === undefined) {
reject(new Error(`Invalid page id: ${process.env.APP_ID}`));
return;
}
export async function getLongLivedPageAccessToken() {
if (process.env.APP_ID === undefined) {
throw new Error(`Invalid page id: ${process.env.APP_ID}`);
}

let token = process.env.PAGE_ACCESS_TOKEN;
const redisToken = Promise.resolve(redis.get('pageAccessToken'));
if (redisToken) {
token = redisToken;
}
let token = process.env.PAGE_ACCESS_TOKEN;
const redisToken = await redis.get('pageAccessToken');
if (redisToken) {
token = redisToken;
}

fetch(
`${URL}/oauth/access_token?grant_type=fb_exchange_token&client_id=${process.env.APP_ID}&client_secret=${process.env.APP_SECRET}&fb_exchange_token=${token}`
)
.then(res => res.json())
.then(res => {
if (!Object.prototype.hasOwnProperty.call(res, 'access_token')) {
throw new Error(
'Failed to get a page access token: ' + JSON.stringify(res)
);
}
process.env.PAGE_ACCESS_TOKEN = res.access_token;
redis.set('pageAccessToken', res.access_token);
resolve();
})
.catch(e => {
reject(e);
});
});
const res = await fetch(
`${URL}/oauth/access_token?grant_type=fb_exchange_token&client_id=${process.env.APP_ID}&client_secret=${process.env.APP_SECRET}&fb_exchange_token=${token}`
);
const resBody = await res.json();
if (!Object.prototype.hasOwnProperty.call(resBody, 'access_token')) {
throw new Error(
'Failed to get a page access token: ' + JSON.stringify(resBody)
);
}
process.env.PAGE_ACCESS_TOKEN = resBody.access_token;
await redis.set('pageAccessToken', resBody.access_token);
}

/**
Expand Down
11 changes: 6 additions & 5 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,16 +75,17 @@ app.use(router.routes());
app.use(router.allowedMethods());

// get page access token and then start listening
getLongLivedPageAccessToken()
.then(() => {
(async () => {
try {
await getLongLivedPageAccessToken();
console.log('Long-lived page access token fetched');

app.listen(process.env.PORT, () => {
// eslint-disable-next-line no-console
console.log('Listening port', process.env.PORT);
});
})
.catch(e => {
} catch (e) {
console.error(e);
process.exit();
});
}
})();

0 comments on commit 7149347

Please sign in to comment.