mirror of
https://github.com/chrononeko/chronocat.git
synced 2024-11-16 12:51:39 +00:00
feat: properly deal with duplicated api registration
This commit is contained in:
parent
25a78dbc7d
commit
49d12becef
@ -1,4 +1,5 @@
|
||||
import type { Methods } from '../types'
|
||||
import { bgMagenta, cyan, white } from '../utils/colors'
|
||||
import { l } from './logger'
|
||||
|
||||
const notimplSym = Symbol('chronocat.internal.notimpl')
|
||||
@ -9,6 +10,7 @@ export type ApiImpl<M extends keyof Methods> = ((
|
||||
[notimplSym]: boolean
|
||||
|
||||
engine: string
|
||||
priority: number
|
||||
}
|
||||
|
||||
export type Api = {
|
||||
@ -18,6 +20,7 @@ export type Api = {
|
||||
|
||||
register: (
|
||||
engine: string,
|
||||
priority?: number,
|
||||
) => <M extends keyof Methods>(
|
||||
method: M,
|
||||
impl: (...args: Methods[M][0]) => Promise<Methods[M][1]>,
|
||||
@ -31,11 +34,11 @@ const buildNotimpl = (name: string) => {
|
||||
throw: true,
|
||||
})
|
||||
|
||||
;(
|
||||
fn as unknown as {
|
||||
[notimplSym]: boolean
|
||||
}
|
||||
)[notimplSym] = true
|
||||
; (
|
||||
fn as unknown as {
|
||||
[notimplSym]: boolean
|
||||
}
|
||||
)[notimplSym] = true
|
||||
|
||||
return fn
|
||||
}
|
||||
@ -43,7 +46,7 @@ const buildNotimpl = (name: string) => {
|
||||
const handler: ProxyHandler<Api> = {
|
||||
get: (target, name) =>
|
||||
typeof name === 'symbol' ||
|
||||
Object.prototype.hasOwnProperty.call(target, name)
|
||||
Object.prototype.hasOwnProperty.call(target, name)
|
||||
? target[name as keyof Methods]
|
||||
: buildNotimpl(name),
|
||||
}
|
||||
@ -51,12 +54,21 @@ const handler: ProxyHandler<Api> = {
|
||||
export const api = new Proxy({} as Api, handler)
|
||||
|
||||
api.register =
|
||||
(engine: string) =>
|
||||
<M extends keyof Methods>(
|
||||
method: M,
|
||||
impl: (...args: Methods[M][0]) => Promise<Methods[M][1]>,
|
||||
) => {
|
||||
// FIXME: Do not use type assertion
|
||||
api[method] = impl /* ApiImpl<M> */ as Api[M]
|
||||
api[method].engine = engine
|
||||
}
|
||||
(engine: string, defaultPriority: number = 0) =>
|
||||
<M extends keyof Methods>(
|
||||
method: M,
|
||||
impl: (...args: Methods[M][0]) => Promise<Methods[M][1]>,
|
||||
priority: number = -1,
|
||||
) => {
|
||||
const newPriority = priority === -1 ? defaultPriority : priority
|
||||
if (api[method]) {
|
||||
l.warn(`${cyan(engine)}(${newPriority}) 与 ${cyan(api[method].engine)}(${api[method].priority
|
||||
}) 重复注册了方法 ${bgMagenta(white(method))},将采用 ${newPriority > api[method].priority ? engine : api[method].engine} 的版本。`)
|
||||
|
||||
if (newPriority < api[method].priority) return
|
||||
}
|
||||
// FIXME: Do not use type assertion
|
||||
api[method] = impl /* ApiImpl<M> */ as Api[M]
|
||||
api[method].engine = engine
|
||||
api[method].priority = newPriority
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user