我正在使用Fastify访问使用OAuth2的Sage API。访问令牌仅持续300秒,因此我经常需要刷新令牌。我不确定刷新令牌后如何返回到原始端点函数。我是否应该使用“ prehandler”选项至少执行步骤1并获取存储在数据库中的令牌?
fastify.route({
method: 'GET',
url: '/api/sage/salebyref/:ref',
handler: async (request, reply) => {
// 1. get credientials to make api call
let credentials = await getCredentialsByUser()
let authStr = 'Bearer '.concat(credentials.dataValues.oauth_token)
try {
// 2. make api call
let sageInvoice = await getSalesInvoicesByRef(authStr, request.params.ref)
return sageInvoice.data
} catch (error) {
if (error.response.status === 401) {
try {
// 3. if token invalid, refresh token
await refreshToken(credentials.dataValues.oauth_refresh_token, credentials.dataValues.userid)
// 4. somehow do it again
} catch (error) {
console.log(error)
throw error
}
} else {
console.log('not 401', error.response)
}
throw error
}
}
})