-
Notifications
You must be signed in to change notification settings - Fork 12
/
server.js
70 lines (62 loc) · 2.28 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
/**
* This file provided by Facebook is for non-commercial testing and evaluation
* purposes only. Facebook reserves all rights not expressly granted.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import fs from 'fs';
import path from 'path';
import express from 'express';
import bodyParser from 'body-parser';
const app = express();
const COMMENTS_FILE = path.join(__dirname, 'comments.json');
app.set('port', (process.env.PORT || 4000));
app.use('/', express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.get('/api/comments', (req, res) =>
fs.readFile(COMMENTS_FILE, (err, data) => {
if (err) {
console.error(err);
process.exit(1);
}
res.setHeader('Cache-Control', 'no-cache');
res.json(JSON.parse(data));
})
);
app.post('/api/comments', (req, res) =>
fs.readFile(COMMENTS_FILE, (err, data) => {
if (err) {
console.error(err);
process.exit(1);
}
let comments = JSON.parse(data);
// NOTE: In a real implementation, we would likely rely on a database or
// some other approach (e.g. UUIDs) to ensure a globally unique id. We'll
// treat Date.now() as unique-enough for our purposes.
const newComment = {
id: Date.now(),
author: req.body.author,
text: req.body.text,
};
comments = comments.concat(newComment);
fs.writeFile(COMMENTS_FILE, JSON.stringify(comments, null, 4), err => {
if (err) {
console.error(err);
process.exit(1);
}
res.setHeader('Cache-Control', 'no-cache');
res.json(comments);
});
})
);
app.listen(app.get('port'), function() {
console.log(`Server started: http://localhost: ${app.get('port')}/`);
});