Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
143 lines (128 loc) · 3.69 KB
/
Copy pathserver.js
File metadata and controls
143 lines (128 loc) · 3.69 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
const http = require('http');
const fs = require('fs');
const path = require('path');
const { URL } = require('url');
const { DB_FILE, initializeSqlite, syncTodosToSqlite } = require('./sqliteService');
const {
DATA_DIR,
DATA_FILE,
buildCsvContent,
ensureDataFile,
escapeCsvValue,
parseCsvLine,
readTodos,
writeTodos
} = require('./services/csvService');
const { handleTodosApi } = require('./routes/todos');
const { sendJson } = require('./utils/http');
const {
buildSummary,
parseImportContent
} = require('./services/todoService');
const {
generateUniqueId,
isValidDateTime,
isValidIsoDate,
normalizeImportedTodos,
normalizePayload,
validateTodo
} = require('./utils/validation');
const PORT = process.env.PORT || 3000;
const PUBLIC_FILES = {
'/': 'index.html',
'/index.html': 'index.html',
'/readme': 'readme-viewer.html',
'/readme.html': 'readme-viewer.html',
'/README.md': 'README.md',
'/docs': 'docs.html',
'/docs.html': 'docs.html',
'/study-guide': 'study-guide/index.html',
'/study-guide/': 'study-guide/index.html',
'/openapi.json': 'openapi.json',
'/styles.css': 'styles.css',
'/app.js': 'app.js'
};
function createAppServer() {
ensureDataFile();
initializeSqlite();
syncTodosToSqlite(readTodos());
return http.createServer(async (req, res) => {
const requestUrl = new URL(req.url, `http://${req.headers.host}`);
if (requestUrl.pathname.startsWith('/api/todos')) {
try {
await handleTodosApi(req, res, requestUrl);
} catch (error) {
sendJson(res, 500, { error: 'Internal server error', detail: error.message });
}
return;
}
if (PUBLIC_FILES[requestUrl.pathname]) {
serveStaticFile(res, PUBLIC_FILES[requestUrl.pathname]);
return;
}
if (requestUrl.pathname.startsWith('/study-guide/')) {
const relativePath = decodeURIComponent(requestUrl.pathname.slice(1));
serveStaticFile(res, relativePath);
return;
}
sendJson(res, 404, { error: 'Resource not found' });
});
}
function startServer(port = PORT) {
const server = createAppServer();
return new Promise((resolve) => {
server.listen(port, () => resolve(server));
});
}
function serveStaticFile(res, fileName) {
const filePath = path.join(__dirname, fileName);
const normalizedPath = path.normalize(filePath);
const workspacePath = path.normalize(__dirname + path.sep);
if (!normalizedPath.startsWith(workspacePath) && normalizedPath !== path.normalize(__dirname)) {
sendJson(res, 403, { error: 'Access denied' });
return;
}
const extension = path.extname(fileName);
const contentType = {
'.html': 'text/html; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.js': 'application/javascript; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.md': 'text/markdown; charset=utf-8'
}[extension] || 'text/plain; charset=utf-8';
fs.readFile(filePath, (error, data) => {
if (error) {
sendJson(res, 500, { error: 'The requested file could not be loaded' });
return;
}
res.writeHead(200, { 'Content-Type': contentType });
res.end(data);
});
}
if (require.main === module) {
startServer(PORT).then((server) => {
const address = server.address();
const activePort = typeof address === 'object' && address ? address.port : PORT;
console.log(`Todo app listening on http://localhost:${activePort}`);
});
}
module.exports = {
DATA_DIR,
DATA_FILE,
DB_FILE,
buildSummary,
createAppServer,
generateUniqueId,
isValidDateTime,
isValidIsoDate,
normalizeImportedTodos,
normalizePayload,
parseImportContent,
parseCsvLine,
buildCsvContent,
escapeCsvValue,
readTodos,
startServer,
validateTodo,
writeTodos
};