'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 } } async function varifyYingshiBelongSecretBySerialNo (serialNo) { const { models } = app.fs.dc const serialNo_ = String(serialNo).toUpperCase() const secretRes = await models.SecretYingshi.findAll() let beloneSecret = null for (let s of secretRes) { const tokenYingshi = await token4yingshi(s.dataValues) // 检测设备所属 const cameraState = await app.fs.yingshiRequest.post('lapp/device/info', { query: { accessToken: tokenYingshi, deviceSerial: serialNo_ } }) if (cameraState.code == 200) { beloneSecret = { ...s.dataValues, token: tokenYingshi } break } } return beloneSecret } return { token4yingshi, varifyYingshiBelongSecretBySerialNo, } }