ynu-oa
Version:
a oa API Client for YNU
62 lines (59 loc) • 1.54 kB
text/typescript
import * as process from 'node:process';
import axios from 'axios';
import * as cache from "memory-cache";
import Debug from "debug";
const debug = Debug('OA:debug');
const warn = Debug('OA:warn');
export class OAError extends Error {
constructor (public code:number, message: string) {
super(message);
this.code = code;
}
}
export type GetToken = {
/**
* 请求地址
*/
host?: string,
/**
* 用户名
*/
userName?: string,
/**
* 密码
*/
password?: string,
}
/**
* 获取token
* @returns 获得的Token
*/
export const getToken = async (options: GetToken): Promise<string> => {
const host = options.host || process.env.API_HOST;
const username = options.userName || process.env.API_USERNAME;
const password = options.password || process.env.API_PASSWORD;
const tokenCacheKey = `OA-token`;
let token = cache.get(tokenCacheKey);
if (token) {
return token;
} else {
const { data } = await axios.post<any>(`${host}/seeyon/rest/token`, {
userName: username,
password: password,
}, {
headers: {
"Content-Type": "application/json",
},
});
if (data.id) {
debug(`获取token成功::${data}`);
const token = data.id;
// 缓存token,提前5分钟过期
cache.put(tokenCacheKey, token, 3600000 - 300000);
return token;
}
warn('获取token出错:', data);
throw new OAError(-1, data);
}
}
export * as House from './user/user';