-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathindex.js
99 lines (82 loc) · 2.63 KB
/
index.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
93
94
95
96
97
98
99
const path = require("path");
const invariant = require("invariant");
const ReactDOMServer = require("react-dom/server");
const React = require("react");
function loadModule(moduleId) {
// Clear the require cache, in case the file was
// changed since the server was started.
const cacheKey = require.resolve(moduleId);
delete require.cache[cacheKey];
const moduleExports = require(moduleId);
// Return exports.default if using ES modules.
if (moduleExports && moduleExports.default) {
return moduleExports.default;
}
return moduleExports;
}
function renderToStaticMarkup(element, callback) {
callback(null, ReactDOMServer.renderToStaticMarkup(element));
}
function renderToString(element, callback) {
callback(null, ReactDOMServer.renderToString(element));
}
function handleRequest(workingDir, request, callback) {
const componentPath = request.component;
const renderMethod = request.render;
const props = request.props;
invariant(componentPath != null, "Missing { component } in request");
let render;
if (renderMethod == null || renderMethod === "renderToString") {
render = renderToString;
} else if (renderMethod === "renderToStaticMarkup") {
render = renderToStaticMarkup;
} else {
const methodFile = path.resolve(workingDir, renderMethod);
try {
render = loadModule(methodFile);
} catch (error) {
if (error.code !== "MODULE_NOT_FOUND") {
process.stderr.write(error.stack + "\n");
}
}
}
invariant(
typeof render === "function",
"Cannot load render method: %s",
renderMethod
);
const componentFile = path.resolve(workingDir, componentPath);
let component;
try {
component = loadModule(componentFile);
} catch (error) {
if (error.code !== "MODULE_NOT_FOUND") {
process.stderr.write(error.stack + "\n");
}
}
invariant(component != null, "Cannot load component: %s", componentPath);
render(React.createElement(component, props), function(err, html) {
callback(err, html, component.context);
});
}
function createRequestHandler(workingDir) {
return function(request, callback) {
try {
handleRequest(workingDir, request, function(error, html, context) {
if (error) {
callback(error);
} else if (typeof html !== "string") {
// Crash the server process.
callback(new Error("Render method must return a string"));
} else {
callback(null, JSON.stringify({ html: html, context: context }));
}
});
} catch (error) {
callback(null, JSON.stringify({ error: error.message }));
}
};
}
module.exports = {
createRequestHandler
};