dev: add database and config access for extensions

This commit is contained in:
KernelDeimos 2024-11-04 16:42:30 -05:00
parent c44b9ab8d5
commit 856688f884
3 changed files with 25 additions and 0 deletions

View File

@ -64,6 +64,7 @@ const install = async ({ services, app, useapi, modapi }) => {
def('core.APIError', require('./api/APIError'));
def('core', require('./services/auth/Actor'), { assign: true });
def('core.config', config);
});
// === LIBRARIES ===

View File

@ -20,6 +20,21 @@ class Extension extends AdvancedBase {
this.ensure_service_();
}
example () {
console.log('Example method called by an extension.');
}
get db () {
const db = this.service.values.get('db');
if ( ! db ) {
throw new Error(
'extension tried to access database before it was ' +
'initialized'
);
}
return db;
}
get (path, handler, options) {
// this extension will have a default service
this.ensure_service_();

View File

@ -2,6 +2,8 @@ const { AdvancedBase } = require("@heyputer/putility");
const BaseService = require("./services/BaseService");
const { Endpoint } = require("./util/expressutil");
const configurable_auth = require("./middleware/configurable_auth");
const { Context } = require("./util/context");
const { DB_READ, DB_WRITE } = require("./services/database/consts");
class ExtensionServiceState extends AdvancedBase {
constructor (...a) {
@ -10,6 +12,9 @@ class ExtensionServiceState extends AdvancedBase {
this.extension = a[0].extension;
this.endpoints_ = [];
// Values shared between the `extension` global and its service
this.values = new Context();
}
register_route_handler_ (path, handler, options = {}) {
// handler and options may be flipped
@ -51,6 +56,10 @@ class ExtensionService extends BaseService {
async _init (args) {
this.state = args.state;
// Create database access object for extension
const db = this.services.get('database').get(DB_WRITE, 'extension');
this.state.values.set('db', db);
// Propagate all events not from extensions to `core.`
const svc_event = this.services.get('event');
svc_event.on_all((key, data, meta = {}) => {