apass-opensdk-hugong 1.0.6 → 1.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/apass/object_.js CHANGED
@@ -1,69 +1,186 @@
1
- class Object_{
1
+ class Object_ {
2
2
  #hg = null
3
- constructor(hg){
3
+ constructor(hg) {
4
4
  this.#hg = hg
5
5
  }
6
6
 
7
- async clearData(table,where){
8
- await application.data.object(table).select('_id').where( where ? where : {_id : application.operator.gte(0)}).findStream(async records=>{
7
+ /**
8
+ * 清空表中满足条件的数据
9
+ * @param table 表名
10
+ * @param where 条件对象;省略时全部清空
11
+ * @param useSystemAuth 是否使用系统权限;默认 false
12
+ */
13
+ async clearData(table, where, useSystemAuth = false) {
14
+ const object = application.data.object(table).select('_id').where(where ? where : { _id: application.operator.gte(0) })
15
+ if (useSystemAuth) {
16
+ object.useSystemAuth()
17
+ }
18
+ await object.findStream(async records => {
9
19
  this.#hg.log4('clear data len', records.length)
10
- await application.data.object(table).batchDelete(records.map(it=>({_id: it._id})))
20
+ const object = application.data.object(table)
21
+ if (useSystemAuth) {
22
+ object.useSystemAuth()
23
+ }
24
+ await object.batchDelete(records.map(it => ({ _id: it._id })))
11
25
  })
12
26
  }
13
27
 
14
- async findList(table,field,where,callback,orderby){
28
+ /**
29
+ * 查询列表
30
+ * @param table 表名
31
+ * @param field 需要返回的字段,默认 ['_id','_name']
32
+ * @param where 过滤条件
33
+ * @param callback 每批记录回调;提供时方法返回 void
34
+ * @param orderby 排序字段,默认 '_id'
35
+ * @param useSystemAuth 是否使用系统权限;默认 false
36
+ * @returns 无 callback 时返回全部记录
37
+ */
38
+ async findList(table, fields, where, callback, orderby, useSystemAuth = false) {
15
39
  const list = []
16
- await application.data.object(table).select(field || ['_id','_name']).where(where || {_id : application.operator.gte(0)}).orderByDesc(orderby || '_id').findStream(async records=>{
17
- if(callback){
40
+ const object = application.data.object(table).select(fields || ['_id', '_name']).where(where || { _id: application.operator.gte(0) }).orderByDesc(orderby || '_id')
41
+ if (useSystemAuth) {
42
+ object.useSystemAuth()
43
+ }
44
+ await object.findStream(async records => {
45
+ if (callback) {
18
46
  this.#hg.log4('find all len', records.length)
19
47
  await callback(records)
20
- }else{
48
+ } else {
21
49
  this.#hg.log4('find all size', records.length)
22
50
  list.push(...records)
23
51
  }
24
52
  })
25
- if(!callback){
53
+ if (!callback) {
26
54
  this.#hg.log4('find all len', list.length)
27
55
  }
28
56
  return list
29
57
  }
30
- async findOne(table,field,where){
31
- return await application.data.object(table).select(field || ['_id','_name']).where(where || {_id : application.operator.gte(0)}).findOne()
58
+ /**
59
+ * 查询单条记录
60
+ * @param table 表名
61
+ * @param field 需要返回的字段,默认 ['_id','_name']
62
+ * @param where 过滤条件
63
+ * @param useSystemAuth 是否使用系统权限;默认 false
64
+ * @returns 记录对象或 null
65
+ */
66
+ async findOne(table, fields, where, useSystemAuth = false) {
67
+ const object = application.data.object(table).select(fields || ['_id', '_name']).where(where || { _id: application.operator.gte(0) })
68
+ if (useSystemAuth) {
69
+ object.useSystemAuth()
70
+ }
71
+ return await object.findOne()
32
72
  }
33
- async findOneById(table,id,field){
34
- return await application.data.object(table).select(field || ['_id','_name']).where({_id: id}).findOne()
73
+ /**
74
+ * 根据 ID 查询单条记录
75
+ * @param table 表名
76
+ * @param id 记录 ID
77
+ * @param fields 需要返回的字段,默认 ['_id','_name']
78
+ * @param useSystemAuth 是否使用系统权限;默认 false
79
+ * @returns 记录对象或 null
80
+ */
81
+ async findOneById(table, id, fields, useSystemAuth = false) {
82
+ const object = application.data.object(table).select(fields || ['_id', '_name']).where({ _id: id })
83
+ if (useSystemAuth) {
84
+ object.useSystemAuth()
85
+ }
86
+ return await object.findOne()
35
87
  }
36
88
 
37
- async batchCreate(table,list){
38
- if(list.length){
39
- return await application.data.object(table).useSystemAuth().batchCreate(list)
89
+ /**
90
+ * 批量创建记录
91
+ * @param table 表名
92
+ * @param list 记录列表
93
+ * @param useSystemAuth 是否使用系统权限;默认 false
94
+ * @returns 创建的记录 ID 列表或 null
95
+ */
96
+ async batchCreate(table, list, useSystemAuth = false) {
97
+ if (list.length) {
98
+ const object = application.data.object(table)
99
+ if (useSystemAuth) {
100
+ object.useSystemAuth()
101
+ }
102
+ return await object.batchCreate(list)
40
103
  }
41
104
  return null
42
105
  }
43
- async create(table,data){
44
- return await application.data.object(table).useSystemAuth().create(data)
106
+ /**
107
+ * 创建单条记录
108
+ * @param table 表名
109
+ * @param data 记录数据
110
+ * @param useSystemAuth 是否使用系统权限;默认 false
111
+ * @returns 创建的记录 ID 或 null
112
+ */
113
+ async create(table, data, useSystemAuth = false) {
114
+ const object = application.data.object(table)
115
+ if (useSystemAuth) {
116
+ object.useSystemAuth()
117
+ }
118
+ return await object.create(data)
45
119
  }
46
120
 
47
- async batchUpdate(table,list){
48
- if(list.length){
49
- return application.data.object(table).useSystemAuth().batchUpdate(list)
121
+ /**
122
+ * 批量更新记录
123
+ * @param table 表名
124
+ * @param list 记录列表
125
+ * @param useSystemAuth 是否使用系统权限;默认 false
126
+ * @returns 更新的记录 ID 列表或 null
127
+ */
128
+ async batchUpdate(table, list, useSystemAuth = false) {
129
+ if (list.length) {
130
+ const object = application.data.object(table)
131
+ if (useSystemAuth) {
132
+ object.useSystemAuth()
133
+ }
134
+ return await object.batchUpdate(list)
50
135
  }
51
136
  return null
52
137
  }
53
- async update(table,data){
54
- return application.data.object(table).useSystemAuth().update(data)
138
+ /**
139
+ * 更新单条记录
140
+ * @param table 表名
141
+ * @param data 记录数据
142
+ * @param useSystemAuth 是否使用系统权限;默认 false
143
+ * @returns 更新的记录 ID 或 null
144
+ */
145
+ async update(table, data, useSystemAuth = false) {
146
+ const object = application.data.object(table)
147
+ if (useSystemAuth) {
148
+ object.useSystemAuth()
149
+ }
150
+ return await object.update(data)
55
151
  }
56
-
57
- async delete(table,_id){
58
- return application.data.object(table).useSystemAuth().delete(_id)
152
+ /**
153
+ * 删除单条记录
154
+ * @param table 表名
155
+ * @param _id 记录 ID
156
+ * @param useSystemAuth 是否使用系统权限;默认 false
157
+ * @returns 删除的记录 ID 或 null
158
+ */
159
+ async deleteOne(table, _id, useSystemAuth = false) {
160
+ const object = application.data.object(table)
161
+ if (useSystemAuth) {
162
+ object.useSystemAuth()
163
+ }
164
+ return await object.delete(_id)
59
165
  }
60
- async delete(table,_ids){
61
- if(_ids.length){
62
- return application.data.object(table).useSystemAuth().batchDelete(_ids)
166
+ /**
167
+ * 批量删除记录
168
+ * @param table 表名
169
+ * @param _ids 记录 ID 列表
170
+ * @param useSystemAuth 是否使用系统权限;默认 false
171
+ * @returns 删除的记录 ID 列表或 null
172
+ */
173
+ async deleteBatchByIds(table, _ids, useSystemAuth = false) {
174
+ if (_ids.length) {
175
+ const object = application.data.object(table)
176
+ if (useSystemAuth) {
177
+ object.useSystemAuth()
178
+ }
179
+ return await object.batchDelete(_ids)
63
180
  }
64
181
  return null
65
182
  }
66
-
183
+
67
184
 
68
185
  }
69
186
  module.exports = Object_
package/index.d.ts CHANGED
@@ -1,90 +1,79 @@
1
- // HG.d.ts
2
- export = HG;
3
-
4
- declare class HG {
5
- constructor(logger: any);
6
-
7
- /* ── 公开属性 ──────────────────────────── */
8
- // users: import('./opensdk/users');
9
- // document: import('./opensdk/document');
10
- // employee: import('./opensdk/employee');
11
- // contract: import('./opensdk/contract');
12
- object: import('./apass/object_');
13
- utils: import('./utils/index');
14
- readonly _time: number | null;
15
-
16
- /* ── 公开方法 ──────────────────────────── */
17
- setLogger(logger: any): Promise<void>;
18
- initEnvAppId(): Promise<void>;
19
- timeRun<T = any>(fn?: () => Promise<T>): Promise<T | null>;
20
- sleep(time?: number): Promise<void>;
21
-
22
- newTime(): void;
23
- printTime(): void;
24
-
25
- setAppId(app_id: string, app_secret: string): void;
26
- getToken(): Promise<string>;
27
-
28
- requestGet(url: string, params?: any, headers?: any): Promise<any>;
29
- request(
30
- url: string | [string, any],
31
- data?: any,
32
- headers?: any,
33
- method?: string
34
- ): Promise<any>;
35
-
36
- paginatedSearchGet(
37
- url: string,
38
- params?: any,
39
- callback?: (items: any[]) => Promise<void> | void
40
- ): Promise<any[]>;
41
-
42
- paginatedSearch(
43
- url: string,
44
- params?: any,
45
- data?: any,
46
- callback?: (items: any[]) => Promise<void> | void,
47
- method?: string
48
- ): Promise<any[]>;
49
-
50
- toMultilingual(
51
- zh: string | any[],
52
- en?: string
53
- ): any;
54
-
55
- toText(textArr: Array<{ language_code: number; text: string }>): string;
56
-
57
- toSafeValue<T = any>(
58
- obj: Record<string, any> | null | undefined,
59
- key: string,
60
- defValue?: T
61
- ): T;
62
-
63
- listFind<T = any>(
64
- list: T[],
65
- key: keyof T,
66
- target: any,
67
- defValue?: T
68
- ): T;
69
-
70
- listMap<T = any>(list: T[], key: keyof T): any[];
71
-
72
- textToFloat(textAmount?: string, defValue?: number): number;
73
-
74
- toValue<T = any>(
75
- obj: Record<string, any>,
76
- path: string,
77
- fallback?: T
78
- ): T;
79
-
80
- /* ── 日志工具 ──────────────────────────── */
81
- log(...args: any[]): void;
82
- log4(...args: any[]): void;
83
- log8(...args: any[]): void;
84
- logm(space: number, ...args: any[]): void;
85
- error(...args: any[]): void;
86
- warn(...args: any[]): void;
87
-
88
- /* ── 语言转换 ──────────────────────────── */
89
- toLanguageByList(list: any[]): any[];
1
+ declare module 'HG' {
2
+ import { AxiosRequestConfig, AxiosResponse } from 'axios';
3
+
4
+ export interface HGLogger {
5
+ log: (...args: any[]) => void;
6
+ error: (...args: any[]) => void;
7
+ warn: (...args: any[]) => void;
8
+ }
9
+
10
+ export interface MultilingualData {
11
+ zh?: string;
12
+ en?: string;
13
+ }
14
+
15
+ export default class HG {
16
+ constructor(logger: HGLogger);
17
+
18
+ /* 属性 */
19
+ readonly object: any; // 对应 new Object_(this)
20
+ readonly utils: any; // 对应 new Utils(this)
21
+ private _time: number | null;
22
+
23
+ /* 公有方法 */
24
+ setLogger(logger: HGLogger): Promise<void>;
25
+
26
+ /* 计时相关 */
27
+ timeRun<T = any>(fn?: () => T | Promise<T>): Promise<T>;
28
+ newTime(): void;
29
+ printTime(): void;
30
+
31
+ /* 工具方法 */
32
+ sleep(time?: number): Promise<void>;
33
+
34
+ /* 网络请求 */
35
+ request<T = any>(config: AxiosRequestConfig): Promise<T>;
36
+ axios<T = any>(config: AxiosRequestConfig): Promise<AxiosResponse<T>>;
37
+
38
+ /* 多语言 */
39
+ toMultilingualByOpenPlatform(
40
+ zh: string | any[],
41
+ en?: string
42
+ ): application.constants.type.Multilingual;
43
+
44
+ toTextByMultilingual(
45
+ textArr: Array<{ language_code: string; text: string }>
46
+ ): string;
47
+
48
+ /* JSON 取值 */
49
+ toValue<T = any>(
50
+ obj: any,
51
+ path: string,
52
+ defaultValue?: T
53
+ ): T | undefined;
54
+
55
+ /* 数组辅助 */
56
+ listFind<T = any>(
57
+ list: T[],
58
+ key: keyof T,
59
+ target: any,
60
+ defValue?: T
61
+ ): T | undefined;
62
+
63
+ listMap<T = any, K extends keyof T = keyof T>(
64
+ list: T[],
65
+ key: K
66
+ ): Array<T[K]>;
67
+
68
+ /* 字符串转数字 */
69
+ textToFloat(textAmount: string | number | null | undefined, defValue?: number): number;
70
+
71
+ /* 日志 */
72
+ log(...arg: any[]): void;
73
+ log4(...arg: any[]): void;
74
+ log8(...arg: any[]): void;
75
+ logm(space: number, ...arg: any[]): void;
76
+ error(...arg: any[]): void;
77
+ warn(...arg: any[]): void;
78
+ }
90
79
  }
package/index.js CHANGED
@@ -1,42 +1,25 @@
1
- const Users = require('./opensdk/users')
2
- const Document = require('./opensdk/document')
3
1
  const Utils = require('./utils/index')
4
- const Employee = require('./opensdk/employee')
5
- const Contract = require('./opensdk/contract')
6
2
  const Object_ = require('./apass/object_')
7
- class HG{
3
+ class HG {
8
4
  #logger
9
- #app_id
10
- #app_secret
11
- constructor(logger){
5
+ constructor(logger) {
12
6
  this.setLogger(logger)
13
- this.users = new Users(this)
14
- this.document = new Document(this)
15
- this.employee = new Employee(this)
16
- this.contract = new Contract(this)
17
7
  this.object = new Object_(this)
18
-
19
8
  this.utils = new Utils(this)
20
9
  this._time = null
21
10
  }
22
- async setLogger(logger){
11
+ async setLogger(logger) {
23
12
  this.#logger = logger
24
- await this.initEnvAppId()
25
- }
26
- async initEnvAppId(){
27
- this.#app_id = await application.globalVar.getVar('app_id')
28
- this.#app_secret =await application.globalVar.getVar('app_secret')
29
- this.log4(`app_id=${this.#app_id},app_secret=${this.#app_secret}`)
30
13
  }
31
14
  /**
32
15
  * 运行函数
33
16
  * @param {*} fn
34
17
  * @returns
35
18
  */
36
- async timeRun(fn){
19
+ async timeRun(fn) {
37
20
  this.newTime()
38
21
  let result = null
39
- if(fn){
22
+ if (fn) {
40
23
  result = await fn()
41
24
  }
42
25
  this.printTime()
@@ -47,16 +30,16 @@ class HG{
47
30
  * @param {*} time 毫秒
48
31
  * @returns
49
32
  */
50
- async sleep(time){
51
- return new Promise((r)=>setTimeout(()=>{ this.log4(`sleep ${(time || 1000)/1000}s`);r();},time || 1000))
33
+ async sleep(time) {
34
+ return new Promise((r) => setTimeout(() => { this.log4(`sleep ${(time || 1000) / 1000}s`); r(); }, time || 1000))
52
35
  }
53
36
 
54
37
  /**
55
38
  * 时间计划-记录
56
39
  */
57
- newTime(){
58
- if(this._time){
59
- this.log4('#time reset to before',(Date.now() - this._time)/1000, 's')
40
+ newTime() {
41
+ if (this._time) {
42
+ this.log4('#time reset to before', (Date.now() - this._time) / 1000, 's')
60
43
  }
61
44
  this.log4('#time reset')
62
45
  this._time = Date.now()
@@ -64,250 +47,107 @@ class HG{
64
47
  /**
65
48
  * 时间计划-打印耗时
66
49
  */
67
- printTime(){
68
- if(!this._time){
69
- return this.#logger.error('#time Error','The time has not been initialized ')
70
- }
71
- this.log4('#time',(Date.now() - this._time)/1000, 's')
72
- }
73
-
74
- /**
75
- * 设置app_id
76
- * @param {*} app_id
77
- * @param {*} app_secret
78
- */
79
- setAppId(app_id,app_secret){
80
- this.#app_id = app_id
81
- this.#app_secret = app_secret
82
- }
83
-
84
- /**
85
- * 开平token
86
- * @returns
87
- */
88
- async getToken(){
89
- if(!this.#app_id){
90
- await this.initEnvAppId()
50
+ printTime() {
51
+ if (!this._time) {
52
+ return this.#logger.error('#time Error', 'The time has not been initialized ')
91
53
  }
92
- 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)
93
- return result.tenant_access_token
94
- }
95
-
96
- async requestGet(url, params, headers=true){
97
- return this.request([url, params], null, headers, 'GET')
54
+ this.log4('#time', (Date.now() - this._time) / 1000, 's')
98
55
  }
99
56
 
100
57
  /**
101
- * 统一网络请求
102
- * @param {*} url
103
- * @param {*} params
104
- * @param {*} data
105
- * @param {*} headers
106
- * @param {*} method
58
+ * 统一网络请求(使用axios)
59
+ * @param {*} config
107
60
  * @returns
108
61
  */
109
- async request(url, data, headers = true, method = 'POST'){
110
- let newHeaders = { 'Content-Type': 'application/json; charset=utf-8' }
111
- if(typeof headers === 'boolean' && headers === true){
112
- newHeaders['Authorization'] = `Bearer ${ await this.getToken() }`
113
- }else{
114
- newHeaders = { ...newHeaders,...(headers || {}) }
115
- }
116
- this.log4('req =',url,data,newHeaders)
117
- let _url = url
118
- let params = null
119
- if(Array.isArray(url)){
120
- _url = url[0]
121
- params = url[1]
122
- }
123
- return new Promise((r,s)=>{
62
+ async request(config) {
63
+ this.log4('req =', config)
64
+ return new Promise((r, s) => {
124
65
  const now = Date.now()
125
- axios({ method, params, url: _url, data, headers: newHeaders}).then(response=>{
126
- this.log8('resp =',(Date.now() - now) / 1000, 's',response.status, response.statusText,response.data)
66
+ axios(config).then(response => {
67
+ this.log8('resp =', (Date.now() - now) / 1000, 's', response.status, response.statusText, response.data)
127
68
  r(response.data)
128
- }).catch(e=>{
129
- console.log(e)
130
- this.#logger.error('resp =',(Date.now() - now) / 1000, 's',e.response.data)
131
- s(e.response.data)
69
+ }).catch(err => {
70
+ this.#logger.error('resp =', (Date.now() - now) / 1000, 's', err.response.data)
71
+ s(err.response.data)
132
72
  })
133
73
  })
134
74
  }
135
75
  /**
136
- * 分页返回开放平台数据
137
- * @param {*} url
138
- * @param {*} params
139
- * @param {*} callback callback(items) 结果回调(根据总数可能多次调用)- 可选
140
- * @returns 如果callback为传递则一次性返回所有的数据
141
- */
142
- async paginatedSearchGet(url,params,callback){
143
- return this.paginatedSearch(url, params, null, callback, 'GET')
144
- }
145
- /**
146
- * 分页返回开放平台数据
147
- * @param {*} url
148
- * @param {*} params
149
- * @param {*} data
150
- * @param {*} callback callback(items) 结果回调(根据总数可能多次调用)- 可选
151
- * @returns 如果callback为传递则一次性返回所有的数据
76
+ * 直接调用axios
77
+ * @param {*} config
78
+ * @returns
152
79
  */
153
- async paginatedSearch(url,params,data,callback,method='POST'){
154
- let list = []
155
- let page_token = null
156
- let has_more = false
157
- do {
158
- const result = await this.request([url, {...(params || {page_size: 100}), page_token}],data,true,method)
159
- page_token = result.data.page_token
160
- has_more = result.data.has_more
161
- if(callback){
162
- await callback(result.data.hasOwnProperty('items') ? result.data.items || [] : result.data)
163
- }else{
164
- if(result.data.hasOwnProperty('items')){
165
- list.push(...(result.data.items || []))
166
- }else{
167
- list.push(result.data)
168
- }
169
- }
170
- } while (has_more);
171
- return list
80
+ axios(config) {
81
+ return axios(config)
172
82
  }
173
-
174
83
  /**
175
- * 生成多语言对象
84
+ * 生成多语言对象(将开放平台返回的多语言对象转换为application.constants.type.Multilingual)
176
85
  * @param {*} zh
177
86
  * @param {*} en
178
87
  * @returns
179
88
  */
180
- toMultilingual(zh,en){
181
- if(Array.isArray(zh)){
182
- //开放平台一般返回内容
183
- if(zh[0].hasOwnProperty('lang')){
184
- const _zh = this.toSafeValue(zh.find(it=>it.lang == 'zh-CN'),'value')
185
- const _en = this.toSafeValue(zh.find(it=>it.lang == 'en-US'),'value')
89
+ toMultilingualByOpenPlatform(zh, en) {
90
+ if (Array.isArray(zh)) {
91
+ if (zh[0].hasOwnProperty('lang')) {
92
+ const _zh = this.toValue(zh.find(it => it.lang == 'zh-CN'), 'value')
93
+ const _en = this.toValue(zh.find(it => it.lang == 'en-US'), 'value')
186
94
  return new application.constants.type.Multilingual({ zh: _zh || _en, en: _en || _zh })
187
95
  }
188
- if(zh[0].hasOwnProperty('locale')){
189
- const _zh = this.toSafeValue(zh.find(it=>it.locale == 'zh_CN' || it.locale == 'zh-CN'),'value')
190
- const _en = this.toSafeValue(zh.find(it=>it.locale == 'en_US' || it.locale == 'en-US'),'value')
96
+ if (zh[0].hasOwnProperty('locale')) {
97
+ const _zh = this.toValue(zh.find(it => it.locale == 'zh_CN' || it.locale == 'zh-CN'), 'value')
98
+ const _en = this.toValue(zh.find(it => it.locale == 'en_US' || it.locale == 'en-US'), 'value')
191
99
  return new application.constants.type.Multilingual({ zh: _zh || _en, en: _en || _zh })
192
100
  }
193
101
  }
194
102
  return new application.constants.type.Multilingual({ zh: zh || en, en: en || zh })
195
103
  }
196
-
197
- toText(textArr){
198
- if(!textArr || !textArr.length) return '--'
199
- return textArr.find(it=>it.language_code == '2052').text
200
- }
201
-
202
104
  /**
203
- * 安全的取值
204
- * @param {*} obj
205
- * @param {*} key
206
- * @param {*} defValue
105
+ * 从多语言对象中获取中文
106
+ * @param {*} textArr
207
107
  * @returns
208
108
  */
209
- toSafeValue(obj,key,defValue){
210
- const _obj = obj || {}
211
- if(!_obj){
212
- return defValue
213
- }
214
- if(!_obj.hasOwnProperty(key)){
215
- return defValue
216
- }
217
- return _obj[key] || defValue
218
- }
219
-
220
- listFind(list,key,target,defValue){
221
- return list.find(it=>it[ key ] == target) || defValue
222
- }
223
- listMap(list,key){
224
- return list.map(it=>it[ key ])
225
- }
226
-
227
- textToFloat(textAmount,defValue = 0) {
228
- return parseFloat((textAmount || '').replace(/,/g, '') || defValue);
109
+ toTextByMultilingual(textArr) {
110
+ if (!textArr || !textArr.length) return '--'
111
+ return textArr.find(it => it.language_code == '2052').text
229
112
  }
230
-
231
-
232
113
  /**
233
- * 从JSON中进行取值
114
+ * 从JSON中根据路径获取值
234
115
  * @param {*} obj
235
116
  * @param {*} path
236
- * @param {*} fallback
117
+ * @param {*} defaultValue
237
118
  * @returns
238
119
  */
239
- toValue(obj, path, fallback = undefined) {
240
- return path.split('.').reduce((acc, key) => acc?.[key], obj) ?? fallback;
120
+ toValue(obj, path, defaultValue = undefined) {
121
+ return path.split('.').reduce((acc, key) => acc?.[key], obj) ?? defaultValue;
122
+ }
123
+ listFind(list, key, target, defValue) {
124
+ return list.find(it => it[key] == target) || defValue
125
+ }
126
+ listMap(list, key) {
127
+ return list.map(it => it[key])
128
+ }
129
+ textToFloat(textAmount, defValue = 0) {
130
+ return parseFloat((textAmount || '').replace(/,/g, '') || defValue);
241
131
  }
242
132
 
243
- log(...arg){
133
+ log(...arg) {
244
134
  this.#logger.log(...arg)
245
135
  }
246
- log4(...arg){
247
- this.logm(4,...arg)
136
+ log4(...arg) {
137
+ this.logm(4, ...arg)
248
138
  }
249
- log8(...arg){
250
- this.logm(8,...arg)
139
+ log8(...arg) {
140
+ this.logm(8, ...arg)
251
141
  }
252
- logm(space,...arg){
142
+ logm(space, ...arg) {
253
143
  const result = ''.padEnd(space, "-");
254
- this.#logger.log(result,...arg)
144
+ this.#logger.log(result, ...arg)
255
145
  }
256
- error(...arg){
146
+ error(...arg) {
257
147
  this.#logger.error(...arg)
258
148
  }
259
- warn(...arg){
149
+ warn(...arg) {
260
150
  this.#logger.warn(...arg)
261
151
  }
262
-
263
- toLanguageByList(list){
264
- // 定义语言代码映射
265
- const languageMap = {
266
- 1033: "en_us",
267
- 2052: "zh_cn"
268
- };
269
- // 递归处理函数
270
- const processJson = (data) => {
271
- const result = [];
272
-
273
- data.forEach(item => {
274
- const newItem = {};
275
- for (const key in item) {
276
- const value = item[key];
277
- if (Array.isArray(value)) {
278
- // 如果是数组,处理数组中的每个对象
279
- const newList = value.map(entry => {
280
- if (entry.language_code in languageMap) {
281
- return { [languageMap[entry.language_code]]: entry.text };
282
- }
283
- return null; // 如果 language_code 不在映射中,则忽略
284
- }).filter(Boolean); // 过滤掉 null 值
285
- if (newList.length > 0) {
286
- newItem[key] = newList.reduce((obj,item)=>({...obj, ...item}),{});
287
- }
288
- } else if (typeof value === 'object' && value !== null) {
289
- // 如果是对象,递归处理
290
- const processedValue = processJson([value])[0];
291
- //console.log('processedValue',processedValue)
292
- if (Object.keys(processedValue).length > 0) {
293
- newItem[key] = processedValue;
294
- }
295
- }else{
296
- newItem[key] = value
297
- }
298
- }
299
- if (Object.keys(newItem).length > 0) {
300
- result.push(newItem);
301
- }
302
- });
303
- return result;
304
- };
305
- // 调用处理函数
306
- const processedData = processJson(list);
307
- return processedData
308
- }
309
-
310
-
311
-
312
152
  }
313
153
  module.exports = HG
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "apass-opensdk-hugong",
3
- "version": "1.0.6",
3
+ "version": "1.0.7",
4
4
  "description": "飞书Apass低代码平台-飞书开放平台-相关的接口整合和常用的方法整合",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
package/readme.md CHANGED
@@ -1,44 +1,13 @@
1
1
  # apass-opensdk-hugong
2
2
  ## 简介
3
- apass-opensdk-hugong 是一个基于apass-opensdk的封装,提供了一些常用的功能
3
+ apass-opensdk-hugong 是一个Nodejs的SDK,提供了一些常用的功能
4
4
  - 什么人可以使用这个SDK
5
- - 从事飞书低代码平台(APASS)开发人员.
5
+ - 从事飞书低代码平台(APASS)开发人员.传统Nodejs开发人员.
6
6
 
7
7
  ## 安装
8
8
 
9
9
  ```
10
10
  在飞书低代码平台(云函数)依赖管理-右侧-搜索: apass-opensdk-hugong
11
-
12
- 最近有同学私聊我说Apass无法安装1.0.0以上的包,解决思路: 先安装1.0.0版本,然后打开yarn.lock文件
13
- ====== 找到这一行 =====
14
- apass-opensdk-hugong@1.0.0:
15
- version "1.0.0"
16
- resolved "https://registry.npmmirror.com/apass-opensdk-hugong/-/apass-opensdk-hugong-1.0.0.tgz#ef2d0a19e793358784cb764de4b885fd86befd66"
17
- integrity sha512-Q8Gpo9v8a/2G43y/Lh2POyDEOcealFuUlGdqGSA9wyfjET4+LWs/PnzK9EB1YZCjQotW7cGO/9a0MiQ6Sgw1LA==
18
- ====== 找到这一行 =====
19
-
20
- 将版本改为最新的版本号后,然后保存,重写部署即可使用NPM源最新的版本
21
- 修改后的yarn.lock文件如下, 一共三处地方:
22
- apass-opensdk-hugong@1.0.3:
23
- version "1.0.3"
24
- resolved "https://registry.npmmirror.com/apass-opensdk-hugong/-/apass-opensdk-hugong-1.0.3.tgz#ef2d0a19e793358784cb764de4b885fd86befd66"
25
- integrity sha512-Q8Gpo9v8a/2G43y/Lh2POyDEOcealFuUlGdqGSA9wyfjET4+LWs/PnzK9EB1YZCjQotW7cGO/9a0MiQ6Sgw1LA==
26
-
27
-
28
- ======
29
- package.json
30
- {
31
- "dependencies": {
32
- "apass-opensdk-hugong": "1.0.0"
33
- }
34
- }
35
- //改成
36
- {
37
- "dependencies": {
38
- "apass-opensdk-hugong": "1.0.5"
39
- }
40
- }
41
- 部署后刷新页面即可生效
42
11
  ```
43
12
 
44
13
  ## 如何使用
@@ -47,13 +16,14 @@ const Hugong = require('apass-opensdk-hugong');
47
16
  初始化(主函数内),函数外不需要入参logger
48
17
  const hg = new Hugong(logger)
49
18
 
50
- 如果在外部初始化后需要在函数中初始化logger模块
19
+ 也可以单独初始化logger模块
51
20
  hg.setLogger(logger)
52
21
  ```
53
22
  ## 常用
54
23
  ```
55
- 显示运行时间
24
+ 记录时间
56
25
  hg.newTime()
26
+ 打印运行时间
57
27
  hg.printTime()
58
28
 
59
29
  安全的取值
@@ -78,7 +48,7 @@ await hg.utils.splitArray([...], 10, async (items)=>{ // do something })
78
48
  hg.utils.unique([1,2,3,1,2,3]) // [1,2,3]
79
49
 
80
50
  ```
81
- ## 文件上传/下载
51
+ ## Apass相关,文件上传/下载
82
52
 
83
53
  ```
84
54
  1)从网络下载文件后上传到飞书租户空间,返回上传后的文件信息
@@ -115,73 +85,11 @@ list是excel所有的内容,建议小文件使用(10M以下),如果是大文
115
85
  ```
116
86
  对象数据新增多语言对象
117
87
 
118
- 生成多语言对象
119
- hg.toMultilingual([{ lang: 'en-US', value: 'Regular' },{ lang: 'zh-CN', value: '正式' }]) 常用于开放平台返回的多语言数据转换
120
- hg.toMultilingual(zh,en)
121
-
122
-
123
-
124
- ```
125
-
126
- ## 飞书人事
127
-
128
- 搜索员工信息
129
-
130
- ```
131
- 设置appid和appsecret
132
- await hg.setAppId('cli_000000000','0000000000000')
133
-
134
- /**
135
- * 搜索员工信息
136
- * @param {*} params
137
- * @param {*} data
138
- * @param {*} callback callback(items) 结果回调(根据总数可能多次调用)- 可选
139
- * @returns 如果callback为传递则一次性返回所有的数据
140
- */
141
- await hg.employee.search(params,data,callback)
142
-
143
- // 示例[具体参数请参考开放平台定义](https://open.feishu.cn/document/server-docs/corehr-v1/employee/search)
144
- await hg.employee.search({ page_size:100,user_id_type:'user_id',},{ /* 要查询的字段 */}, async (items)=>{
145
- // do something 假设服务端有300条数据,每次返回100条,会调用3次, 如果希望一次性返回所有数据,callback传null即可
146
- })
147
- const list = await hg.employee.search(params,data) //这将一次性返回所有数据
148
- ```
149
- ## 开放平台分页获取所有数据
150
-
151
- 所有的分页接口都可以使用
88
+ 生成多语言对象(将开放平台返回的多语言对象转换为application.constants.type.Multilingual)
89
+ hg.toMultilingualByOpenPlatform([{ lang: 'en-US', value: 'Regular' },{ lang: 'zh-CN', value: '正式' }])
90
+ hg.toMultilingualByOpenPlatform(zh,en)
152
91
 
153
92
  ```
154
- 设置appid和appsecret
155
- await hg.setAppId('cli_000000000','0000000000000')
156
-
157
- /**
158
- * GET类型接口分页返回开放平台数据
159
- * @param {*} url
160
- * @param {*} params
161
- * @param {*} callback callback(items) 结果回调(根据总数可能多次调用)- 可选
162
- * @returns callback为null,则一次性返回所有的数据
163
- */
164
- hg.paginatedSearchGet(url,params,callback)
165
-
166
- /**
167
- * POST接口分页返回开放平台数据
168
- * @param {*} url
169
- * @param {*} params
170
- * @param {*} data
171
- * @param {*} callback callback(items) 结果回调(根据总数可能多次调用)- 可选
172
- * @returns callback为null,则一次性返回所有的数据
173
- */
174
- await hg.paginatedSearch(url,params,data,callback)
175
-
176
- 示例1
177
- const list = await hg.paginatedSearchGet(url, params, data)
178
- 示例2
179
- await hg.paginatedSearchGet(url, params, async (items)=>{
180
- // do something 假设服务端有300条数据,每次返回100条,会调用3次, 如果希望一次性返回所有数据,callback传null即可
181
- })
182
- ```
183
-
184
-
185
93
 
186
94
  ## 交流学习
187
95
 
package/utils/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  const Url = require('./url')
2
2
  const File_ = require('./file_')
3
3
  const Date_ = require('./date_')
4
- class Utils{
4
+ class Utils {
5
5
  #hg = null
6
- constructor(hg){
6
+ constructor(hg) {
7
7
  this.#hg = hg
8
8
 
9
9
  this.url = new Url(hg)
@@ -18,13 +18,13 @@ class Utils{
18
18
  * @param {*} callback(item) 分割后回调(不传递则方法返回切割长度后的数组)
19
19
  * @returns
20
20
  */
21
- async splitArray(list, chunkSize, callback) {
21
+ async splitArray(list, chunkSize, callback) {
22
22
  const result = [];
23
23
  this.#hg.log4('splitArray len ', list.length)
24
24
  for (let i = 0; i < list.length; i += chunkSize) {
25
25
  const batch = list.slice(i, i + chunkSize)
26
- this.#hg.log8('splitArray item ',i, i + chunkSize)
27
- if(callback){
26
+ this.#hg.log8('splitArray item ', i, i + chunkSize)
27
+ if (callback) {
28
28
  await callback(batch)
29
29
  continue
30
30
  }
@@ -33,7 +33,7 @@ class Utils{
33
33
  return result;
34
34
  }
35
35
 
36
- toMD5(data){
36
+ toMD5(data) {
37
37
  const crypto = require('crypto');
38
38
  const hash = crypto.createHash('md5');
39
39
  hash.update(data);
@@ -50,8 +50,8 @@ class Utils{
50
50
  * @param {*} currency
51
51
  * @returns
52
52
  */
53
- formatCurrency(amount, locale = 'en-US', currency = 'USD') {
54
- return new Intl.NumberFormat(locale, { style: 'currency', currency, }).format(amount);
53
+ formatCurrency(amount, locale = 'en-US', currency = 'USD') {
54
+ return new Intl.NumberFormat(locale, { style: 'currency', currency, }).format(amount);
55
55
  }
56
56
 
57
57
  /**
@@ -60,7 +60,7 @@ class Utils{
60
60
  * @param {*} size
61
61
  * @returns
62
62
  */
63
- chunkAll(arr, size) {
63
+ chunkAll(arr, size) {
64
64
  return Array.from({ length: Math.ceil(arr.length / size) }, (_, i) => arr.slice(i * size, i * size + size));
65
65
  }
66
66
 
@@ -72,10 +72,10 @@ class Utils{
72
72
  * @param {*} step
73
73
  * @returns
74
74
  */
75
- range(start, end, step = 1) {
75
+ range(start, end, step = 1) {
76
76
  return Array.from({ length: (end - start) / step + 1 }, (_, i) => start + i * step);
77
77
  }
78
-
78
+
79
79
  /**
80
80
  * 移除重复项
81
81
  * @param {*} arr
@@ -1,17 +0,0 @@
1
- class Contract{
2
- #hg = null
3
- constructor(hg){
4
- this.#hg = hg
5
- }
6
-
7
- /**
8
- * 通过手机号或邮箱获取用户 ID
9
- * @param {*} user_id_type user_id、open_id、union_id
10
- * @returns
11
- */
12
- async batch_get_id(data,user_id_type){
13
- return await this.#hg.request(`https://open.feishu.cn/open-apis/contact/v3/users/batch_get_id?user_id_type=${user_id_type || 'open_id'}`,data,true)
14
- }
15
-
16
- }
17
- module.exports = Contract
@@ -1,46 +0,0 @@
1
- class Document{
2
- #hg = null
3
- constructor(hg){
4
- this.#hg = hg
5
- }
6
- /**
7
- * 增加协作者权限 https://open.feishu.cn/document/server-docs/docs/permission/permission-member/create
8
- * @param {*} app_token app_token 多维表格 App 的唯一标识
9
- * @param {*} type 文件类型 bitable:多维表格
10
- * @param {*} data {
11
- "member_type": "openchat",
12
- "member_id": "oc_b962e8debdc37712a1d60bb97087a8e8",
13
- "perm": "edit",
14
- "perm_type": "container",
15
- "type": "chat"
16
- }
17
- */
18
- async permissions(app_token,type,data){
19
- if(!type){
20
- throw 'type is not empty'
21
- }
22
- return await this.#hg.request(`https://open.feishu.cn/open-apis/drive/v1/permissions/${app_token}/members?type=${type}&need_notification=false`,data,true)
23
- }
24
- /**
25
- * 复制多维表格 https://open.feishu.cn/document/server-docs/docs/bitable-v1/app/copy
26
- * @param {*} app_token 要复制的多维表格 App 的唯一标识
27
- * @param {*} name 多维表格 App 名称。最长为 255 个字符
28
- * @param {*} folder_token 文件夹
29
- * @returns
30
- */
31
- async copy(app_token,name,folder_token,without_content,time_zone){
32
- return await this.#hg.request(`https://open.feishu.cn/open-apis/bitable/v1/apps/${app_token}/copy`,{ name,folder_token,without_content: without_content || false,time_zone: time_zone || 'Asia/Shanghai' },true)
33
- }
34
- /**
35
- * 创建多维表格 https://open.feishu.cn/document/server-docs/docs/bitable-v1/app/create
36
- * @param {*} name 多维表格 App 名称
37
- * @param {*} folder_token 多维表格 App 归属文件夹
38
- * @param {*} time_zone
39
- * @returns
40
- */
41
- async create(name, folder_token, time_zone){
42
- return await this.#hg.request('https://open.feishu.cn/open-apis/bitable/v1/apps',{ name, folder_token, time_zone: time_zone || 'Asia/Shanghai' },true)
43
- }
44
-
45
- }
46
- module.exports = Document
@@ -1,34 +0,0 @@
1
- class Employee{
2
- #hg = null
3
- constructor(hg){
4
- this.#hg = hg
5
- }
6
-
7
- /**
8
- * 搜索员工信息
9
- * @param {*} params
10
- * @param {*} data
11
- * @param {*} callback(items) 结果回调(根据总数可能多次调用)
12
- */
13
- async search(params,data,callback){
14
- return await this.#hg.paginatedSearch(`https://open.feishu.cn/open-apis/corehr/v2/employees/search`,params,data,callback)
15
- }
16
-
17
- /**
18
- * 批量查询员工薪资档案
19
- * @param {*} _id
20
- * @param {*} user_id
21
- */
22
- async archives_query(effective_start_date,effective_end_date,user_id_list,user_id_type){
23
- return await this.#hg.paginatedSearch(`https://open.feishu.cn/open-apis/compensation/v1/archives/query`, {
24
- page_size,
25
- user_id_type: 'people_corehr_id',
26
- },{
27
- user_id_list,
28
- effective_start_date,
29
- effective_end_date,
30
- })
31
- }
32
-
33
- }
34
- module.exports = Employee
package/opensdk/users.js DELETED
@@ -1,17 +0,0 @@
1
- class Users{
2
- #hg = null
3
- constructor(hg){
4
- this.#hg = hg
5
- }
6
-
7
- /**
8
- * 通过手机号或邮箱获取用户 ID
9
- * @param {*} user_id_type user_id、open_id、union_id
10
- * @returns
11
- */
12
- async batch_get_id(data,user_id_type){
13
- return await this.#hg.request(`https://open.feishu.cn/open-apis/contact/v3/users/batch_get_id?user_id_type=${user_id_type || 'open_id'}`,data,true)
14
- }
15
-
16
- }
17
- module.exports = Users