You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
49 lines
1.3 KiB
49 lines
1.3 KiB
'use strict';
|
|
|
|
const moment = require('moment')
|
|
|
|
module.exports = function (app, opts) {
|
|
async function token4yingshi ({ key, secret, token, expire } = {}) {
|
|
const { models } = app.fs.dc
|
|
if (!key || !secret) {
|
|
throw '参数 { key, secret } 缺一不可'
|
|
}
|
|
|
|
if (token && expire && moment().isBefore(moment(expire))) {
|
|
return token
|
|
} else {
|
|
const secretRes = await models.SecretYingshi.findOne({
|
|
where: { key, secret }
|
|
})
|
|
if (secretRes && secretRes.expire && secretRes.token && moment().isBefore(moment(secretRes.expire))) {
|
|
return secretRes.token
|
|
}
|
|
}
|
|
|
|
// 也可以做基于 redis 的缓存
|
|
const tokenRes = await app.fs.yingshiRequest.post(`lapp/token/get`, {
|
|
query: {
|
|
appKey: key,
|
|
appSecret: secret
|
|
}
|
|
})
|
|
if (tokenRes.code == 200) {
|
|
const { accessToken, expireTime } = tokenRes.data
|
|
await models.SecretYingshi.update({
|
|
token: accessToken,
|
|
expire: expireTime
|
|
}, {
|
|
where: {
|
|
key, secret
|
|
}
|
|
})
|
|
return accessToken
|
|
} else {
|
|
throw tokenRes
|
|
}
|
|
}
|
|
|
|
return {
|
|
token4yingshi
|
|
}
|
|
}
|