-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
233 lines (194 loc) · 5.71 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
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
'use strict';
// require built-in dependencies
const path = require('path');
const util = require('util');
const fs = require('fs');
const readFile = util.promisify(fs.readFile);
const writeFile = util.promisify(fs.writeFile);
const readDir = util.promisify(fs.readdir);
// require express-related dependencies
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
// require local dependencies
const logger = require('./middleware/logger');
// declare local constants and helper functions
const PORT = process.env.PORT || 4600;
const DATA_DIR = 'data';
const TAG_RE = /#\w+/g;
const slugToPath = (slug) => {
const filename = `${slug}.md`;
return path.join(DATA_DIR, filename);
};
const removeExtension = (item) => {
const pos = item.lastIndexOf('.');
return item.slice(0, pos);
}
// initialize express app
const app = express();
// use middlewares
app.use(cors());
app.use(logger);
app.use(bodyParser.json());
// this commented line of code will statically serve the frontend
// it will not work until you:
// $ cd client
// $ yarn install
// $ yarn build
app.use('/', express.static(path.join(__dirname, 'client', 'build')));
// GET: '/api/page/:slug'
// success response: {status: 'ok', body: '<file contents>'}
// failure response: {status: 'error', message: 'Page does not exist.'}
app.get('/api/page/:slug', async (req, res) => {
const filename = slugToPath(req.params.slug);
try {
const body = await readFile(filename, 'utf-8');
res.json({
status: 'ok',
body
});
// return jsonOK(res, { body });
} catch (e) {
res.json({
status: 'error',
message: 'Page does not exist.'
});
}
});
// POST: '/api/page/:slug'
// body: {body: '<file text content>'}
// tries to write the body to the given file
// success response: {status: 'ok'}
// failure response: {status: 'error', message: 'Could not write page.'}
app.post('/api/page/:slug', async (req, res) => {
const filename = slugToPath(req.params.slug);
try {
console.log('**post all pages**');
const content = req.body;
await writeFile(filename, content.body);
res.json({status: 'ok'});
} catch (e) {
console.log('something went wrong');
res.json({
status: 'error',
message: 'Could not write page.'
});
}
});
// GET: '/api/pages/all'
// sends an array of all file names in the DATA_DIR
// file names do not have .md, just the name!
// success response: {status:'ok', pages: ['fileName', 'otherFileName']}
// failure response: no failure response
app.get('/api/pages/all', async (req, res) => {
try {
console.log('**get all pages**');
const pages = [];
const files = fs.readdirSync(DATA_DIR);
files.forEach(file => {
const sliced = removeExtension(file);
pages.push(sliced);
});
//send response
res.json({
status: 'ok',
pages: pages
});
} catch (e) {
console.log('something went wrong');
res.json({
status: 'error',
message: e
});
}
});
// GET: '/api/tags/all'
// sends an array of all tag names in all files, without duplicates!
// tags are any word in all documents with a # in front of it
// hint: use the TAG_RE regular expression to search the contents of each file
// success response: {status:'ok', tags: ['tagName', 'otherTagName']}
// failure response: no failure response
app.get('/api/tags/all', async (req, res) => {
try {
console.log('**get all tags**');
const tags = [];
const files = fs.readdirSync(DATA_DIR);
files.forEach(file => {
//read files one by one
const readFile = `${DATA_DIR}/${file}`;
const data = fs.readFileSync(readFile, 'utf8');
const matchTag = data.match(TAG_RE);
//if we found a match we add it to the tags array
//matchTag is also an array
if (matchTag){
matchTag.forEach(tag => {
//remove '#'
const tmp = tag.substring(1, tag.length);
tags.push(tmp);
});
}
});
//remove duplicates of our array
const uniq = [...new Set(tags)];
//send response
res.json({
status: 'ok',
tags: uniq
});
} catch (e) {
console.log('something went wrong');
res.json({
status: 'error',
message: e
});
}
});
// GET: '/api/tags/:tag'
// searches through the contents of each file looking for the :tag
// it will send an array of all file names that contain this tag (without .md!)
// success response: {status:'ok', tag: 'tagName', pages: ['tagName', 'otherTagName']}
// failure response: no failure response
app.get('/api/tags/:tag', async (req, res) => {
try{
console.log('**get search for tag in each file**');
const filesWithTags = [];
const files = fs.readdirSync(DATA_DIR);
files.forEach(file => {
//read files one by one
const readFile = `${DATA_DIR}/${file}`;
const data = fs.readFileSync(readFile, 'utf8');
//get :tag param
const matchTag = data.match(req.params.tag);
//file contains the tag
if (matchTag){
const sliced = removeExtension(file);
filesWithTags.push(sliced);
}
});
//send response
res.json({
status: 'ok',
pages: filesWithTags
});
}
catch(e){
console.log('something went wrong');
res.json({
status: 'error',
message: e
});
}
});
// this needs to be here for the frontend to create new wiki pages
// if the route is not one from above
// it assumes the user is creating a new page
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'client', 'build', 'index.html'));
});
app.listen(PORT, (err) => {
if (err) {
console.error(err);
return;
}
console.log(`Wiki app is serving at http://localhost:${PORT}`)
});