All Projects → luin → Express Promise

luin / Express Promise

Licence: mit
❤️ Middleware for easy rendering of async Query results.

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Express Promise

Webpack Hmr 3 Ways
Three ways to set up your webpack hot module replacement: webpack-dev-server CLI, webpack-dev-server API, and express with webpack-hot-middleware.
Stars: ✭ 108 (-66.25%)
Mutual labels:  middleware, express
Grant
OAuth Proxy
Stars: ✭ 3,509 (+996.56%)
Mutual labels:  middleware, express
Graphql Serverless
GraphQL (incl. a GraphiQL interface) middleware for the webfunc serverless web framework.
Stars: ✭ 124 (-61.25%)
Mutual labels:  middleware, express
Service Tools
Prepare your Node.js application for production
Stars: ✭ 89 (-72.19%)
Mutual labels:  middleware, express
Express Status Monitor
🚀 Realtime Monitoring solution for Node.js/Express.js apps, inspired by status.github.com, sponsored by https://dynobase.dev
Stars: ✭ 3,302 (+931.88%)
Mutual labels:  middleware, express
Corser
CORS middleware for Node.js
Stars: ✭ 90 (-71.87%)
Mutual labels:  middleware, express
Graphbrainz
A fully-featured GraphQL interface for the MusicBrainz API.
Stars: ✭ 130 (-59.37%)
Mutual labels:  middleware, express
Http Proxy Middleware
⚡ The one-liner node.js http-proxy middleware for connect, express and browser-sync
Stars: ✭ 8,730 (+2628.13%)
Mutual labels:  middleware, express
Connext Js
A middleware and route handling solution for Next.js.
Stars: ✭ 211 (-34.06%)
Mutual labels:  middleware, express
Host Validation
Express.js middleware for "Host" and "Referer" header validation to protect against DNS rebinding attacks.
Stars: ✭ 183 (-42.81%)
Mutual labels:  middleware, express
Redirect Ssl
Connect/Express middleware to enforce https using is-https
Stars: ✭ 81 (-74.69%)
Mutual labels:  middleware, express
Home
Project Glimpse: Node Edition - Spend less time debugging and more time developing.
Stars: ✭ 260 (-18.75%)
Mutual labels:  middleware, express
Bbs node
node后端服务,node+express+mysql, 搭建token-权限-管理完整的web服务, 对应页面: https://www.lyh.red/admin \ https://www.lyh.red/bbs \ 接口地址https://www.lyh.red/apidoc/index.html
Stars: ✭ 78 (-75.62%)
Mutual labels:  middleware, express
Connect Cas2
NodeJS implement of CAS(Central Authentication Service) client.
Stars: ✭ 91 (-71.56%)
Mutual labels:  middleware, express
Express Joi Validation
validate express application inputs and parameters using joi
Stars: ✭ 70 (-78.12%)
Mutual labels:  middleware, express
Resource Router Middleware
🚴 Express REST resources as middleware mountable anywhere
Stars: ✭ 124 (-61.25%)
Mutual labels:  middleware, express
Webpack Isomorphic Dev Middleware
The webpack-dev-middleware, but for isomorphic applications
Stars: ✭ 38 (-88.12%)
Mutual labels:  middleware, express
Rainbow
An Express router middleware for RESTful API base on file path.
Stars: ✭ 53 (-83.44%)
Mutual labels:  middleware, express
Next Session
Simple promise-based session middleware for Next.js, micro, Express, and more
Stars: ✭ 161 (-49.69%)
Mutual labels:  middleware, promise
Express Basic Auth
Plug & play basic auth middleware for express
Stars: ✭ 241 (-24.69%)
Mutual labels:  middleware, express

express-promise

An express.js middleware for easy rendering async query.

Build Status

Cases

1. previously

app.get('/users/:userId', function(req, res) {
    User.find(req.params.userId).then(function(user) {
        Project.getMemo(req.params.userId).then(function(memo) {
            res.json({
                user: user,
                memo: memo
            });
        });
    });
});

1. now

app.get('/users/:userId', function(req, res) {
    res.json({
        user: User.find(req.params.userId),
        memo: Project.getMemo(req.params.userId)
    });
});

2. previously

app.get('/project/:projectId', function(req, res) {
    var field = req.query.fields.split(';');
    var result = {};

    var pending = 0;
    if (field.indexOf('people') !== -1) {
        pending++;
        Project.getField(req.params.projectId).then(function(result) {
            result.people = result;
            if (--pending) {
                output();
            }
        });
    }

    if (field.indexOf('tasks') !== -1) {
        pending++;
        Project.getTaskCount(req.params.projectId).then(function(result) {
            result.tasksCount= result;
            if (--pending) {
                output();
            }
        });
    }

    function output() {
        res.json(result);
    }
});

2. now

app.get('/project/:projectId', function(req, res) {
    var field = req.query.fields.split(';');
    var result = {};

    if (field.indexOf('people') !== -1) {
        result.people = Project.getField(req.params.projectId);
    }

    if (field.indexOf('tasks') !== -1) {
        result.tasksCount = Project.getTaskCount(req.params.projectId);
    }

    res.json(result);
});

Install

$ npm install express-promise

Usage

Just app.use it!

app.use(require('express-promise')());

This library supports the following methods: res.send, res.json, res.render.

If you want to let express-promise support nodejs-style callbacks, you can use dotQ to convert the nodejs-style callbacks to Promises. For example:

require('dotq');
app.use(require('express-promise')());

var fs = require('fs');
app.get('/file', function(req, res) {
    res.send(fs.readFile.promise(__dirname + '/package.json', 'utf-8'));
});

Skip traverse

As a gesture to performance, when traverse an object, we call toJSON on it to reduce the properties we need to traverse recursively. However that's measure has some negative effects. For instance, all the methods will be removed from the object so you can't use them in the template.

If you want to skip calling toJSON on an object(as well as stop traverse it recursively), you can use the skipTraverse option. If the function return true, express-promise will skip the object.

app.use(require('express-promise')({
  skipTraverse: function(object) {
    if (object.hasOwnProperty('method')) {
      return true;
    }
  }
}))

Libraries

express-promise works well with some ODM/ORM libraries such as Mongoose and Sequelize. There are some examples in the /examples folder.

Mongoose

When query a document without passing a callback function, Mongoose will return a Query instance. For example:

var Person = mongoose.model('Person', yourSchema);
var query = Person.findOne({ 'name.last': 'Ghost' }, 'name occupation');

Query has a exec method, when you call query.exec(function(err, result) {}), the query will execute and the result will return to the callback function. In some aspects, Query is like Promise, so express-promise supports Query as well. You can do this:

exports.index = function(req, res){
  res.render('index', {
    title: 'Express',
    cat: Cat.findOne({name: 'Zildjian'})
  });
};

and in the index.jade, you can use cat directly:

p The name of the cat is #{cat.name}

Sequelize

Sequelize supports Promise after version 1.7.0 :)

Articles and Recipes

License

The MIT License (MIT)

Copyright (c) 2013 Zihua Li

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Bitdeli Badge

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].