Skip to content

Commit

Permalink
Everything updated for blog post
Browse files Browse the repository at this point in the history
  • Loading branch information
marcusoftnet committed May 12, 2015
1 parent 63dffae commit ff824b8
Show file tree
Hide file tree
Showing 15 changed files with 201 additions and 25 deletions.
9 changes: 6 additions & 3 deletions apis/address/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ app.use(routes.put("/:id", update));
app.use(routes.del("/:id", remove));

// Fire it up
app.listen(3000);
if(process.env.standalone){
app.listen(3000);
}
console.log("The app is listening. Port 3000");


Expand All @@ -31,7 +33,7 @@ function *add() {

var insertedAddress = yield addresses.insert(postedAddress);

this.set("location", "/" + insertedAddress._id);
this.set("location", this.originalUrl + "/" + insertedAddress._id);
this.status = 201;
};

Expand All @@ -46,7 +48,8 @@ function *update(id) {

yield addresses.updateById(id, postedAddress);

this.set("location", "/" + id);
var prefixOfUrl = this.originalUrl.replace(id, "");
this.set("location", prefixOfUrl + id);
this.status = 204;
};

Expand Down
2 changes: 1 addition & 1 deletion apis/address/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"description": "The Address API",
"main": "index.js",
"scripts": {
"start": "node --harmony index.js",
"start": "node --harmony index.js standalone",
"test": "./node_modules/mocha/bin/mocha --harmony-generators -u bdd -R dot"
},
"author": "Marcus Hammarberg",
Expand Down
1 change: 0 additions & 1 deletion apis/order/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,4 @@ app.use(routes.del("/:id", orderRoutes.remove));
app.use(routes.get("/user/:userId", orderRoutes.getForUser));

// Fire it up
app.listen(3000);
console.log("The app is listening. Port 3000");
5 changes: 3 additions & 2 deletions apis/order/orderRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ module.exports.add = function * () {

var insertedOrder = yield orders.insert(postedOrder);

this.set("location", "/order/" + insertedOrder.orderId);
this.set("location", this.originalUrl + "/" + insertedOrder.orderId);
this.status = 201;
};

Expand All @@ -38,7 +38,8 @@ module.exports.update = function * (orderId) {

yield orders.update({ orderId : orderId }, orderFromRequest);

this.set("location", "/" + orderId);
var prefixOfUrl = this.originalUrl.replace(orderId, "");
this.set("location", prefixOfUrl + orderId);
this.status = 204;
}

Expand Down
9 changes: 4 additions & 5 deletions apis/user/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,10 @@ var routes = require("koa-route");

// routes
var userRoutes = require("./userRoutes.js");
app.use(routes.post("/user", userRoutes.add));
app.use(routes.get("/user/:id", userRoutes.get));
app.use(routes.put("/user/:id", userRoutes.update));
app.use(routes.del("/user/:id", userRoutes.remove));
app.use(routes.post("/", userRoutes.add));
app.use(routes.get("/:id", userRoutes.get));
app.use(routes.put("/:id", userRoutes.update));
app.use(routes.del("/:id", userRoutes.remove));

// Fire it up
app.listen(3000);
console.log("The app is listening. Port 3000");
4 changes: 2 additions & 2 deletions apis/user/test/user.del.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ var helpers = require('./testHelpers.js');
var users = helpers.users;
var request = helpers.request;

