0.1.1 • Published 7 years ago

prg-express v0.1.1

Weekly downloads
2
License
MIT
Repository
github
Last release
7 years ago

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.

ParamType
errorstring
statusnumber
codenumber

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

Simpifies starting an Express.js server

Kind: global function
Returns: Object - description

ParamTypeDefaultDescription
appanyserver listener
portnumber | string3000listening port, default 3000
logconsole
procprocessfor testing purposes

Example

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

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

configurator(app, httpConfig, compressionMiddleware)

Kind: global function

ParamTypeDescription
appExpressapplication
httpConfigobjectthe configuration
httpConfig.zlibobject | booleancompression configuration
httpConfig.forceSlashesboolean | nullforcing slashes
httpConfig.trustProxybooleanenables proxytrust
httpConfig.isUsingSslbooleanforces https
httpConfig.excludeRedirectPathsarrayforces https
compressionMiddlewarefunc

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

ParamTypeDescription
optionsObject
logconsolethe 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

ParamTypeDefaultDescription
loggerconsolewhere to log
muteLogsbooleanfalseuse 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

ParamTypeDefaultDescription
callbackfunccalled, when request is finnished
muteLogsbooleanfalsemutes 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

ParamTypeDescription
expressHbsExpressHandlebarsExpress Handlebars
helpersObjectmap of helpers
dataObjectstatic data
hbsHandlebarshandlebars 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}}