interfaces

This commit is contained in:
Erik 2022-11-09 11:20:32 +02:00
parent cdd07ee328
commit 52bd21434b
Signed by: Navy.gif
GPG Key ID: 811EC0CD80E7E5FB
3 changed files with 74 additions and 0 deletions

View File

@ -0,0 +1,13 @@
class AbstractUserDatabase {
fetchUser () {
throw new Error('This function is expected to be implemented by a subclass');
}
matchToken () {
throw new Error('This function is expected to be implemented by a subclass');
}
}
module.exports = AbstractUserDatabase;

View File

@ -0,0 +1,57 @@
const { Util } = require('../../util');
class Endpoint {
constructor (server, { path, name }) {
if (!server) Util.fatal(new Error('Missing server object in endpoint'));
this.server = server;
if (!path) Util.fatal(new Error('Missing path in endpoint'));
this.path = path;
if (name) this.name = name;
else this.name = path;
// Subpaths that should exist on *all* endpoints, the subpaths property can be overwritten, so storing these separately to ensure they exist
this._subpaths = [
'/debug', 'post', this.toggleDebug.bind(this), [ server.authenticator.createAuthoriser('developer') ]
];
this.middleware = [];
this.subpaths = [];
this.methods = [];
this.logger = server.createLogger(this);
this.debug = false;
}
init () {
for (const [ method, cb ] of this.methods) {
if (typeof method !== 'string') throw new Error(`Invalid method parameter type in Endpoint ${this.name} major path`);
this.client.app[method](this.path, ...this.middleware, cb);
}
this.subpaths = [ ...this._subpaths, ...this.subpaths ];
for (const [ sub, method, cb, mw = [] ] of this.subpaths) {
if (typeof method !== 'string') throw new Error(`Invalid method parameter type in Endpoint ${this.name} subpath ${sub}`);
this.client.app[method](this.path + sub, ...this.middleware, ...mw, cb);
}
}
toggleDebug (req, res) {
const { body } = req;
if (typeof body.value !== 'boolean') res.stats(400).send(`Invalid value`);
this.logger.info(`Setting debug mode on endpoint ${this.name} to ${body.value}`);
this.debug = true;
this.logger.setDebug(body.value);
res.status(200).send(body.value);
}
}
module.exports = Endpoint;

View File

@ -0,0 +1,4 @@
module.exports = {
Endpoint: require('./Endpoint'),
AbstractUserDatabase: require('./AbstractUserDatabase')
};