describe('DEL to /user/:id', function(){
describe('DEL user /:id', function(){

var test_user = {};

Expand All @@ -20,7 +20,7 @@ describe('DEL to /user/:id', function(){
co(function *() {
// Insert test user in database
var user = yield users.insert(test_user);
var userUrl = '/user/' + user._id;
var userUrl = '/' + user._id;

// Delete the user
request
Expand Down
4 changes: 2 additions & 2 deletions apis/user/test/user.get.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ var helpers = require('./testHelpers.js');
var users = helpers.users;
var request = helpers.request;

describe('GET /user/:id ', function(){
describe('GET user /:id ', function(){

var test_user = {};

Expand All @@ -20,7 +20,7 @@ describe('GET /user/:id ', function(){
co(function *() {
// Insert test user in database
var user = yield users.insert(test_user);
var userUrl = '/user/' + user._id;
var userUrl = '/' + user._id;

// Get
request
Expand Down
9 changes: 4 additions & 5 deletions apis/user/test/user.post.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,13 @@ describe('POST to /user', function(){
it('creates a new user for complete posted data', function(done){
// Post
request
.post('/user')
.post('/')
.send(test_user)
.expect('location', /^\/user\/[0-9a-fA-F]{24}$/) // Mongo Object Id /user/234234523562512512
.expect('location', /^\/[0-9a-fA-F]{24}$/) // Mongo Object Id /234234523562512512
.expect(201)
.end(function () {
co(function *() {
var userFromDb = yield users.findOne({ name : test_user.name });
// userFromDb.name.should.equal("This is not the name you are looking for");
userFromDb.name.should.equal(test_user.name);
}).then(done, done);
});
Expand All @@ -37,7 +36,7 @@ describe('POST to /user', function(){
var u = { city : "A city without a user name"};

request
.post('/user')
.post('/')
.send(u)
.expect('ValidationError', "Name is required")
.expect(200, done);
Expand All @@ -47,7 +46,7 @@ describe('POST to /user', function(){
var u = { name : "A name without a city"};

request
.post('/user')
.post('/')
.send(u)
.expect('ValidationError', "City is required")
.expect(200, done);
Expand Down
2 changes: 1 addition & 1 deletion apis/user/test/user.update.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ describe('PUT to /user', function(){
co(function *() {
// Insert test user in database
var user = yield users.insert(test_user);
var userUrl = '/user/' + user._id;
var userUrl = '/' + user._id;

request
.put(userUrl)
Expand Down
6 changes: 3 additions & 3 deletions apis/user/userRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ module.exports.users = users;

module.exports.add = function * () {
var postedUser = yield parse(this);

if(!exists(postedUser.name)){
this.set('ValidationError', 'Name is required');
this.status = 200;
Expand All @@ -23,7 +22,7 @@ module.exports.add = function * () {

var insertedUser = yield users.insert(postedUser);

this.set("location", "/user/" + insertedUser._id);
this.set("location", this.originalUrl + "/" + insertedUser._id);
this.status = 201;
};

Expand All @@ -38,7 +37,8 @@ module.exports.update = function * (id) {

yield users.updateById(id, userFromRequest);

this.set("location", "/user/" + id);
var prefixOfUrl = this.originalUrl.replace(id, "");
this.set("location", prefixOfUrl + id);
this.status = 204;
}

Expand Down
15 changes: 15 additions & 0 deletions authentication.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
module.exports.reqBasic = function *(next){
try {
yield next;
}
catch (err) {
if (401 == err.status) {
this.status = 401;
this.set('WWW-Authenticate', 'Basic');
this.body = 'Nope... you need to authenticate first. With a proper user!';
}
else {
throw err;
}
}
};
26 changes: 26 additions & 0 deletions config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
var adminUser = {
name : process.env.BASIC_USER || 'ypkbk',
pass : process.env.BASIC_PASS || 'ypkbk'
};

var config = {
local: {
mode: 'local',
port: 3000,
adminUser : adminUser
},
testing: {
mode: 'testing',
port: 4000,
adminUser : adminUser
},
prod: {
mode: 'prod',
port: process.env.PORT || 5000,
adminUser : adminUser
}
};

module.exports = function (mode) {
return config[mode || process.argv[2] || 'local'] || config.local;
};
33 changes: 33 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
var koa = require('koa');
var app = module.exports = koa();
var mount = require('koa-mount');
var config = require("./config.js")();

// The root application
var rootApp = koa();
rootApp.use(function *(next){
yield next;
this.body = 'Find the APIs under /user, /order and /address respectively';
});

// APIS
var userApi = require('UserAPI');
var addressApi = require('AddressAPI');
var orderApi = require('OrderAPI');

// Mounting
app.use(mount('/', rootApp));
app.use(mount('/users', userApi));
app.use(mount('/address', addressApi));


// middleware configuration
var auth = require('koa-basic-auth');
var userAuth = require('./authentication.js');
app.use(userAuth.reqBasic);
app.use(mount('/orders', auth(config.adminUser)));
app.use(mount('/orders', orderApi));

// listen and all of that
app.listen(config.port);
console.log("listening on port " + config.port);
39 changes: 39 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
{
"name": "UserApiWithTest",
"version": "1.0.0",
"description": "The overarching application for the 3 apis",
"main": "index.js",
"scripts": {
"start": "node --harmony index.js prod",
"startLocal": "nodemon --harmony index.js",
"test": "./node_modules/mocha/bin/mocha --harmony-generators -u bdd -R spec"
},
"repository": {
"type": "git",
"url": "https://github.com/marcusoftnet/UserApiWithTest.git"
},
"keywords": [
"koa",
"api",
"rest",
"supertest"
],
"author": "Marcus Hammarberg @marcusoftnet",
"license": "MIT",
"bugs": {
"url": "https://github.com/marcusoftnet/UserApiWithTest/issues"
},
"homepage": "https://github.com/marcusoftnet/UserApiWithTest",
"dependencies": {
"AddressAPI": "file:apis/address",
"OrderApi": "file:apis/order",
"UserAPI": "file:apis/user",
"koa": "^0.20.0",
"koa-basic-auth": "^1.1.2",
"koa-mount": "^1.3.0"
},
"devDependencies": {
"mocha": "^2.2.4",
"supertest": "^0.15.0"
}
}
62 changes: 62 additions & 0 deletions test/rootApp.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/// <reference path="../typings/mocha/mocha.d.ts"/>
var supertest = require('supertest');
var app = require("../");
var config = require('../config')();
var request = supertest.agent(app.listen());

describe('Our application', function () {
it('has a simple root application', function (done) {
request
.get('/')
.expect(200)
.expect(/Find the APIs under/)
.end(done);
});
it('an user api to which we can post', function (done) {
request
.post('/users')
.send({ name: 'Marcus', city : 'Bandung, Indonesia'})
.expect(201)
.expect('location', /^\/users\/[0-9a-fA-F]{24}$/)
.end(done);
});
it('and an address api to which we can post', function (done) {
var test_address = {
userId: 987654321,
street : 'Jalan Jawa No 20',
city : 'Bandung',
country: 'Indonesia'
};

request
.post('/address')
.send(test_address)
.expect(201)
.expect('location', /^\/address\/[0-9a-fA-F]{24}$/)
.end(done);
});
it('and an order api, but that requires login', function (done) {
var test_order = {
orderId: '123456789',
ordered : new Date("2015-01-01"),
userId : "987654321"
};

request
.post('/orders')
.auth(config.adminUser.name, config.adminUser.pass)
.send(test_order)
.expect('location', /^\/orders\/[0-9]{9}$/)
.expect(201)
.end(done);
});
it('exactly - the order API require login. Not logging in will give you access', function (done) {
var test_order = { };

request
.post('/orders')
.send(test_order)
.expect(401)
.end(done);
});
});

0 comments on commit ff824b8

Please sign in to comment.