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-swagger-delta

v1.4.0

Published

Using Express with Swagger

Downloads

43

Readme

✅ express-swagger-delta

Fast, unopinionated, minimalist web framework for node.

NPM Version NPM Downloads badge-statements badge-branches badge-functions badge-lines

🔹 Installation

This is a Node.js module available through the npm registry.

Before installing, download and install Node.js.

Installation is done using the npm install command:

$ npm install express-swagger-delta

OU

$ yarn add express-swagger-delta

🔹 Usage

To start using the library, it is necessary to create a base configuration file, following the structure:

Note: Follows the same structure pattern as the swagger.js documentation (openapi: 3.0.0).

import { description, name, version } from '../../package.json';

export const layout = {
  explorer: false,
  customSiteTitle: 'Example Documentation',
  customCss: '.swagger-ui .topbar { display: none }',
  swaggerOptions: {
    docExpansion: 'none',
  },
};

export const specification = {
  info: {
    name: name,
    version: version,
    description: description,
    title: 'Example Documentation',
  },
  servers: [
    {
      url: `http://localhost:8080/api`,
    },
  ],
  components: {
    securitySchemes: {
      ExampleKey: {
        in: 'header',
        type: 'apiKey',
        name: 'ExampleKey',
      },
    },
    schemas: {
      Return: {
        type: 'object',
        properties: {
          statusCode: {
            type: 'integer',
            format: 'int64',
            description: 'Request Status Code',
          },
          message: {
            type: 'string',
            description: 'Request Status Message',
          },
          content: {
            type: 'object',
            description: 'Request Content',
          },
        },
      },
    },
    responses: {
      default: {
        description: 'Api Default Return',
        content: {
          'application/json': {
            schema: {
              $ref: '#/components/schemas/Return',
            },
          },
        },
      },
    },
  },
};

That done, you need to configure the server, which can be done as follows:

import { json, urlencoded } from 'body-parser';
import cors from 'cors';
import helmet from 'helmet';
import ExpressSwagger from '../../dist/index';
import ExampleController from '../controllers/ExampleController';
import AuthService from '../services/AuthService';
import { layout, specification } from './swagger';

class Server {
  constructor() {
    this.server = ExpressSwagger.Server;

    this.server.NODE_ENV = 'test';
    this.server.BASE_HOST = 'localhost';
    this.server.BASE_PATH = '/api';
    this.server.PORT = 8080;

    this.server.setSwaggerProps({
      layout: layout,
      specification: specification,
    });

    this.server.app.use(cors());
    this.server.app.use(helmet());
    this.server.app.use(urlencoded({ extended: true }));
    this.server.app.use(json({ limit: '2gb' }));

    this.server.middleware = this.middleware;
    this.server.authMiddleware = this.authMiddleware;

    ExampleController.setRoutes();

    this.server.initialize();
  }

  authMiddleware(req, res, next) {
    AuthService.checkAuth(req)
      .then((auth) => {
        switch (auth.statusCode) {
          case 200:
            return next();
          case 400:
            return res.status(400).json(auth);
          case 401:
            return res.status(401).json(auth);
        }
      })
      .catch((err) => res.status(500).json(err));
  }

  middleware(req, res, callback) {
    callback(req, res)
      .then((data) => res.status(data.statusCode).json(data))
      .catch((err) => res.status(500).json(err));
  }

  listen = (port) => this.server.listen(port);
}

export default new Server();

To add a route to the server it is necessary to create a file for building routes by calling an option from the ExpressSwagger property and thus passing its parameters, that way the API documentation and route will already be created, see:

Note: The parameter object follows the same structure pattern as swagger.js documentation (openapi: 3.0.0).

import ExpressSwagger from '../../dist/index';
import { specification } from '../configs/swagger';
import Return from '../models/Return';

export default class ExampleController {
  static setRoutes() {
    ExpressSwagger.Server.addRoute({
      auth: true,
      method: 'GET',
      path: '/example',
      tags: ['Example'],
      summary: 'Example Controller',
      security: [specification.components.securitySchemes],
      responses: specification.components.responses,
      handler: async (req) => {
        return new Return(200, 'OK', {
          date: new Date(),
        });
      },
    });

    ExpressSwagger.Server.addRoute({
      auth: true,
      method: 'GET',
      path: '/example/:text',
      tags: ['Example'],
      summary: 'Example Controller',
      security: [specification.components.securitySchemes],
      responses: specification.components.responses,
      parameters: [
        {
          in: 'path',
          required: true,
          name: 'text',
          schema: {
            type: 'string',
          },
          description: 'Text to print in the response',
        },
      ],
      handler: async (req) => {
        return new Return(200, 'OK', {
          date: new Date(),
          text: req.params.text,
        });
      },
    });
  }
}

🔹 Contributors

🔹 License

MIT