npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

express-master-controller

v1.0.41

Published

Master Controller with automated swagger docs creation for node express app

Downloads

401

Readme

express-master-controller

express-master-controller is a powerful express middleware designed to help you create APIs and sockets super fast. It is a master-controller-based express package that provides a streamlined way to manage your routes and socket events. It also automates the creation of Swagger documentation for your express application

Features

  • Easy creation of APIs and sockets
  • Automated Swagger documentation
  • Joi validation
  • TypeScript support

Installation

npm install express-master-controller

or

yarn add express-master-controller

Initialization

import { masterController } from 'express-master-controller';

const app = express();

app.use(
        masterController({
          // path to the routes directory (optional)
          routesFolder: path.join(__dirname, 'routes'),
          // path to the cron directory (optional)
          cronFolder: path.join(__dirname, 'cron'),
          // whether to enable sockets or not (optional)
          enableSockets: true,
          // swagger config (optional)
          swaggerConfig: {
            // swagger definition (required)
            title: 'API Documentation',
            description: 'API Documentation',
            version: '1.0.0',
            // swagger docs endpoint (optional)
            swaggerDocsEndpoint: '/api-docs',
            // if you want to give your swagger doc (optional)
            swaggerDocPath: path.join(__dirname, 'swagger.json'),
            // whether to modify your provided swagger doc or not (optional)
            modifySwaggerDoc: true,
          },
        }),
);

app.listen(3000, () => {
  console.log('Server started');
});

masterController Parameters

  • routesFolder: Absolute path to the routes directory (required)
  • swaggerConfig: Swagger configuration (optional), if not provided, no swagger documentation will be generated
    • title: Swagger title (required)
    • description: Swagger description (required)
    • version: Swagger version (required)
    • swaggerDocsEndpoint: Swagger docs endpoint (optional), default: /api-docs
    • swaggerDocPath: Absolute path to the swagger doc file (optional)
    • modifySwaggerDoc: Whether to modify your provided swagger doc or not (optional), default: false

Creating APIs

Controller

import {
    MasterController,
    RequestBuilder,
    ResponseBuilder,
} from 'express-master-controller';
import Joi from 'joi';

class Controller extends MasterController<IParams, IQuery, IBody> {
    // swagger documetation for the api
    static doc() {
        return {
            tags: ['User'],
            summary: 'Register User',
            description: 'Register User',
        };
    }

    // add your validations here,
    // rest of the swagger documentation will be generated automatically from the validation
    public static validate(): RequestBuilder {
        const payload = new RequestBuilder();

        // request body validation
        payload.addToBody(
            Joi.object().keys({
                name: Joi.string().required(),
                lastName: Joi.string().required(),
                email: Joi.string().email().required(),
                password: Joi.string().min(8).max(20).required(),
            }),
        );

        // request query validation
        payload.addToQuery(
            Joi.object().keys({
                limit: Joi.number().required(),
                offset: Joi.number().required(),
            }),
        );

        // request params validation
        payload.addToParams(
            Joi.object().keys({
                id: Joi.number().required(),
            }),
        );
        return payload;
    }

    // controller function
    async restController(
        params: IParams,
        query: IQuery,
        body: IBody,
        headers: any,
        allData: any): Promise<ResponseBuilder> {
        // your code here
        return new ResponseBuilder(200, Response, 'Success Message');
    }

    // socket controller function
    socketController(io: Server, socket: Socket, payload: any): void {
        // your code here
        // Socket data will be available in payload, recieved from the client on socket event, which is setup in the route file
        // You can emit data back to the client using io.emit or socket.emit
    }

    // cron controller function
    cronController(): void {
        // your scheduled code here (if any)
    }
}

export default Controller;

Controller Generics

  • IParams: Request params interface/type
  • IQuery: Request query interface/type
  • IBody: Request body interface/type

restController Parameters

  • params: Request params (eg. /user/:id)
  • query: Request query (eg. /user?limit=10&offset=0)
  • body: Request body
  • headers: Request headers
  • allData: All request data (all the above-combined + custom data from middlewares)

socketController Parameters

  • io: Socket.io instance
  • socket: Socket instance
  • payload: Data sent from the client

Router File

import express from 'express'
import Controller from '../Controller'

export default (app: express.Application) => {
    // REST Routes
    Controller.get(app, '/user/:id', [
        /* Comma separated middlewares */
    ])
    Controller.post(app, '/user/:id', [])
    Controller.put(app, '/user/:id', [])
    Controller.delete(app, '/user/:id', [])
    Controller.patch(app, '/user/:id', [])

    // Socket Events
    // Any payload you send from the client to this event will be available in the socketController function
    Controller.socketIO('Event Name')
}

Important: Make sure to name your router file as *.routes.ts or *.routes.js

Note: You don't need to import your router file to anywhere, put it in the routes directory, and it will be automatically taken care by the package.

Cron File

import { MasterController, CronBuilder, CronMonth, CronWeekday } from 'express-master-controller';

class DemoCron extends MasterController<null, null, null> {
    cronController() {
        console.log('Cron job is running');
    }
}

// Unix Crontab format
DemoCron.cronJob('*/5 * * * * *');

// Using CronBuilder
DemoCron.cronJob(
    new CronBuilder()
    .every()
    .second()
    .every()
    .specificMinute([10, 20, 30])
    .every()
    .dayOfMonth(CronMonth.January)
    .every()
    .dayOfWeek(CronWeekday.Friday)
    .build(),
);

Important: Make sure to name your cron file as *.cron.ts or *.cron.js

Note: You don't need to import your cron file to anywhere, put it in cron directory, and it will be automatically taken care by the package.

External Dependencies (You need to install these packages)