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

@qest/express-utils

v1.0.3

Published

Base features and settings for express framework to projects

Downloads

2,507

Readme

Express utils

Make our express applications normalized, use same error handling, requests logging, etc. Make same security settings and outputs for all aplications.

Package include basic normalized express server with pre and post middlewares for each requests (like cors, rate limiter, body parsing, etc). Package has simply error handler for each request witch correctly work with throwed HTTP errors from @qest/error-utils package. Also log each error or request with @qest/logger-utils package or custom logger.

Instalation

Install package to our dependencies from NPM.

yarn add @qest/express-utils

or

npm install @qest/express-utils

What is in package

Server

It make instance of express server with our routes and some default features.

const expressServer: (options: IExpressApp, config?: IExpressConfig) => core.Express= server({...}, {...});

Options parameters

  • router: Router - Router for our application.
  • logger ?: ILogger - Implementation of logger interface, whitch is used for predefined request logger or error handler.
  • middlewares - Basic middlewares whitch is used for all requests.
    • rateLimiter?: Handler - Middleware for rate limiting. You can use predefined rateLimiter.
    • logRequest?: Handler - If you can log each request to some logging service. You can use predefined logRequest whitch use ILogger implementation.
    • notFoundHandler?: Handler - Handler for normalization of not recognized routes from router. You can use predefined notFoundHandler.
    • errorHandler?: ErrorRequestHandler - Our custom error handler or predefined errorHandler.
  • preMiddleware?: Handler[] - Custom middlewares which is before router.
  • postMiddleware?: Handler[] - Custom middlewares which is after router.
  • bodyParser?: Handler - Custom body parsing middleware, if it isn't set, default parser is from package body-parser.
  • urlParser?: Handler - Custom url parsing middleware, if it isn't set, default parser is from package body-parser.

Config parameters

  • useSentry?: boolean - If it's true, Sentry.Handlers.errorHandler was used. Default value is false
  • useDefaultMiddlewares?: boolean - If it's true, preconfigured middlewares from this package was used. Every default middleware you can override via options middlewares Default middlewares are with this setting:
    notFoundHandler,
    errorHandler: errorHandler(logger),
    logRequest: logRequest(logger),
    rateLimiter: rateLimiter({ windowMs: 5 * 1000, max: 500, enabled: true }),

Usage

First you must have router for our application with controllers of each route.

If you type controllers for routes, every must have try-catch statement with calling next function in catch. It's important for error handling.

You can use prepared controllers for robots.txt and favicon.ico.

import { Router } from 'express';
import { getFavicon, getRobots } from '@qest/express-utils';

export const router = Router()
    // use predefined controllers
    .get('/favicon.ico', getFavicon)
    .get('/robots.txt', getRobots)  
    
    //
    .get('/', (req, res, next) => {
        //
        try {
            res.send({ foo: 'bar' });
        } catch (e) {
            next(e);    
        }
    })        
    
    // some controllers may be throw errors in code
    .get('/throw', (req, res, next) => {
        try {
            new Error('throwed error');
        } catch (e) {
            next(e);
        }
    }); // some route throw error, because there is mistake

Controller getFavicon return no-content response with status 204. Controller getRobots return text with disalow indexing.

Now you must have prepared logger whitch implemented 'ILogger', or you can use our logger from @qest/logger-utils package.

import { ILoggger } from '@qest/express-utils';

const logger: ILogger = {
    fatal: msg => console.error(msg),
    error: msg => console.error(msg),
    warn: msg => console.warn(msg),
    info: msg => console.info(msg),
    debug: msg => console.debug(msg),
    trace: msg => console.trace(msg),
}

Now you can configure our express server and listen to them.

import { server, corsSetup } from './dist';

const expressServer = server({
    logger,
    router,
    preMiddleware: [corsSetup('*')],   
}, {
    useDefaultMiddlewares: true,
});

export const listen = () => {
    return expressServer
        .listen(8080, () => {
            logger.info('[Express] Listening at 8080');
        })
        .on('error', (e) => logger.error(e));
};

listen();