simov / grant

OAuth Proxy
MIT License
4.1k stars 257 forks source link

Koa 2 examples (with current Koa API) #89

Closed ryanlabouve closed 6 years ago

ryanlabouve commented 6 years ago

Thank you for all the great examples! I had to make some modification to get with "koa": "^2.5.0".

I would be happy to add something like this as an additional example if it would be helpful:

(I also left comments on what I had to change)

const Koa = require('koa');

const session = require('koa-session');
const Router = require('koa-router'); // New style of router
const mount = require('koa-mount');
const accesslog = require('koa-accesslog');

const Grant = require('grant-koa');
const grant = new Grant(require('./config.json'));

const app = new Koa(); // Must use new keyword
const router = new Router(); // New version of the router

require('koa-qs')(app); // This must happen via require instead of middleware

app.use(accesslog());

// REQUIRED:
app.keys = ['grant'];
app.use(session(app));
// mount grant
app.use(mount(grant));

// Updated to use `ctx` instead of `this`
router.get('/handle_github_callback', async (ctx, next) => {
  console.log(ctx.query);
  ctx.body = JSON.stringify(ctx.query, null, 2);
});

// For the new router
app.use(router.routes()).use(router.allowedMethods());

app.listen(5001, () => {
  console.log('Koa server listening on port ' + 5001);
});
simov commented 6 years ago

I was thinking about Koa2 example at some point. Feel free to add one, I'll do my final touch on top of it. Personally I'm not a huge fan of excessive comments, because it will be much easier to spot the differences between the Koa1 and Koa2 examples if you open up the files in split view or just diff them. Also the examples follow the same style rules as the rest of the code base, you can validate your example using npm run lint.

ryanlabouve commented 6 years ago

Totally! I just added the comments for the sake of sharing the snippet here. I will cleanup and PR tonight. :)

simov commented 6 years ago

I've published the example here.

Thanks for the feedback :+1: