Skip to content

Commit

Permalink
migrate to koa@2 (#108)
Browse files Browse the repository at this point in the history
* support async/await

* change nodejs version 4 or 6 to 5.6

* eslint

* remove jade
  • Loading branch information
isdongyu authored and haoxin committed May 30, 2017
1 parent 7fc965b commit 50bcadf
Show file tree
Hide file tree
Showing 36 changed files with 349 additions and 354 deletions.
4 changes: 2 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
node_js:
- "4"
- "6"
- stable
- 7.6
language: node_js
script:
- make lint
Expand Down
24 changes: 10 additions & 14 deletions 404/app.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,25 @@
var koa = require('koa');
const Koa = require('koa');

var app = module.exports = koa();

app.use(function *pageNotFound(next) {
yield next;

if (404 != this.status) return;
const app = module.exports = new Koa();

app.use(async function pageNotFound(ctx) {
// we need to explicitly set 404 here
// so that koa doesn't assign 200 on body=
this.status = 404;
ctx.status = 404;

switch (this.accepts('html', 'json')) {
switch (ctx.accepts('html', 'json')) {
case 'html':
this.type = 'html';
this.body = '<p>Page Not Found</p>';
ctx.type = 'html';
ctx.body = '<p>Page Not Found</p>';
break;
case 'json':
this.body = {
ctx.body = {
message: 'Page Not Found'
};
break;
default:
this.type = 'text';
this.body = 'Page Not Found';
ctx.type = 'text';
ctx.body = 'Page Not Found';
}
});

Expand Down
4 changes: 2 additions & 2 deletions 404/test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@

var app = require('./app');
var request = require('supertest').agent(app.listen());
const app = require('./app');
const request = require('supertest').agent(app.listen());

describe('404', function() {
describe('when GET /', function() {
Expand Down
23 changes: 12 additions & 11 deletions base-auth/app.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
var koa = require('koa');
var auth = require('koa-basic-auth');
var app = module.exports = koa();
const Koa = require('koa');
const auth = require('koa-basic-auth');

const app = module.exports = new Koa();

// custom 401 handling

app.use(function* (next) {
app.use(async function(ctx, next) {
try {
yield next;
await next();
} catch (err) {
if (401 == err.status) {
this.status = 401;
this.set('WWW-Authenticate', 'Basic');
this.body = 'cant haz that';
if (err.status === 401) {
ctx.status = 401;
ctx.set('WWW-Authenticate', 'Basic');
ctx.body = 'cant haz that';
} else {
throw err;
}
Expand All @@ -24,8 +25,8 @@ app.use(auth({ name: 'tj', pass: 'tobi' }));

// secret response

app.use(function* () {
this.body = 'secret';
app.use(async function(ctx) {
ctx.body = 'secret';
});

if (!module.parent) app.listen(3000);
57 changes: 29 additions & 28 deletions blog/app.js
Original file line number Diff line number Diff line change
@@ -1,71 +1,72 @@

/**
* Module dependencies.
*/
const render = require('./lib/render');
const logger = require('koa-logger');
const router = require('koa-router')();
const koaBody = require('koa-body');

var render = require('./lib/render');
var logger = require('koa-logger');
var route = require('koa-route');
var parse = require('co-body');
var koa = require('koa');
var app = module.exports = koa();
const Koa = require('koa');
const app = module.exports = new Koa();

// "database"

var posts = [];
const posts = [];

// middleware

app.use(logger());

// route middleware
app.use(render);

app.use(route.get('/', list));
app.use(route.get('/post/new', add));
app.use(route.get('/post/:id', show));
app.use(route.post('/post', create));
app.use(koaBody());

// route definitions

router.get('/', list)
.get('/post/new', add)
.get('/post/:id', show)
.post('/post', create);

app.use(router.routes());

/**
* Post listing.
*/

function *list() {
this.body = yield render('list', { posts: posts });
async function list(ctx) {
await ctx.render('list', { posts: posts });
}

/**
* Show creation form.
*/

function *add() {
this.body = yield render('new');
async function add(ctx) {
await ctx.render('new');
}

/**
* Show post :id.
*/

function *show(id) {
var post = posts[id];
if (!post) this.throw(404, 'invalid post id');
this.body = yield render('show', { post: post });
async function show(ctx) {
const id = ctx.params.id;
const post = posts[id];
if (!post) ctx.throw(404, 'invalid post id');
await ctx.render('show', { post: post });
}

/**
* Create a post.
*/

function *create() {
var post = yield parse(this);
var id = posts.push(post) - 1;
async function create(ctx) {
const post = ctx.request.body;
const id = posts.push(post) - 1;
post.created_at = new Date();
post.id = id;
this.redirect('/');
ctx.redirect('/');
}

// listen

if (!module.parent) app.listen(3000);

4 changes: 2 additions & 2 deletions blog/lib/render.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
* Module dependencies.
*/

var views = require('co-views');
var path = require('path');
const views = require('koa-views');
const path = require('path');

// setup views mapping .html
// to the swig template engine
Expand Down
9 changes: 6 additions & 3 deletions blog/test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
var app = require('./app');
var request = require('supertest').agent(app.listen());
const app = require('./app');
const request = require('supertest').agent(app.listen());
require('should');

describe('Blog', function() {
describe('GET /', function() {
Expand All @@ -8,12 +9,12 @@ describe('Blog', function() {
.get('/')
.expect(200, function(err, res) {
if (err) return done(err);

res.should.be.html;
res.text.should.include('<title>Posts</title>');
done();
});
});

it('should see 0 post', function(done) {
request
.get('/')
Expand All @@ -26,6 +27,7 @@ describe('Blog', function() {
});
});
});

describe('POST /post/new', function() {
it('should create post and redirect to /', function(done) {
request
Expand All @@ -39,6 +41,7 @@ describe('Blog', function() {
});
});
});

describe('GET /post/0', function() {
it('should see post', function(done) {
request
Expand Down
19 changes: 11 additions & 8 deletions body-parsing/app.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@

var koa = require('koa');
var parse = require('co-body');
const Koa = require('koa');
const koaBody = require('koa-body');

var app = module.exports = koa();
const app = module.exports = new Koa();

app.use(koaBody({
jsonLimit: '1kb'
}));

// POST .name to /uppercase
// co-body accepts application/json
// and application/x-www-form-urlencoded

app.use(function *(next) {
if ('POST' != this.method) return yield next;
var body = yield parse(this, { limit: '1kb' });
if (!body.name) this.throw(400, '.name required');
this.body = { name: body.name.toUpperCase() };
app.use(async function(ctx) {
const body = ctx.request.body;
if (!body.name) ctx.throw(400, '.name required');
ctx.body = { name: body.name.toUpperCase() };
});

if (!module.parent) app.listen(3000);
36 changes: 18 additions & 18 deletions compose/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,41 +12,41 @@
* ]))
*/

var compose = require('koa-compose');
var koa = require('koa');
var app = module.exports = koa();
const compose = require('koa-compose');
const Koa = require('koa');
const app = module.exports = new Koa();

// x-response-time

function *responseTime(next) {
var start = new Date();
yield next;
var ms = new Date() - start;
this.set('X-Response-Time', ms + 'ms');
async function responseTime(ctx, next) {
const start = new Date();
await next();
const ms = new Date() - start;
ctx.set('X-Response-Time', ms + 'ms');
}

// logger

function* logger(next) {
var start = new Date();
yield next;
var ms = new Date() - start;
async function logger(ctx, next) {
const start = new Date();
await next();
const ms = new Date() - start;
if ('test' != process.env.NODE_ENV) {
console.log('%s %s - %s', this.method, this.url, ms);
console.log('%s %s - %s', this.method, ctx.url, ms);
}
}

// response

function* respond(next) {
yield next;
if ('/' != this.url) return;
this.body = 'Hello World';
async function respond(ctx, next) {
await next();
if ('/' != ctx.url) return;
ctx.body = 'Hello World';
}

// composed middleware

var all = compose([
const all = compose([
responseTime,
logger,
respond
Expand Down
4 changes: 2 additions & 2 deletions compose/test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
var app = require('./app');
var request = require('supertest').agent(app.listen());
const app = require('./app');
const request = require('supertest').agent(app.listen());

describe('Compose', function() {
describe('when GET /', function() {
Expand Down
19 changes: 9 additions & 10 deletions conditional-middleware/app.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
var logger = require('koa-logger');
var koa = require('koa');
var app = koa();
const logger = require('koa-logger');
const Koa = require('koa');
const app = new Koa();

// passing any middleware to this middleware
// will make it conditional, and will not be used
// when an asset is requested, illustrating how
// middleware may "wrap" other middleware.

function ignoreAssets(mw) {
return function *(next) {
if (/(\.js|\.css|\.ico)$/.test(this.path)) {
yield next;
return async function(ctx, next) {
if (/(\.js|\.css|\.ico)$/.test(ctx.path)) {
await next();
} else {
// must .call() to explicitly set the receiver
// so that "this" remains the koa Context
yield mw.call(this, next);
await mw.call(this, ctx, next);
}
};
}
Expand All @@ -26,8 +25,8 @@ function ignoreAssets(mw) {

app.use(ignoreAssets(logger()));

app.use(function *() {
this.body = 'Hello World';
app.use(async function(ctx) {
ctx.body = 'Hello World';
});

app.listen(3000);
Loading

0 comments on commit 50bcadf

Please sign in to comment.