-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
92 lines (80 loc) · 2.83 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
80
81
82
83
84
85
86
87
88
89
90
91
92
/**
* Copyright 2014, Yahoo! Inc.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
require('node-jsx').install({extension: '.jsx'});
var http = require('http');
var express = require('express');
var expressState = require('express-state');
var compression = require('compression');
var bodyParser = require('body-parser');
var debug = require('debug')('Example');
var React = require('react');
var ReactAsync = require('react-async');
var Application = require('./app/app');
var navigateAction = require('flux-router-component').navigateAction;
var Fetcher = require('fetchr');
var app = express();
expressState.extend(app);
app.set('state namespace', 'App');
app.set('views', __dirname + '/app'); // only for layout
app.set('view engine', 'jade');
// Enable GZip compression and serving static files
app.use(compression());
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
Fetcher.registerFetcher(require('./app/fetchers/post'));
app.use(Application.config.xhrPath, Fetcher.middleware());
app.use(function (req, res, next) {
var fetcher = new Fetcher({
req: req
});
var application = new Application({
fetcher: fetcher
});
application.context.getActionContext().executeAction(navigateAction, {
path: req.url
}, function (err) {
if (err) {
if (err.status && err.status === 404) {
next();
} else {
next(err);
}
return;
}
/**
* Send generated markup.
* @param error
* @param {String} html
* @param {Object} data component's state. Standard React-async
* approach is to inject the data as JSON into html markup. But
* we use Flux stores for holding the state, so instead we inject
* stores into markup.
*/
var sendMarkup = function (error, html, data) {
if (error) {
console.log(error);
}
debug('Exposing context state');
res.expose(application.context.dehydrate(), 'Context');
debug('Rendering application into layout');
res.render('layout', {
html: html
}, function (err, markup) {
if (err) {
next(err);
}
debug('Sending markup');
res.send(markup);
});
};
debug('Rendering Page component');
ReactAsync.renderComponentToStringWithAsyncState(application.getComponent(), sendMarkup);
// var markup = React.renderComponentToString(application.getComponent());
// sendMarkup(null, markup, {});
});
});
var port = process.env.PORT || 3000;
http.createServer(app).listen(port);
console.log('Listening on port ' + port);