第一个RESTful API

一个简单的测试

/**
 * Created by M.C on 2017/9/8.
 */

var superagent = require('superagent');
var expect = require('expect.js');



describe('express rest api server', function () {
    var id;

    it('post object', function (done) {
        superagent.post('http://localhost:3000/collections/test')
            .send({
                name: 'James',
                email: 'james@qq.com'
            })
            .end(function (err, res) {
                expect(err).to.eql(null);
                expect(res.body.length).to.eql(1);
                expect(res.body[0]._id.length).to.eql(24);
                id = res.body[0]._id;
                done();
            });
    });

    it('retrieves an object', function (done) {
        superagent.get('http://localhost:3000/collections/test/' + id)
            .end(function (err, res) {
                expect(err).to.eql(null);
                expect( typeof res.body).to.eql('object');
                // expect(res.body._id.length).to.eql(24);
                expect(res.body._id).to.eql(id);
                done();
            });
    });

    it('retrieves a collection', function (done) {
        superagent.get('http://localhost:3000/collections/test')
            .end(function (err, res) {
                expect(err).to.eql(null);
                expect(res.body.length).to.be.above(0);
                expect(res.body.map(function (item) {
                    return item._id;
                })).to.contain(id);
                done();
            });
    });

    it('updates an object', function (done) {
        superagent.put('http://localhost:3000/collections/test/' + id)
            .send({
                name: 'Bond',
                email: 'bond@qq.com'
            })
            .end(function (err, res) {
                expect(err).to.eql(null);
                expect(typeof res.body).to.eql('object');
                expect(res.body.msg).to.eql('success');
                done();
            });
    });

    it('checks an updated object', function (done) {
        superagent.get('http://localhost:3000/collections/test/' + id)
            .end(function (err, res) {
                expect(err).to.eql(null);
                expect( typeof res.body).to.eql('object');
                expect(res.body._id.length).to.eql(24);
                expect(res.body._id).to.eql(id);
                done();
            });
    });

    it('remove an object', function (done) {
        superagent.del('http://localhost:3000/collections/test/' + id)
            .end(function (err, res) {
                expect(err).to.eql(null);
                expect(typeof res.body).to.eql('object');
                expect(res.body.msg).to.eql('success');
                done();
            });
    });

});


一个简单的api

/**
 * Created by M.C on 2017/9/8.
 */

const express = require('express'),
    mongoskin = require('mongoskin'),
    bodyParser = require('body-parser'),
    logger = require('morgan');

const app = express();

app.use(bodyParser.urlencoded());
app.use(bodyParser.json());
app.use(logger());

const db = mongoskin.db('mongodb://@localhost:27017/test', {safe: true});

const id  = mongoskin.helper.toObjectID;

app.param('collectionName', function (req, res, next, collectionName) {
    req.collection = db.collection(collectionName);
    return next();
});

app.get('/',function (req, res, next) {
    res.send('Select a collection,e.g., /collections/messages');
});

app.get('/collections/:collectionName', function (req, res, next) {
    req.collection.find({}, {limit: 10, sort: [['_id', -1]]})
        .toArray(function (err, results) {
            console.info(err);
            if (err) return next();
            res.send(results);
        });
});

app.post('/collections/:collectionName', function (req, res, next) {
    req.collection.insert(req.body, {}, function (err, results) {
        if (err) return next();
        res.send(results);
    });
});

app.get('/collections/:collectionName/:id', function (req, res, next) {
    req.collection.findOne({_id: id(req.params.id)}, function (err, result) {
        console.info(result._id);
        if (err) return next();
        res.send(result);
    });
});

app.put('/collections/:collectionName/:id',function (req, res, next) {
    req.collection.update({
        _id: id(req.params.id)
    }, {
        $set: req.body
    }, {
        safe: true, multi: false
    }, function (err, result) {
        console.info('Put error: ' + err);
        console.info('Put result: ' + result);
        if (err) return next();
        res.send((result === 1) ? {msg: 'success'} : {msg: 'error'});
    });
});

app.del('/collections/:collectionName/:id', function (req, res, next) {
    req.collection.remove({_id: id(req.params.id)}, function (err, result) {
        if (err) return next();
        res.send((result === 1) ? {msg: 'success'} : {msg: 'error'});
    });
});

app.listen(3000, function () {
    console.log('Server is running');
});

posted @ 2017-09-09 01:51  马在路上  阅读(493)  评论(0编辑  收藏  举报