Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /************************** Info
- License: MIT license at bottom, nullifying any license stipulations of this platform
- Requirements: NodeJS with Express, Morgan packages
- This is a substitute for the /bin/www and server.js file generated when creating an Express App.
- This will not work out of the box, to make it work:
- - optional - add API_PORT to .env
- - remove reference to JsonParseCatch, hardcode it, or create the file
- - redefine ApiEndpoints and its usage in useRoutes, or create file at that path
- - remove references to routes, and add your own
- - Change npm start command in package.json, or run directly with "node ApiServer.js"
- */
- /************************** JsonParseCatch.js
- Optional middleware, prevents Express from crashing when parsing JSON.
- Save in ./Middleware/JsonParseCatch.js, or elsewhere and modify reference
- */
- const JsonParseCatch = (err, req, res, next) => {
- if(err instanceof SyntaxError && err.status === 400 && "body" in err){
- return res.status(400).send({status: 400, message: err.message});
- }
- next();
- }
- module.exports = {
- JsonParseCatch: JsonParseCatch,
- router: require("express").Router()
- };
- /************************** ApiServer.js */
- require("dotenv").config();
- class ApiServer {
- constructor() {
- this.ApiEndpoints = require("./Static/Shared/Config").ApiEndpoints;
- this.logger = require("morgan")("dev");
- this.port = this.normalizePort(process.env.API_PORT) || 3000;
- this.httpServer = (this.http = require("http")).createServer(this.app = (this.express = require("express"))());
- }
- run = () => {
- this.setConfig();
- this.setMiddleware();
- this.setRoutes();
- this.startListening();
- }
- setConfig = () => {
- this.app.use(this.logger);
- this.app.use(this.express.json());
- }
- setMiddleware = () => {
- this.app.use(require("./Middleware/JsonParseCatch").JsonParseCatch);
- }
- setRoutes = () => {
- let homeRouter = require("./Routes/HomeRouter");
- let productRouter = require("./Routes/ProductRouter");
- /*
- GET /products
- Returns: Array of products
- Beschrijving: Get all products
- */
- this.app.use(this.ApiEndpoints.Products, productRouter);
- /*
- GET /
- Returns: Metric
- Beschrijving: Get metrics
- */
- this.app.use(this.ApiEndpoints.Metrics, homeRouter);
- }
- startListening = () => {
- this.httpServer.listen(this.port);
- this.httpServer.on('error', this.onError);
- this.httpServer.on('listening', this.onListening);
- }
- normalizePort = (val) => {
- let port; return port = parseInt(val, 10), isNaN(port) ? val : port >= 0 ? port : false;
- }
- onError = (error) => {
- error.syscall !== "listen" ? (() => { throw error; }).call() : null;
- let bind = typeof this.port === 'string' ? 'Pipe ' + this.port : 'Port ' + this.port;
- switch (error.code) {
- case 'EACCES':
- console.error('[ApiServer - onError.EACCES] ' + bind + ' requires elevated privileges');
- process.exit(1);
- break;
- case 'EADDRINUSE':
- console.error('[ApiServer - onError.EADDRINUSE] ' + bind + ' is already in use');
- process.exit(1);
- break;
- default:
- throw error;
- }
- }
- onListening = () => {
- let addr = this.httpServer.address();
- let bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port;
- console.log('[ApiServer - onListening] API server listening on ' + bind);
- }
- }
- const server = new ApiServer().run();
- /* Author: Benjamin Van Renterghem
- *
- * Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- * "Software"), to deal in the Software without restriction, including
- * without limitation the rights to use, copy, modify, merge, publish,
- * distribute, sublicense, and/or sell copies of the Software, and to
- * permit persons to whom the Software is furnished to do so, subject to
- * the following conditions:
- *
- * The above copyright notice and this permission notice shall be
- * included in all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
- * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
- * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
Add Comment
Please, Sign In to add comment