ep

expressjs-plus

A pluggable expansion to express js aimed at adding much needed features and helpers.

Showing:

Popularity

Downloads/wk

7

GitHub Stars

3

Maintenance

Last Commit

4yrs ago

Contributors

0

Package

Dependencies

8

Size (min+gzip)

27.2KB

License

MIT

Type Definitions

Tree-Shakeable

No?

Categories

Readme

Build Status

Description

The main feature of this library is the getMiddlewareVersion function which facilitates passing variables between middlewares seamlessly. A great feature of this library is that it allows its users to create their own handlers for passing variables.

Usage

var express = require('express');
var ExpressPlus = require('expressjs-plus').ExpressPlus;
var app = express();
// simple handler example
var userHandler = function (param, paramsArray, req, res) {
    if (param !== 'user') return false;
    paramsArray.push("USER WAS FOUND!");
    return true;
};

// this handler allows you to pass res.locals properties between your middlewares seemingly,
// it the parameter was found in locals, it attaches it to paramsArray.
var resLocalsHandler = function (param, paramsArray, req, res) {
    if (param in res.locals) {
        paramsArray.push(res.locals[param]);
        return true;
    } else return false;
};
var appPlus = new ExpressPlus(app, [userHandler, resLocalsHandler], []);
var regularFunction = function (user, id, cb) {
    return cb(null, {response: {user: user, id: id}, status: 200, resLocalsVar: "passVar"});
};

// resLocalsVar was passed in a previous method
var regularFunction2 = function (resLocalsVar, user, id, cb) {
    // now you can have access to it
    console.log(resLocalsVar);
    return cb(null);
};

// the responder at the end will use res.locals.status and res.locals.response to issue an HTTP response
app.use(appPlus.GMV(regularFunction), appPlus.GMV(regularFunction2), appPlus.responder);

// adds error handlers, it will add a default error handler along with the list of error handlers passed
// in this case, no error handlers were passed
appPlus.setErrorHandlers();

app.listen(3001, function () {
    console.log('Listening!');
});

Another example for a paramHandler

function userHandler(param, paramsArray, req){
    if(param === 'user'){
        paramsArray.push(req.user);
        return true;
    }else{
        return false;
    }
}

Install

npm install expressjs-plus

ExpressPlus

Kind: global class

new exports.ExpressPlus(app, passedParamHandlers, passedErrorHandlers)

This function abstracts the constraints of express middleware signature and allows you to easily pass variables between middlewares without ugly code. It introduces a neat pattern for passing these variables.

ParamTypeDescription
appObjectexpress app object
passedParamHandlersArrayarray of functions in the format of @see lastHandler
passedErrorHandlersArrayarray of middlewares

expressPlus.HTTPError

Kind: instance class of ExpressPlus

new this.HTTPError(status, errCode)

Generic error handler

ParamTypeDescription
statusNumberHTTP error code
errCodeStringerrorCode, the error handler should handle this

expressPlus.getMiddlewareVersion ⇒

Returns a middleware version of the function passed, this function replaces the last parameter with a callback function to work with express js.

Kind: instance property of ExpressPlus
Returns: function

ParamTypeDescription
funcfunctionthe function to be converted

Example

function regularFunc(someVar, cb){
    console.log(someVar);
    return cb(null, {response: someVar+="addedString"});
}
// middleware version of regularFunc
var func = GMV(regularFunc);

// func will behave like this
function mw(req, res, next){
    let someVar = req.query.someVar;
    console.log(someVar);
    res.locals.response = someVar+="addedString";
    return next();
}

expressPlus.getMiddlewareVersionPromise ⇒

Similar to GMV @see GMV but accepts promises instead

Kind: instance property of ExpressPlus
Returns: function

ParamTypeDescription
promisePromisethe promise to be converted

Example

function regularPromise = (someVar) => {
// you can use co as well
    return new Promise((resolve, reject) => {
        resolve({ response: {user: user, id: id}, status: 123 });
    });
}
// middleware version of regularFunc
var func = GMVPromise(regularFunc);

expressPlus.setErrorHandlers()

sets error handlers, make sure to use this last

Kind: instance method of ExpressPlus

expressPlus.responder(req, res, next)

Handles responses. Other middlewares need to use locals to pass data to this function

Kind: instance method of ExpressPlus

ParamTypeDescription
reqObjectrequest object
resObjectresponse object
res.statusfunctionfunction to set the status
res.localsObjectobject that is used to pass data around
res.locals.statusNumberContains HTTP status code
res.locals.responseObjectContains the response body
nextfunction

expressPlus.defaultCbWithResponse(cb, [status])

Handles callbacks and puts response & status in the second callback argument if successful Replace your callback with this if appropriate.

Kind: instance method of ExpressPlus

ParamTypeDefaultDescription
cbfunctioncallback function
[status]Number204optional argument to pass specific HTTP code if no errors were found if the status is 204, no response will be returns according to HTTP codes.

expressPlus.defaultCb(cb, [resource])

Handles callbacks. Replace your callback with this if appropriate.

Kind: instance method of ExpressPlus

ParamTypeDescription
cbfunctioncallback function
[resource]Objectoptional argument to return instead of the actual result

expressPlus.useArray(middlewares)

Enables sending array of middlewares to app.use

Kind: instance method of ExpressPlus

Param
middlewares

ExpressPlus~lastHandler(param, paramsArray, req, res) ⇒ boolean

Default parameter handler used in getMiddlewareVersion. Every parameter is passed to a set of functions to be handled, this is the last handler that just pushes the parameter to the paramsArray.

Kind: inner method of ExpressPlus
Returns: boolean - if true is returned, the parameter will be considered handled and the function GMV will move on to the next parameter. if false is returned, the next handler on the list will attempt to handle the parameter until this methods turn comes, which will always return true
See: dataHandler this function is a more real example of a parameter handler, it is used to integrate with another library https://www.npmjs.com/package/simple-express-validator

ParamTypeDescription
paramStringstring parameter
paramsArrayArrayparameter arrays which will be sent to the underlying function of the middleware
reqObjectexpress request object that is used in middlewares, useful for accessing req.params, req.query, etc
resObjectexppress response object that is used in middlewares, could be useful if you want to access res.locals

Testing

npm test

© 2016 A Amri a.amri.91@gmail.com

Rate & Review

Great Documentation0
Easy to Use0
Performant0
Highly Customizable0
Bleeding Edge0
Responsive Maintainers0
Poor Documentation0
Hard to Use0
Slow0
Buggy0
Abandoned0
Unwelcoming Community0
100
No reviews found
Be the first to rate

Alternatives

No alternatives found

Tutorials

No tutorials found
Add a tutorial