plugdo-mvc
Version:
A module that implements mvc software architecture on top of express module
101 lines (86 loc) • 2.97 kB
JavaScript
const express = require("express");
class Api {
constructor(path, middleware) {
if(path === undefined) throw new Error("The path argument is undefined");
this._path = path;
this._router = express.Router();
this._middleware = middleware || this.defaultMiddleware;
this.methods = {};
}
Router() {
if(this.methods === undefined) throw new Error("This api does not have methods defined");
if(this.methods.get !== undefined) {
this._get(this.methods.get);
}
if(this.methods.post !== undefined) {
this._post(this.methods.post);
}
if(this.methods.put !== undefined) {
this._put(this.methods.put);
}
if(this.methods.delete !== undefined) {
this._delete(this.methods.delete);
}
return this._router;
}
_get(handler) {
if (handler.constructor.name !== "AsyncFunction") throw new Error("Callback function must be async");
this._router.get(this._path, this._middleware, async (req, res, next) => {
try {
let response = await handler(req, res);
res.json(response);
}
catch (error) {
res.json(this.errorWrapper(error));
}
});
}
_post(handler) {
if (handler.constructor.name !== "AsyncFunction") throw new Error("Callback function must be async");
this._router.post(this._path, this._middleware, async (req, res, next) => {
try {
let response = await handler(req, res);
res.json(response);
}
catch (error) {
res.json(this.errorWrapper(error));
}
});
}
_put(handler) {
if (handler.constructor.name !== "AsyncFunction") throw new Error("Callback function must be async");
this._router.put(this._path, this._middleware, async (req, res, next) => {
try {
let response = await handler(req, res);
res.json(response);
}
catch (error) {
res.json(this.errorWrapper(error));
}
});
}
_delete(handler) {
if (handler.constructor.name !== "AsyncFunction") throw new Error("Callback function must be async");
this._router.delete(this._path, this._middleware, async (req, res, next) => {
try {
let response = await handler(req, res);
res.json(response);
}
catch (error) {
res.json(this.errorWrapper(error));
}
});
}
errorWrapper(error) {
return {
success: false,
errorCode: 500,
error: error.message,
stack: error.stack
}
}
defaultMiddleware(req, res, next) {
next();
}
}
module.exports = Api;