UNPKG

apass-opensdk-hugong

Version:

飞书Apass低代码平台-飞书开放平台-相关的接口整合和常用的方法整合

232 lines (220 loc) 6.32 kB
const Users = require('./opensdk/users') const Document = require('./opensdk/document') const Utils = require('./utils/index') const Employee = require('./opensdk/employee') const Contract = require('./opensdk/contract') const Object_ = require('./apass/object_') class HG{ #logger #app_id #app_secret constructor(logger){ this.setLogger(logger) this.users = new Users(this) this.document = new Document(this) this.employee = new Employee(this) this.contract = new Contract(this) this.object = new Object_(this) this.utils = new Utils(this) this._time = null } setLogger(logger){ this.#logger = logger } /** * 运行函数 * @param {*} fn * @returns */ async timeRun(fn){ this.newTime() let result = null if(fn){ result = await fn() } this.printTime() return result } /** * 线程睡眠 * @param {*} time 毫秒 * @returns */ async sleep(time){ return new Promise((r)=>setTimeout(()=>{ this.log4(`sleep ${(time || 1000)/1000}s`);r();},time || 1000)) } /** * 时间计划-记录 */ newTime(){ if(this._time){ this.log4('#time reset to before',(Date.now() - this._time)/1000, 's') } this.log4('#time reset') this._time = Date.now() } /** * 时间计划-打印耗时 */ printTime(){ if(!this._time){ return this.#logger.error('#time Error','The time has not been initialized ') } this.log4('#time',(Date.now() - this._time)/1000, 's') } /** * 设置app_id * @param {*} app_id * @param {*} app_secret */ setAppId(app_id,app_secret){ this.#app_id = app_id this.#app_secret = app_secret } /** * 开平token * @returns */ async getToken(){ const result = await this.request('https://open.feishu.cn/open-apis/auth/v3/app_access_token/internal',{ app_id: this.#app_id, app_secret: this.#app_secret},false) return result.tenant_access_token } async requestGet(url, params, headers=true){ return this.request([url, params], null, headers, 'GET') } /** * 统一网络请求 * @param {*} url * @param {*} params * @param {*} data * @param {*} headers * @param {*} method * @returns */ async request(url, data, headers = true, method = 'POST'){ let newHeaders = { 'Content-Type': 'application/json; charset=utf-8' } if(typeof headers === 'boolean' && headers === true){ newHeaders['Authorization'] = `Bearer ${ await this.getToken() }` }else{ newHeaders = { ...newHeaders,...(headers || {}) } } this.log4('req =',url,data,newHeaders) let _url = url let params = null if(Array.isArray(url)){ _url = url[0] params = url[1] } return new Promise((r,s)=>{ const now = Date.now() axios({ method, params, url: _url, data, headers: newHeaders}).then(response=>{ this.log8('resp =',(Date.now() - now) / 1000, 's',response.status, response.statusText,response.data) r(response.data) }).catch(e=>{ console.log(e) this.#logger.error('resp =',(Date.now() - now) / 1000, 's',e.response.data) s(e.response.data) }) }) } /** * 分页返回开放平台数据 * @param {*} url * @param {*} params * @param {*} callback callback(items) 结果回调(根据总数可能多次调用)- 可选 * @returns 如果callback为传递则一次性返回所有的数据 */ async paginatedSearchGet(url,params,callback){ return this.paginatedSearch(url, params, null, callback, 'GET') } /** * 分页返回开放平台数据 * @param {*} url * @param {*} params * @param {*} data * @param {*} callback callback(items) 结果回调(根据总数可能多次调用)- 可选 * @returns 如果callback为传递则一次性返回所有的数据 */ async paginatedSearch(url,params,data,callback,method='POST'){ let list = [] let page_token = null let has_more = false do { const result = await this.request([url, {...(params || {page_size: 100}), page_token}],data,true,method) page_token = result.data.page_token has_more = result.data.has_more if(callback){ await callback(result.data.hasOwnProperty('items') ? result.data.items || [] : result.data) }else{ if(result.data.hasOwnProperty('items')){ list.push(...(result.data.items || [])) }else{ list.push(result.data) } } } while (has_more); return list } /** * 生成多语言对象 * @param {*} zh * @param {*} en * @returns */ toMultilingual(zh,en){ if(Array.isArray(zh)){ //开放平台一般返回内容 if(zh[0].hasOwnProperty('lang')){ const _zh = this.toSafeValue(zh.find(it=>it.lang == 'zh-CN'),'value') const _en = this.toSafeValue(zh.find(it=>it.lang == 'en-US'),'value') return new application.constants.type.Multilingual({ zh: _zh || _en, en: _en || _zh }) } if(zh[0].hasOwnProperty('locale')){ const _zh = this.toSafeValue(zh.find(it=>it.locale == 'zh_CN'),'value') const _en = this.toSafeValue(zh.find(it=>it.locale == 'en_US'),'value') return new application.constants.type.Multilingual({ zh: _zh || _en, en: _en || _zh }) } } return new application.constants.type.Multilingual({ zh: zh || en, en: en || zh }) } /** * 安全的取值 * @param {*} obj * @param {*} key * @param {*} defValue * @returns */ toSafeValue(obj,key,defValue){ const _obj = obj || {} if(!_obj){ return defValue } if(!_obj.hasOwnProperty(key)){ return defValue } return _obj[key] || defValue } listFind(list,key,target,defValue){ return list.find(it=>it[ key ] == target) || defValue } listMap(list,key){ return list.map(it=>it[ key ]) } textToFloat(textAmount,defValue = 0) { return parseFloat((textAmount || '').replace(/,/g, '') || defValue); } log(...arg){ this.#logger.log(...arg) } log4(...arg){ this.logm(4,...arg) } log8(...arg){ this.logm(8,...arg) } logm(space,...arg){ const result = ''.padEnd(space, "-"); this.#logger.log(result,...arg) } } module.exports = HG