UNPKG

ynu-aaa

Version:

a 3A API Client for YNU

52 lines (49 loc) 1.51 kB
import * as process from 'node:process'; import axios from 'axios'; import * as cache from "memory-cache"; import Debug from "debug"; const debug = Debug('AAA:debug'); const warn = Debug('AAA:warn'); const https = require('https'); const httpsAgent = new https.Agent({ rejectUnauthorized: false // 禁用证书验证 }); export class AAAError extends Error { constructor (public code:number, message: string) { super(message); this.code = code; } } export type GetToken = { /** * 请求地址 */ host?: string, } /** * 获取token * @returns 获得的Token */ export const getToken = async (options: GetToken): Promise<string> => { const host = options.host || process.env.IDS_HOST; const tokenCacheKey = `AAA-token`; let token = cache.get(tokenCacheKey); if (token) { return token; } else { // const res = await axios.get<any>(`${host}/api/v1/auth/get-access-token`, { httpsAgent }) // console.log(res) const { data } = await axios.get<any>(`${host}/api/v1/auth/get-access-token`, { httpsAgent }) console.log(data) if (data?.code === 0 && data.data?.access_token) { debug(`获取token成功::${data}`); const token = data.data.access_token; // 缓存token,提前5分钟过期 cache.put(tokenCacheKey, token, 3600000 - 300000); return token; } warn('获取token出错:', data); throw new AAAError(-1, data); } } export * as House from './user/user';