Code Monkey home page Code Monkey logo

prg-express's Introduction

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

{AppError}
AppError

Functions

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

Simpifies starting an Express.js server

configurator(app, httpConfig, [compressionMiddleware])
errorMiddleware([options], log)errorMiddleware~error

Return error processing middleware

throwMiddleware(logger, muteLogs)throwMiddleware~throwMid

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

requestLogger(callback, [muteLogs])requestLogger~logger

Creates express middleware for logging duration of requests

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

Attaches compiler helpers which makes some static data compiled once

{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}}

prg-express's People

Contributors

davidmenger avatar

Watchers

 avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.