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.
69 lines
2.2 KiB
69 lines
2.2 KiB
1 year ago
|
'use strict';
|
||
|
const moment = require('moment')
|
||
|
|
||
|
module.exports = function (app, opts) {
|
||
|
|
||
|
let axyTokenCache = {
|
||
|
userId: null,
|
||
|
orgId: null,
|
||
|
token: null,
|
||
|
expireTime: null //过期时间
|
||
|
}
|
||
|
|
||
|
let getAnxinyunToken = async function () {
|
||
|
try {
|
||
|
if (!axyTokenCache.token || moment() > moment(axyTokenCache.expireTime)) {
|
||
|
const dataToAxy = {
|
||
|
pcode: 'fce4afe2-5b6a-408a-ab18-a2afa7fa027c',
|
||
|
username: '123456',
|
||
|
password: '123456',
|
||
|
}
|
||
|
const axyResponse = await app.fs.waterReq.post('/login', dataToAxy)
|
||
|
const axyData = axyResponse.body
|
||
|
if (axyData.authorized) {
|
||
|
axyTokenCache.userId = axyData.id //放进缓存
|
||
|
axyTokenCache.orgId = axyData.orgId //放进缓存
|
||
|
axyTokenCache.token = axyData.token //放进缓存
|
||
|
axyTokenCache.expireTime = moment().add(23, 'hour').format('YYYY-MM-DD HH:mm:ss')
|
||
|
}
|
||
|
}
|
||
|
return axyTokenCache
|
||
|
} catch (err) {
|
||
|
app.fs.logger.error(`utils: fetch anxinyun token, error: ${err}`);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
let rslt = {};
|
||
|
async function getDataFromAxy(url, method, data) {
|
||
|
try {
|
||
|
if (rslt[url]) {
|
||
|
getData(url, method, data)
|
||
|
return rslt[url]
|
||
|
} else {
|
||
|
let res = await getData(url, method, data)
|
||
|
return res
|
||
|
}
|
||
|
} catch (err) {
|
||
|
app.fs.logger.error(`utils: fetch axy sensors Data, error: ${err}`);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
async function getData(url, method = 'get', data) {
|
||
|
try {
|
||
|
let ache = await getAnxinyunToken()
|
||
|
if (ache) {
|
||
|
const connector = url.indexOf('?') > -1 ? '&' : '?'
|
||
|
const res = await app.fs.waterReq[method](`${url}`, { ...data })
|
||
|
rslt[url] = res
|
||
|
return rslt[url]
|
||
|
}
|
||
|
} catch (err) {
|
||
|
app.fs.logger.error(`utils: fetch axy sensors Data, error: ${err}`);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return {
|
||
|
getAnxinyunToken,
|
||
|
getDataFromAxy
|
||
|
}
|
||
|
}
|