• Stars
    star
    317
  • Rank 132,216 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 11 years ago
  • Updated almost 9 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

❤️ Middleware for easy rendering of async Query results.

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

More Repositories

1

medis

💻 Medis is a beautiful, easy-to-use Mac database management application for Redis.
JavaScript
11,605
star
2

readability

📚 Turn any web page into a clean view
HTML
2,480
star
3

wechat-export

📃 Export WeChat chat histories to HTML files.
C
674
star
4

ranaly

📈 An easy to use chart system
JavaScript
498
star
5

CodeGame

🎮 JavaScript AI tank game
JavaScript
349
star
6

express-di

Dependency injection for Express applications
JavaScript
160
star
7

npm-try

🚆 Quickly try npm packages without writing boilerplate code.
TypeScript
113
star
8

bazinga

💥 The best all-in-one toolbox. Bazinga!
TypeScript
110
star
9

redis-book-assets

《Redis入门指南》第五章程序代码
JavaScript
92
star
10

serialize

Serialize an object including it's function into a JSON.
JavaScript
79
star
11

superfetch

A super powerful node.js HTTP client with the support of promise.
JavaScript
77
star
12

Hits-the-mole

The Hits-the-mole game implemented in pure CSS
CSS
62
star
13

colortype

A responsive WordPress theme
PHP
38
star
14

OhMyPullRequests

🚀 Access my pull requests from the menu bar
Swift
30
star
15

node_ranaly

Ranaly client library
JavaScript
19
star
16

express-mongoose

JavaScript
15
star
17

SwiftJSONFormatter

🪞 Formatter JSON delightfully.
Swift
15
star
18

teascript

Synchronous JavaScript
JavaScript
13
star
19

slicee

a CLI version of slicy.
Ruby
13
star
20

typo

妈妈从此再也不怕我输错属性(方法)名了!
JavaScript
12
star
21

dotQ

Yet another Q.
JavaScript
10
star
22

redis-book-v3-code

JavaScript
8
star
23

Tribbble

A Dribbble client for iPhone
Objective-C
7
star
24

blog

My blog
HTML
6
star
25

php-lugit-framework

简单优雅的PHP前端框架。
PHP
6
star
26

the-css-that-you-dont-know-about

你不知道的 CSS
HTML
6
star
27

quicker-npm-run

Alternative to `npm run` with support for autocomplete.
JavaScript
4
star
28

scene

A tiny front-end framework designed with ❤️
JavaScript
4
star
29

splitargs

Splitting Redis arguments as redis-cli
JavaScript
3
star
30

Suki

An elegant web framework for node.js
CoffeeScript
3
star
31

guokroup

将果壳所有小组的最新贴子显示在一页
CoffeeScript
3
star
32

cheerio-tester

Test the cheerio selector online
JavaScript
3
star
33

sample-NSSplitViewControlller

Swift
2
star
34

buddybook

books for buddies.
JavaScript
1
star
35

superspider

A powerful and distributed spider library used to crawl the web with the API of jQuery
1
star
36

3-key

⌨️ Personal key mapping for The Key.
C
1
star
37

SwiftPHPSerialization

Swift implementation of PHP's `serialize` and `unserialize`.
Swift
1
star
38

GameEngineSuki

A JavaScript Game Engine
CoffeeScript
1
star
39

express-sequelize

Adds Sequelize Promise support to Express rendering.
JavaScript
1
star
40

Threes-AI

A Threes! AI
CoffeeScript
1
star
41

dribbble

A full-featured Dribbble client for Node.js
JavaScript
1
star
42

my-first-ios-app

Swift
1
star
43

aqsort

An implementation of asynchronous quicksort in JavaScript
JavaScript
1
star