From 49d12becefb43a058d52bd0df52b094ddfdff3c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?impart=E6=88=91=E7=9A=84impart=E5=91=A2?= Date: Sat, 9 Mar 2024 01:46:40 +0800 Subject: [PATCH] feat: properly deal with duplicated api registration --- packages/shell/src/services/api.ts | 42 +++++++++++++++++++----------- 1 file changed, 27 insertions(+), 15 deletions(-) diff --git a/packages/shell/src/services/api.ts b/packages/shell/src/services/api.ts index 2a4a956..06b2da9 100644 --- a/packages/shell/src/services/api.ts +++ b/packages/shell/src/services/api.ts @@ -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 = (( [notimplSym]: boolean engine: string + priority: number } export type Api = { @@ -18,6 +20,7 @@ export type Api = { register: ( engine: string, + priority?: number, ) => ( method: M, impl: (...args: Methods[M][0]) => Promise, @@ -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 = { 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 = { export const api = new Proxy({} as Api, handler) api.register = - (engine: string) => - ( - method: M, - impl: (...args: Methods[M][0]) => Promise, - ) => { - // FIXME: Do not use type assertion - api[method] = impl /* ApiImpl */ as Api[M] - api[method].engine = engine - } + (engine: string, defaultPriority: number = 0) => + ( + method: M, + impl: (...args: Methods[M][0]) => Promise, + 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 */ as Api[M] + api[method].engine = engine + api[method].priority = newPriority + }