-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.js
79 lines (57 loc) · 1.95 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
require('node-jsx').install({extension: '.jsx'});
require("babel/register");
var koa = require('koa'),
Router = require('koa-router'),
React = require('react'),
serve = require('koa-static'),
mount = require('koa-mount'),
thunkify = require('thunkify-wrap'),
stateHelper = require("./state/stateHelper"),
favicon = require('koa-favicon'),
navigateAction = require('fluxible-router').navigateAction;
//router instance
var apiRouter = new Router();
//create our app
var server = koa();
server.use(favicon(__dirname + '/images/favicon.ico'));
//mount our web api
//server.use(mount('/api', apiRouter.middleware()));
//mount our static middleware
server.use(mount('/dist', serve(__dirname + '/dist', {defer: true})));
//index component
var HtmlComponent = React.createFactory(require('./components/html.jsx'));
//create our react-fluxible application
var app = require("./app");
server.use(mount("/", function *( next ) {
//ignore api and static routes
if ( this.path.startsWith("/dist") || this.path.startsWith('/api') ) {
return yield next;
}
var _this = this;
// Per request/session
var context = app.createContext();
var actionContext = context.getActionContext();
var executeAction = thunkify(actionContext.executeAction);
console.log(_this.path);
// Execute navigation action
try {
yield executeAction(navigateAction, {url: _this.path});
} catch ( err ) {
if ( err.status === 404 ) {
this.throw(404);
}
this.throw(500, 'Error happened.');
}
var AppComponent = app.getComponent();
var html = React.renderToStaticMarkup(HtmlComponent({
title: "Primer",
state: stateHelper.shareState(app, context),
markup: React.renderToString(context.createElement()),
context:context.getComponentContext()
}));
//set the body
_this.body = html;
yield next;
}));
//start the server
server.listen(3000);