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

skutil-express

v1.2.1

Published

A further encapsulation of express app, support convenient route definition.

Downloads

10

Readme

A further encapsulation of express app, support convenient route definition.

  • extend with little change from expressJS
  • support async middlewares
  • define controllers similar to nestjs, automatic load all controllers
  • support jwt by express-jwt
  • support ajv validation of query, params, body
  • support an implementation of RDBC and CASL
  • uniform json response by controller return, while support full customization

Install

yarn add skutil-express

Changelog

Changelog

Usage example

/////////////////////////////////////////
// server.js
const express = require('skutil-express');
const bodyParser = require('body-parser')

const app = express();
app.initJWT('123456', { expiresIn: '2h' }, { requestProperty: 'user' })
app.setUserAuth('userAuth', async (jwtAuth) => {
  return { isAdmin: false, roles: ['reader'], permissions: ['book.query'] }
})
app.set('wrap response', true)
app.use(bodyParser.json({ limit: '10mb' }))
app.use(bodyParser.urlencoded({ extended: false }))
app.loadControllers(path.join(__dirname, 'controllers'))
app.startServe(3000)

/////////////////////////////////////////
// controllers/demo.js
const jwtUtil = require('skutil-express-jwt')
module.exports = {
  hello: {
    method: 'get',
    path: '/api/hello',
    handler: function(req, res) {
      res.status(200).send('hello, world')
    }
  },
  helloAgain: {
    method: 'get',
    path: '/api/helloAgain',
    handler: function(req, res) {
      return 'hello, again'
    }
  },
  login: {
    method: 'post',
    path: '/api/user/login',
    bodySchema: {
      type: 'object',
      properties: {
        username: {
          type: 'string',
          pattern: '^[a-zA-Z0-9_-]{5,16}$'
        },
        password: {
          type: 'string',
          format: 'password'
        }
      }
    },
    handler: async function(req, res) {
      const { username, password } = req.validatedBody
      const token = jwtUtil.sign({ id: 1, username })
      return { token }
    }
  },

  getBook: {
    method: 'get',
    path: '/api/books/:id',
    paramsSchema: {
      type: 'object',
      properties: {
        id: { type: 'string' }
      }
    },
    jwt: true,
    permissions: ['book.query'],
    handler: async function(req, res) {
      const { id } = req.validatedParams
      return { id, title: 'Fly' }
    }
  },

  getUser: {
    method: 'get',
    path: '/api/users/:id',
    paramsSchema: {
      type: 'object',
      properties: {
        id: { type: 'string' }
      }
    },
    jwt: true,
    permissions: ['user.query'],
    handler: async function(req, res) {
      const { id } = req.validatedParams
      return { id, username: 'Kevin' }
    }
  }
}

Express extended functions

  interface Express extends express.Express {
    /**
     * The jwt is required by the controller's implementation, and thus need to be initiallized from the app
     * The default algorithm is HS256
     * @param secret
     * @param signOpts the sign options supported by jsonwebtoken, such as `expiresIn`
     * @param verifyOpts the verify options supported by express-jwt, such as `requestProperty`
     * */
    initJWT(secret: string, signOpts?: SignOptions, verifyOpts?: VerifyOpts): undefined;

    /**
     * The jwt sign method to get a token. Use the default sign options from `initJWT` and merged with the options provided.
     * @param payload 
     * @param signOpts 
     */
    jwtSign(payload: string | Buffer | object, signOpts?: SignOpts): string;

    /**
     * get the resolved token from request header
     * @param req the express request
     */
    getJWTResovledData(req: express.Request): object;

    /**
     * @param port http listen port
     */
    startServe: (port: number) => undefined;

    /**
     * @param key the key of fetched user authorizaton data appending to request
     * @param fn the function to fetch user authorizaton data. the in param `jwtAuth` is the decoded data from jwt
     */
    setUserAuth: (key: string, fn: (jwtAuth: object) => UserAuthorization | Promise<UserAuthorization>) => undefined;

    /**
     * @param path directory of controllers
     */
    loadControllers: (path: string) => undefined;
  }

Controller explaination

  1. Controller files are loaded recursively
  2. A controller file contains group of routes, supports array and object(like in the examples above). For object, the key of route is useless.
  3. A Controller route is an object with the following fields:
  • method: String. The http method supported by express
  • path: String. The route path
  • schema: Object. Contains at least one of query, params, body fields, each field is a valid ajv schema.
  • querySchema, paramsSchema, bodySchema: a convenient way to define schema.
    • The query, params, body of request will not change after ajv validation. Instead, the validated data will be appended to the request as validatedQuery, validatedParams, validateBody.
  • jwt: Boolean. Use jwt verification or not.
  • roles: Array. The keys of roles allowed to access. if roles is used, then the function provided by app.setUserAuth must return the roles assigned to the user, or the authorization will fail.
  • permissions: Array. The keys of permissions allowed to access. if permissions is used, then the function provided by app.setUserAuth must return the permissions assigned to the user, or the authorization will fail.
  • handler: the function handling the request in format. async function and error thrown are supported. the result returned by the handler will be send to the client.
    • the default response body is in json format of { code, message, data }, the result of function return is the data part.
  • midwares: The additional middlewares of express.
  1. The fields of a controller route take effect in the order of jwt -> roles/permissions -> midwares -> schema/querySchema/paramsSchema/bodySchema ->handler. Once a part throws an error, the process stops and a http error response is returned to the client. The default error response body is in json form of { code, message }. The suggested error module used in your application is the well-known http-errors package.

Resonse and Errors

  1. The default success/error response is in json format of { code, message, data }.
  • code is generally the same as statusCode. You can also specify a custom code in errors through a customCode or code field. If you use a code field in errors for custom code, then a statusCode or status field can be used to specify the statusCode.
  • message is the message of the error, or ok.
  • data is the result of the handler function return. An error response has no data field.
  • A string thrown is also allowed, in which case the statusCode would be 500.

Maintainers