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

prg-express

v0.1.1

Published

Express utitlities for automatic https redirects, slash forcing, logging, error handling and Handlebars templating

Downloads

4

Readme

Pragonauts Express Tools

Usefull tools for:

  • starting express app in one line
  • handling errors within Express.js with app.use(errorMiddleware())
  • throwing nice JSON errors with res.throw(401);
  • measuring request duration and logging with app.use(requestLogger())
  • cache some static data in templates using hbsStaticHelpers
  • having nice new AppError('Missing attribute', 400, 4596)
  • forcing slashes in url with configurator
  • redirecting to https with configurator
  • enabling trust proxy with configurator
  • enabling compression with configurator

API

Classes

Functions

{AppError}

Kind: global class

new {AppError}()

Class with prepared status and code for {throwMiddleware} and for {errorMiddleware}

AppError

Kind: global class

new AppError(error, status, code)

Creates an instance of AppError.

| Param | Type | | --- | --- | | error | string | | status | number | | code | number |

createWebserver(app, [port], [log], [proc]) ⇒ Object

Simpifies starting an Express.js server

Kind: global function
Returns: Object - description

| Param | Type | Default | Description | | --- | --- | --- | --- | | app | any | | server listener | | [port] | number | string | 3000 | listening port, default 3000 | | [log] | console | | | | [proc] | process | | for testing purposes |

Example

const express = ('express');
const { createWebserver } = require('prg-express');

const app = express();
createWebserver(app).start();

configurator(app, httpConfig, [compressionMiddleware])

Kind: global function

| Param | Type | Description | | --- | --- | --- | | app | Express | application | | httpConfig | object | the configuration | | [httpConfig.zlib] | object | boolean | compression configuration | | [httpConfig.forceSlashes] | boolean | null | forcing slashes | | [httpConfig.trustProxy] | boolean | enables proxytrust | | [httpConfig.isUsingSsl] | boolean | forces https | | [httpConfig.excludeRedirectPaths] | array | forces https | | [compressionMiddleware] | func | |

Example

// theese are default values
const { configurator } = require('prg-express');

configurator(app, {
     zlib: { threshold: 1024 },// true=enable with default params, false=dont attach zlib
     forceSlashes: false,      // true=with slashes, false=without slashes, null=dont redirect
     trustProxy: true,
     isUsingSsl: false,        // redirect to https
     redirectWww: true,        // redirect from www to base domain
     excludeRedirectPaths: []  // exlude from forcing slashes
});

errorMiddleware([options], log) ⇒ errorMiddleware~error

Return error processing middleware

Kind: global function
Returns: errorMiddleware~error - - the middleware

| Param | Type | Description | | --- | --- | --- | | [options] | Object | | | log | console | the logger |

Example

const { errorMiddleware } = require('prg-express');

app.use(errorMiddleware({
     errorView: '500', // error template name
     attachStackTraces: false,
     logLevel: 'error', // which method will be called on log object
     mute: false        // mutes error logging for testing purposes
}));

throwMiddleware(logger, muteLogs) ⇒ throwMiddleware~throwMid

Creates middleware, which allows simple logging and error responding in API

Kind: global function
Returns: throwMiddleware~throwMid - - the middleware

| Param | Type | Default | Description | | --- | --- | --- | --- | | logger | console | | where to log | | muteLogs | boolean | false | use true for tests |

Example

const express = require('express');

const app = express();

app.use(throwMiddleware());

app.get('/', (req, res) => {
     res.throw(401, 'Unauthorized'); // log as info
     // responds with { code: 401, error: 'Unauthorized' }
     res.throw(403);                 // log as info with default message
     res.throw(401, true);           // log as error

     const err = new Error('Failed');
     err.code = 345;   // will be used in response json
     err.status = 400; // will be used as http status
     res.throw(err);

     const err = new Error('Failed');
     err.code = 457;   // will be used in response json
     res.throw(err);   // status will be set regarding to first digit of code
});

requestLogger(callback, [muteLogs]) ⇒ requestLogger~logger

Creates express middleware for logging duration of requests

Kind: global function
Returns: requestLogger~logger - - returns the middleware

| Param | Type | Default | Description | | --- | --- | --- | --- | | callback | func | | called, when request is finnished | | [muteLogs] | boolean | false | mutes logs for testing |

Example

app.use(requestLogger((data) => {
     const {
         message,
         url,
         method,
         responseTime,
         status,
         referrer,
         remoteAddr
     } = data;
}));

hbsStaticHelpers(expressHbs, helpers, [data], [hbs]) ⇒ ExpressHandlebars

Attaches compiler helpers which makes some static data compiled once

Kind: global function

| Param | Type | Description | | --- | --- | --- | | expressHbs | ExpressHandlebars | Express Handlebars | | helpers | Object | map of helpers | | [data] | Object | static data | | [hbs] | Handlebars | handlebars library |

Example

const { hbsStaticHelpers } = require('prg-express');

// setup templating
const hbs = expressHandlebars.create({
    defaultLayout: 'index',
    extname: '.hbs',
    layoutsDir: LAYOUTS_PATH,
    partialsDir: VIEWS_PATH,
    helpers
});

// setup template caching
if (!config.debugEnabled) {
    app.enable('view cache');
}

// setup compile-time helpers {{$xkf kdkd}}
hbsStaticHelpers(hbs, helpers, app.locals);

// attach template engine
app.set('views', VIEWS_PATH);
app.engine('hbs', hbs.engine);
app.set('view engine', 'hbs');

// will be staticly executed in compilation time
{{$staticHelper 'param'}}
// will be staticly loaded from data
{{$dataParam}}