Skip to content

Commit

Permalink
update prettier print width
Browse files Browse the repository at this point in the history
  • Loading branch information
adaex authored Sep 28, 2021
1 parent 3ce6dff commit 17329dd
Show file tree
Hide file tree
Showing 13 changed files with 320 additions and 67 deletions.
2 changes: 1 addition & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@
"@typescript-eslint/explicit-function-return-type": "off",
"@typescript-eslint/explicit-module-boundary-types": "off"
}
}
}
1 change: 0 additions & 1 deletion .prettierrc.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
{
"printWidth": 160,
"semi": false,
"singleQuote": true
}
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,11 @@ yarn add coa-wx-work
### 使用

```typescript
import { WxWorkBin, WxWorkDepartmentService, WxWorkMemberService } from 'coa-wx-work'
import {
WxWorkBin,
WxWorkDepartmentService,
WxWorkMemberService,
} from 'coa-wx-work'

// Bin实例,任何服务都必须依赖此实例
const bin = new WxWorkBin()
Expand Down
30 changes: 25 additions & 5 deletions src/base/WxWorkBin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,21 @@ export class WxWorkBin {
return this.wxResponseResult(res, allow)
}

async post(url: string, data: WxWork.Dic, params: WxWork.Dic = {}, config: Axios.AxiosRequestConfig = {}, allow: number[] = []) {
const res = await axios(url, { params, data, baseURL, method: 'POST', proxy: false, ...config })
async post(
url: string,
data: WxWork.Dic,
params: WxWork.Dic = {},
config: Axios.AxiosRequestConfig = {},
allow: number[] = []
) {
const res = await axios(url, {
params,
data,
baseURL,
method: 'POST',
proxy: false,
...config,
})
return this.wxResponseResult(res, allow)
}

Expand All @@ -29,7 +42,8 @@ export class WxWorkBin {
if (info.errcode) {
const message = _.toString(info.errmsg) || '企业微信服务返回错误'
const code = _.toNumber(info.errcode) || 0
if (!allow.includes(code)) CoaError.throw('WxWork.Error.' + info.errcode, message)
if (!allow.includes(code))
CoaError.throw('WxWork.Error.' + info.errcode, message)
}
return $.camelCaseKeys(info)
}
Expand All @@ -42,8 +56,14 @@ export class WxWorkBin {
const prefix = `--${BOUNDARY}${BREAK}Content-Disposition: form-data; name="${key}"; filename="${filename}"${BREAK}Content-Type: application/octet-stream${BREAK}${BREAK}`
const suffix = `${BREAK}--${BOUNDARY}--${BREAK}`

const headers = { 'content-type': 'multipart/form-data; boundary=' + BOUNDARY }
const data = Buffer.concat([Buffer.from(prefix), readFileSync(filepath), Buffer.from(suffix)])
const headers = {
'content-type': 'multipart/form-data; boundary=' + BOUNDARY,
}
const data = Buffer.concat([
Buffer.from(prefix),
readFileSync(filepath),
Buffer.from(suffix),
])

return { headers, data }
}
Expand Down
29 changes: 23 additions & 6 deletions src/base/WxWorkServiceAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,25 @@ export class WxWorkServiceAuth extends WxWorkService {
}

// 上传临时素材
async uploadMedia(filepath: string, type: 'image' | 'voice' | 'video' | 'file'): Promise<{ type: string; mediaId: string; createdAt: string }> {
async uploadMedia(
filepath: string,
type: 'image' | 'voice' | 'video' | 'file'
): Promise<{ type: string; mediaId: string; createdAt: string }> {
const { data, headers } = this.bin.parseUploadFile(filepath, 'media')
const access_token = await this.getToken()
return await this.bin.post('/cgi-bin/media/upload', data, { access_token, type }, { headers })
return await this.bin.post(
'/cgi-bin/media/upload',
data,
{ access_token, type },
{ headers }
)
}

// 解密
decrypt(encrypted: string) {
const aesKey = this.agent.aesKey ?? CoaError.message('WxWork.Missing', '缺少AesKey,无法解析数据')
const aesKey =
this.agent.aesKey ??
CoaError.message('WxWork.Missing', '缺少AesKey,无法解析数据')
const { message } = decrypt(aesKey, encrypted)
return message
}
Expand Down Expand Up @@ -53,7 +63,10 @@ export class WxWorkServiceAuth extends WxWorkService {
// 获取Token
async getToken() {
const cacheName = `WxWorkToken:${this.agent.corpId}:${this.agent.agentId}`
let result = (await this.bin.storage.get<WxWork.Token>(cacheName)) ?? { token: '', expire: 1 }
let result = (await this.bin.storage.get<WxWork.Token>(cacheName)) ?? {
token: '',
expire: 1,
}
if (!result.token) {
const param = { corpid: this.agent.corpId, corpsecret: this.agent.secret }
const data = await this.bin.get('/cgi-bin/gettoken', param)
Expand All @@ -80,10 +93,14 @@ export class WxWorkServiceAuth extends WxWorkService {
// 获取Ticket
private async gain() {
const cacheName = `WxWorkJsapiTicket:${this.agent.corpId}:${this.agent.agentId}`
let result = (await this.bin.storage.get<WxWork.JsapiTicket>(cacheName)) ?? { ticket: '', expire: 1 }
let result = (await this.bin.storage.get<WxWork.JsapiTicket>(
cacheName
)) ?? { ticket: '', expire: 1 }
if (!result.ticket) {
const access_token = await this.getToken()
const data = await this.bin.get('/cgi-bin/get_jsapi_ticket', { access_token })
const data = await this.bin.get('/cgi-bin/get_jsapi_ticket', {
access_token,
})
const ms = _.toInteger(data.expiresIn) * 1e3 - 200 * 1e3
const expire = _.now() + ms
const ticket = (data.ticket as string) || ''
Expand Down
42 changes: 35 additions & 7 deletions src/services/WxWorkBotService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,31 @@ export class WxWorkBotService extends WxWorkService {
this.key = key
}

async text(content: string, mentioned_list: string[] = [], mentioned_mobile_list: string[] = []) {
const data = { msgtype: 'text', text: { content, mentioned_list, mentioned_mobile_list } }
async text(
content: string,
mentioned_list: string[] = [],
mentioned_mobile_list: string[] = []
) {
const data = {
msgtype: 'text',
text: { content, mentioned_list, mentioned_mobile_list },
}
return await this.send(data)
}

async json(title: string, env: string, data: any) {
return await this.text(`${title} ${env} ${dayjs().format('YYYY-MM-DD HH:mm:ss')} \n${JSON.stringify(data, undefined, 2)}`)
return await this.text(
`${title} ${env} ${dayjs().format(
'YYYY-MM-DD HH:mm:ss'
)} \n${JSON.stringify(data, undefined, 2)}`
)
}

async markdown(markdown: WxWorkMarkdown) {
const data = { msgtype: 'markdown', markdown: { content: markdown.value() } }
const data = {
msgtype: 'markdown',
markdown: { content: markdown.value() },
}
return await this.send(data)
}

Expand All @@ -31,7 +45,14 @@ export class WxWorkBotService extends WxWorkService {
return await this.send(data)
}

async news(articles: Array<{ title: string; description?: string; url: string; picurl?: string }>) {
async news(
articles: Array<{
title: string
description?: string
url: string
picurl?: string
}>
) {
const data = { msgtype: 'news', news: { articles } }
return await this.send(data)
}
Expand All @@ -41,9 +62,16 @@ export class WxWorkBotService extends WxWorkService {
return await this.send(data)
}

async upload(filepath: string): Promise<{ type: string; mediaId: string; createdAt: string }> {
async upload(
filepath: string
): Promise<{ type: string; mediaId: string; createdAt: string }> {
const { data, headers } = this.bin.parseUploadFile(filepath, 'media')
return await this.bin.post('/cgi-bin/webhook/upload_media', data, { key: this.key, type: 'file' }, { headers })
return await this.bin.post(
'/cgi-bin/webhook/upload_media',
data,
{ key: this.key, type: 'file' },
{ headers }
)
}

protected async send(data: any) {
Expand Down
44 changes: 36 additions & 8 deletions src/services/WxWorkDepartmentService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,56 @@ import { WxWork } from '../typings'

export class WxWorkDepartmentService extends WxWorkServiceAuth {
// 创建部门 https://work.weixin.qq.com/api/doc/90000/90135/90205
async create({ id = 0, name = '', nameEn = '', parentid = 0, order = 0 } = {}) {
async create({
id = 0,
name = '',
nameEn = '',
parentid = 0,
order = 0,
} = {}) {
const params = _.pickBy({ id, name, name_en: nameEn, parentid, order })
return (await this.bin.post('/cgi-bin/department/create', $.snakeCaseKeys(params), { access_token: await this.getToken() }, {}, [
60008,
])) as WxWork.CreateDepartmentResponse
return (await this.bin.post(
'/cgi-bin/department/create',
$.snakeCaseKeys(params),
{ access_token: await this.getToken() },
{},
[60008]
)) as WxWork.CreateDepartmentResponse
}

// 更新部门 https://work.weixin.qq.com/api/doc/90000/90135/90206
async update(id: number, { name, nameEn, parentid, order }: { name?: string; nameEn?: string; parentid?: number; order?: number }) {
async update(
id: number,
{
name,
nameEn,
parentid,
order,
}: { name?: string; nameEn?: string; parentid?: number; order?: number }
) {
const access_token = await this.getToken()
const params = { id, name, name_en: nameEn, parentid, order }
return (await this.bin.post('/cgi-bin/department/update', _.pickBy(params), { access_token })) as WxWork.NormalResponse
return (await this.bin.post(
'/cgi-bin/department/update',
_.pickBy(params),
{ access_token }
)) as WxWork.NormalResponse
}

// 删除部门 https://work.weixin.qq.com/api/doc/90000/90135/90207
async delete(id: number) {
return (await this.bin.get('cgi-bin/department/delete', { access_token: await this.getToken(), id })) as WxWork.NormalResponse
return (await this.bin.get('cgi-bin/department/delete', {
access_token: await this.getToken(),
id,
})) as WxWork.NormalResponse
}

// 获取部门列表 https://work.weixin.qq.com/api/doc/90000/90135/90208
async getList(id?: number) {
const params = id ? { id } : {}
return (await this.bin.get('cgi-bin/department/list', { access_token: await this.getToken(), ...params })) as WxWork.DepartmentList
return (await this.bin.get('cgi-bin/department/list', {
access_token: await this.getToken(),
...params,
})) as WxWork.DepartmentList
}
}
30 changes: 26 additions & 4 deletions src/services/WxWorkGroupService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,37 @@ export class WxWorkGroupService extends WxWorkServiceAuth {
}

// 修改群聊会话 https://work.weixin.qq.com/api/doc/90000/90135/90246
async update(chatId: string, name: string, owner: string, addUserList: string[], delUserList: string[]) {
async update(
chatId: string,
name: string,
owner: string,
addUserList: string[],
delUserList: string[]
) {
const param = { access_token: await this.getToken() }
return (await this.bin.post(
'/cgi-bin/appchat/update',
{ chatid: chatId, name, owner, add_user_list: addUserList, del_user_list: delUserList },
{
chatid: chatId,
name,
owner,
add_user_list: addUserList,
del_user_list: delUserList,
},
param
)) as WxWork.NormalResponse
}

// 获取群聊会话 https://work.weixin.qq.com/api/doc/90000/90135/90247
async get(name: string, owner: string, userList: string[], chatId = '') {
const access_token = await this.getToken()
return (await this.bin.get('/cgi-bin/appchat/create', { access_token, name, owner, userlist: userList, chatid: chatId })) as WxWork.GetGroupResponse
return (await this.bin.get('/cgi-bin/appchat/create', {
access_token,
name,
owner,
userlist: userList,
chatid: chatId,
})) as WxWork.GetGroupResponse
}

// 发送纯文本消息
Expand All @@ -36,6 +54,10 @@ export class WxWorkGroupService extends WxWorkServiceAuth {
text: { content },
safe,
}
return (await this.bin.post('cgi-bin/appchat/send', { ...args }, param)) as WxWork.NormalResponse
return (await this.bin.post(
'cgi-bin/appchat/send',
{ ...args },
param
)) as WxWork.NormalResponse
}
}
Loading

0 comments on commit 17329dd

Please sign in to comment.