From 30550fcddda18469735499546de502d29b85e2ad Mon Sep 17 00:00:00 2001 From: KernelDeimos Date: Wed, 5 Jun 2024 16:12:50 -0400 Subject: [PATCH] feat(backend): add script service The script service allows other services to register re-runnable tasks called "scripts". These can be invoked via "script:run" in the console. --- packages/backend/src/CoreModule.js | 3 ++ .../backend/src/services/ScriptService.js | 47 +++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 packages/backend/src/services/ScriptService.js diff --git a/packages/backend/src/CoreModule.js b/packages/backend/src/CoreModule.js index d98565d5..920bd6e1 100644 --- a/packages/backend/src/CoreModule.js +++ b/packages/backend/src/CoreModule.js @@ -228,6 +228,9 @@ const install = async ({ services, app }) => { const { DriverService } = require("./services/drivers/DriverService"); services.registerService('driver', DriverService); + + const { ScriptService } = require('./services/ScriptService'); + services.registerService('script', ScriptService); } const install_legacy = async ({ services }) => { diff --git a/packages/backend/src/services/ScriptService.js b/packages/backend/src/services/ScriptService.js new file mode 100644 index 00000000..f0576c89 --- /dev/null +++ b/packages/backend/src/services/ScriptService.js @@ -0,0 +1,47 @@ +const BaseService = require("./BaseService"); + +class BackendScript { + constructor (name, fn) { + this.name = name; + this.fn = fn; + } + + async run (ctx, args) { + return await this.fn(ctx, args); + } + +} + +class ScriptService extends BaseService { + _construct () { + this.scripts = []; + } + + async _init () { + const svc_commands = this.services.get('commands'); + svc_commands.registerCommands('script', [ + { + id: 'run', + description: 'run a script', + handler: async (args, ctx) => { + const script_name = args.shift(); + const script = this.scripts.find(s => s.name === script_name); + if ( ! script ) { + ctx.error(`script not found: ${script_name}`); + return; + } + await script.run(ctx, args); + } + } + ]); + } + + register (name, fn) { + this.scripts.push(new BackendScript(name, fn)); + } +} + +module.exports = { + ScriptService, + BackendScript, +};