@vnxjs/service
Version:
Vnmf Service
81 lines (71 loc) • 2.16 kB
text/typescript
import { addPlatforms } from '@vnxjs/helper'
import Kernel from './Kernel'
import { ICommand, IHook, IPlatform } from './utils/types'
export default class Plugin {
id: string
path: string
ctx: Kernel
optsSchema: (...args: any[]) => void
constructor (opts) {
this.id = opts.id
this.path = opts.path
this.ctx = opts.ctx
}
register (hook: IHook) {
if (typeof hook.name !== 'string') {
throw new Error(`Plugins ${this.id} Registered in %1 %2 hook Failed, hook.name It has to be. string Type`)
}
if (typeof hook.fn !== 'function') {
throw new Error(`Plugins ${this.id} Registered in %1 %2 hook Failed, hook.fn It has to be. function Type`)
}
const hooks = this.ctx.hooks.get(hook.name) || []
hook.plugin = this.id
this.ctx.hooks.set(hook.name, hooks.concat(hook))
}
registerCommand (command: ICommand) {
if (this.ctx.commands.has(command.name)) {
throw new Error(`Command ${command.name} Existing`)
}
this.ctx.commands.set(command.name, command)
this.register(command)
}
registerPlatform (platform: IPlatform) {
if (this.ctx.platforms.has(platform.name)) {
throw new Error(`Adaptation platform ${platform.name} Existing`)
}
addPlatforms(platform.name)
this.ctx.platforms.set(platform.name, platform)
this.register(platform)
}
registerMethod (...args) {
const { name, fn } = processArgs(args)
const methods = this.ctx.methods.get(name) || []
methods.push(fn || function (fn: (...args: any[]) => void) {
this.register({
name,
fn
})
}.bind(this))
this.ctx.methods.set(name, methods)
}
addPluginOptsSchema (schema) {
this.optsSchema = schema
}
}
function processArgs (args) {
let name, fn
if (!args.length) {
throw new Error('Parameter is empty')
} else if (args.length === 1) {
if (typeof args[0] === 'string') {
name = args[0]
} else {
name = args[0].name
fn = args[0].fn
}
} else {
name = args[0]
fn = args[1]
}
return { name, fn }
}