Skip to content

Instantly share code, notes, and snippets.

@mindpivot
Last active February 14, 2017 23:27
Show Gist options
  • Save mindpivot/20fe18707041b4a4f9ffd739d3c330b2 to your computer and use it in GitHub Desktop.
Save mindpivot/20fe18707041b4a4f9ffd739d3c330b2 to your computer and use it in GitHub Desktop.
router function not firing
import { getServerPageRoutes } from './utility/makeServerRoutes';
import {routes} from './../shared/routes/index';
const Koa = require('koa');
const app = new Koa();
const Router = require('koa-router');
//let cleanRoutes = getServerPageRoutes(routes);
let cleanRoutes = [
{ method: 'GET',
route: '/',
roles: [ 'admin', 'user' ],
handlers: [ [Function: renderer] ]
},
{ method: 'GET',
route: '/inventory',
roles: [ 'admin', 'user' ],
handlers: [ [Function: renderer] ]
},
{ method: 'get',
route: '/inventory/adjustments',
roles: [ 'admin', 'user' ],
handlers: [ [Function: renderer] ]
}
]
for (let route of cleanRoutes) {
const router = new Router();
const lastHandler = route.handlers.pop();
const handlers = route.handlers;
const path = route.route;
const method = route.method.toLowerCase();
// THIS DAMN FUNCTION SHOULD GET CALLED... YET DOESN'T SEEM TO
// The middleware being passed in is valid middleware (see renderer file)
router[method](path, ...handlers, async function(ctx) {
return await lastHandler(ctx);
});
app.use(router.routes());
app.use(router.allowedMethods());
}
// THIS WORKS
const otherRouter = new Router();
otherRouter.get('/test', renderer());
app.use(otherRouter.routes());
app.use(otherRouter.allowedMethods());
// /end THIS WORKS
app.listen(3000, () => console.log('server started on port 3000'));
// for reference, renderer middleware
// this renderer middlware works when called explicitly like in app.use(renderer());
import React from 'react';
import { renderToString } from 'react-dom/server';
import { StaticRouter } from 'react-router';
import App from '../shared/app';
//module.exports = renderer;
function renderer(config) {
return async function renderer(ctx, next) {
await next();
const context = {};
let markup = renderToString(
<StaticRouter location={ctx.request.url} context={context}>
<App/>
</StaticRouter>
);
if (context.url) {
// handle a redirect, obviously ;)
ctx.response.set("Location", context.url);
ctx.response.status = 302;
console.log("ctx: ", ctx);
console.log("response: ", ctx.response);
//ctx.response.status('back', context.url);
} else {
if (false) {
// send a 404 and according to RR docs, re-render markup?
// 404
//ctx.response.status = 404;
// re-render markup
markup = renderToString(
<StaticRouter context={context} location={ctx.request.url}>
<App/>
</StaticRouter>
);
}
let pageMarkup = `
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<div id="sitewrapper">
${markup}
</div>
</body>
</html>
`;
ctx.body = pageMarkup;
}
}
}
export default renderer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment