Add method to patch services

This commit is contained in:
KernelDeimos 2024-05-15 15:32:18 -04:00
parent 0b093dd57e
commit 2e0d7361cb
2 changed files with 32 additions and 0 deletions

View File

@ -32,6 +32,11 @@ class Container {
? cls.getInstance({ services: this, config, my_config, name, args })
: new cls({ services: this, config, my_config, name, args }) ;
}
patchService (name, patch, args) {
const original_service = this.instances_[name];
const patch_instance = new patch();
patch_instance.patch({ original_service, args });
}
set (name, instance) { this.instances_[name] = instance; }
get (name, opts) {
if ( this.instances_[name] ) {

View File

@ -0,0 +1,27 @@
const { AdvancedBase } = require("@heyputer/puter-js-common");
class ServicePatch extends AdvancedBase {
patch ({ original_service }) {
const patch_methods = this._get_merged_static_object('PATCH_METHODS');
for ( const k in patch_methods ) {
if ( typeof patch_methods[k] !== 'function' ) {
throw new Error(`Patch method ${k} to ${original_service.service_name} ` +
`from ${this.constructor.name} ` +
`is not a function.`)
}
const patch_method = patch_methods[k];
const patch_arguments = {
that: original_service,
original: original_service[k].bind(original_service),
};
original_service[k] = (...a) => {
return patch_method.call(this, patch_arguments, ...a);
}
}
}
}
module.exports = ServicePatch;