-
Notifications
You must be signed in to change notification settings - Fork 644
Expand file tree
/
Copy pathapi.server.js
More file actions
202 lines (180 loc) · 5.15 KB
/
api.server.js
File metadata and controls
202 lines (180 loc) · 5.15 KB
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
'use strict';
const register = require('react-server-dom-webpack/node-register');
register();
const babelRegister = require('@babel/register');
babelRegister({
ignore: [/[\\\/](build|server|node_modules)[\\\/]/],
presets: [['react-app', {runtime: 'automatic'}]],
plugins: ['@babel/transform-modules-commonjs'],
});
const express = require('express');
const compress = require('compression');
const {readFileSync} = require('fs');
const {unlink, writeFile} = require('fs').promises;
const {pipeToNodeWritable} = require('react-server-dom-webpack/writer');
const path = require('path');
const {Pool} = require('pg');
const React = require('react');
const ReactApp = require('../src/App.server').default;
// Don't keep credentials in the source tree in a real app!
const pool = new Pool(require('../credentials'));
const PORT = process.env.PORT || 4000;
const app = express();
app.use(compress());
app.use(express.json());
app
.listen(PORT, () => {
console.log(`React Notes listening at ${PORT}...`);
})
.on('error', function(error) {
if (error.syscall !== 'listen') {
throw error;
}
const isPipe = (portOrPipe) => Number.isNaN(portOrPipe);
const bind = isPipe(PORT) ? 'Pipe ' + PORT : 'Port ' + PORT;
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
});
function handleErrors(fn) {
return async function(req, res, next) {
try {
return await fn(req, res);
} catch (x) {
next(x);
}
};
}
app.get(
'/',
handleErrors(async function(_req, res) {
await waitForWebpack();
const html = readFileSync(
path.resolve(__dirname, '../build/index.html'),
'utf8'
);
// Note: this is sending an empty HTML shell, like a client-side-only app.
// However, the intended solution (which isn't built out yet) is to read
// from the Server endpoint and turn its response into an HTML stream.
res.send(html);
})
);
async function renderReactTree(res, props) {
await waitForWebpack();
const manifest = readFileSync(
path.resolve(__dirname, '../build/react-client-manifest.json'),
'utf8'
);
const moduleMap = JSON.parse(manifest);
pipeToNodeWritable(React.createElement(ReactApp, props), res, moduleMap);
}
function sendResponse(req, res, redirectToId) {
const location = JSON.parse(req.query.location);
if (redirectToId) {
location.selectedId = redirectToId;
}
res.set('X-Location', JSON.stringify(location));
renderReactTree(res, {
selectedId: location.selectedId,
isEditing: location.isEditing,
searchText: location.searchText,
});
}
app.get('/react', function(req, res) {
sendResponse(req, res, null);
});
const NOTES_PATH = path.resolve(__dirname, '../notes');
app.post(
'/notes',
handleErrors(async function(req, res) {
const now = new Date();
const result = await pool.query(
'insert into notes (title, body, created_at, updated_at) values ($1, $2, $3, $3) returning id',
[req.body.title, req.body.body, now]
);
const insertedId = result.rows[0].id;
await writeFile(
path.resolve(NOTES_PATH, `${insertedId}.md`),
req.body.body,
'utf8'
);
sendResponse(req, res, insertedId);
})
);
app.put(
'/notes/:id',
handleErrors(async function(req, res) {
const now = new Date();
const updatedId = Number(req.params.id);
await pool.query(
'update notes set title = $1, body = $2, updated_at = $3 where id = $4',
[req.body.title, req.body.body, now, updatedId]
);
await writeFile(
path.resolve(NOTES_PATH, `${updatedId}.md`),
req.body.body,
'utf8'
);
sendResponse(req, res, null);
})
);
app.delete(
'/notes/:id',
handleErrors(async function(req, res) {
await pool.query('delete from notes where id = $1', [req.params.id]);
await unlink(path.resolve(NOTES_PATH, `${req.params.id}.md`));
sendResponse(req, res, null);
})
);
app.get(
'/notes',
handleErrors(async function(_req, res) {
const {rows} = await pool.query('select * from notes order by id desc');
res.json(rows);
})
);
app.get(
'/notes/:id',
handleErrors(async function(req, res) {
const {rows} = await pool.query('select * from notes where id = $1', [
req.params.id,
]);
res.json(rows[0] || null);
})
);
app.get('/sleep/:ms', function(req, res) {
setTimeout(() => {
res.json({ok: true});
}, req.params.ms);
});
app.use(express.static('build'));
app.use(express.static('public'));
async function waitForWebpack() {
while (true) {
try {
readFileSync(path.resolve(__dirname, '../build/index.html'));
return;
} catch (err) {
console.log(
'Could not find webpack build output. Will retry in a second...'
);
await new Promise((resolve) => setTimeout(resolve, 1000));
}
}
}