Skip to content

Commit

Permalink
feat(plugin-common): support info order
Browse files Browse the repository at this point in the history
  • Loading branch information
shigma committed Jan 25, 2020
1 parent ff24d1a commit 7119a58
Showing 1 changed file with 14 additions and 4 deletions.
18 changes: 14 additions & 4 deletions packages/plugin-common/src/info.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,21 @@ import { Context, UserField, UserData, getTargetId, Meta } from 'koishi-core'

type UserInfoCallback <K extends UserField = UserField> = (user: Pick<UserData, K>) => string

interface Info <K extends UserField = UserField> {
order: number
callback: (user: Pick<UserData, K>) => string
}

const infoFields = new Set<UserField>(['authority'])
const infoCallbacks: UserInfoCallback[] = []
const infoList: Info[] = []

export function registerUserInfo <K extends UserField> (callback: UserInfoCallback<K>, fields: Iterable<K> = []) {
infoCallbacks.push(callback)
export function registerUserInfo <K extends UserField> (callback: UserInfoCallback<K>, fields: Iterable<K> = [], order = 0) {
const index = infoList.findIndex(a => a.order > order)
if (index >= 0) {
infoList.splice(index, 0, { order, callback })
} else {
infoList.push({ order, callback })
}
for (const field of fields) {
infoFields.add(field)
}
Expand Down Expand Up @@ -50,7 +60,7 @@ export default function apply (ctx: Context, config: InfoOptions = {}) {
output.push(`${config.getUserName(user, meta) || meta.userId},您的权限为 ${user.authority} 级。`)
}

for (const callback of infoCallbacks) {
for (const { callback } of infoList) {
const result = callback(user)
if (result) output.push(result)
}
Expand Down

0 comments on commit 7119a58

Please sign in to comment.