Skip to content

Instantly share code, notes, and snippets.

@nelix
Last active February 11, 2016 21:46
Show Gist options
  • Save nelix/920378bccb3248aa7522 to your computer and use it in GitHub Desktop.
Save nelix/920378bccb3248aa7522 to your computer and use it in GitHub Desktop.
import Expedite from './';
const getTest = async (testContext) => ({true: true, test: 'Hello World', testContext}); // pretend async thing thats not really
const pretendCreatePromise = ({uuid, name}) => Promise.resolve({uuid, name});
export default class Test extends Expedite {
// req: express request object
// context: dependency injection (added at class initialise to avoid singletons)
async get(req, context) { // magically wrapped in try catch in the middleware, checks for this.error then defaults back to the next item in express
const res = await getTest(context); // database or whatever promise
return res; // json, + magic keys statusCode, redirect and contentType
}
async post(req, context) {
const {params} = req;
const model = pretendCreatePromise({uuid, name});
return model;
}
// TODO: content type neg
render({method, props, context}) { // if content type is html, response json goes through this before getting sent to the client
const {test} = props;
return `<div>${test} via ${method}</div>`;
}
}
import test from 'ava';
import request from 'supertest-as-promised';
import express from 'express';
import Expedite from './';
import Example from './example';
const makeApp = (ex) => {
const app = express();
ex.attach(app);
return app;
};
test('get:success', async (t) => {
const r = new Example({route: '/example'});
const response = await request(makeApp(r))
.get('/example');
t.is(response.status, 200);
});
test('post:success', async (t) => {
const r = new Example({route: '/example'});
const response = await request(makeApp(r))
.post('/example')
.send({uuid: 'lol', name: 'hey mate'});
t.is(response.status, 200);
t.is(response.body.uuid, 'lol');
t.is(response.body.name, 'hey mate');
});
import express from 'express';
import bodyParser from 'body-parser';
function reply(res, json, status = 200) {
res.json(json); // TODO: status
}
export default class Expedite {
static processMethod (controller, context) {
return async (req, res, next) => {
try {
const fn = controller[req.method.toLowerCase()];
if (fn) {
const {status, redirect, contentType, ...json} = await fn(req, context);
reply(res, json, status);
} else {
next();
}
} catch (err) {
next(err);
}
}
}
constructor({route, options, context}) {
this.router = express.Router(options);
this.router.use(bodyParser.json());
this.router.use(bodyParser.urlencoded({ extended: true }));
this.router.all(route, Expedite.processMethod(this, context));
this.error && this.router.use(this.error); // TODO: make general catchall express error handler
}
attach = (app) => {
app.use(this.router);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment