import { Registrable } from "../registry/index.js"; import { FormItemProps } from "../dt/index.js"; import { HttpClient, ILogger, utils } from "@certd/basic"; import * as _ from "lodash-es"; import { PluginRequestHandleReq } from "../plugin/index.js"; import { IRuntimeDepsService, IServiceGetter } from "../service/index.js"; // export type AccessRequestHandleReqInput = { // id?: number; // title?: string; // access: T; // }; export type AccessRequestHandleReq = PluginRequestHandleReq; export type AccessInputDefine = FormItemProps & { title: string; required?: boolean; encrypt?: boolean; }; export type AccessDefine = Registrable & { icon?: string; subtype?: string; dependPlugins?: Record; dependPackages?: Record; input?: { [key: string]: AccessInputDefine; }; }; export interface IAccessService { getById(id: any): Promise; getCommonById(id: any): Promise; } export interface IAccess { ctx: AccessContext; [key: string]: any; } export type AccessContext = { http: HttpClient; logger: ILogger; utils: typeof utils; accessService: IAccessService; serviceGetter?: IServiceGetter; define?: AccessDefine; }; export abstract class BaseAccess implements IAccess { ctx!: AccessContext; runtimeDepsService?: IRuntimeDepsService; async importRuntime(specifier: string) { if (!this.runtimeDepsService) { throw new Error("runtimeDepsService 未初始化"); } return await this.runtimeDepsService.importRuntime(specifier, this.ctx.logger); } async setCtx(ctx: AccessContext) { this.ctx = ctx; if (!this.runtimeDepsService && this.ctx.serviceGetter) { this.runtimeDepsService = await this.ctx.serviceGetter.get("runtimeDepsService"); } } async onRequest(req: AccessRequestHandleReq) { if (!req.action) { throw new Error("action is required"); } let methodName = req.action; if (!req.action.startsWith("on")) { methodName = `on${_.upperFirst(req.action)}`; } // @ts-ignore const method = this[methodName]; if (method) { // @ts-ignore return await this[methodName](req.data); } throw new Error(`action ${req.action} not found`); } normalizeEndpoint(endpoint: string) { return endpoint.replace(/\/$/, ""); } }