-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
111 lines (88 loc) · 2.71 KB
/
main.js
File metadata and controls
111 lines (88 loc) · 2.71 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
'use strict';
const http = require ('node:http');
const port = 9999;
const statusNotFound = 404;
const statusBadRequest = 400;
const statusOk = 200;
let nextId = 1;
const posts = [];
function sendResponse(response, {status = statusOk, headers = {}, body = null}) {
Object.entries(headers).forEach(function([key, value]) {
response.setHeader(key, value);
});
response.writeHead(status);
response.end(body);
}
function SendJSON(response, body) {
sendResponse(response, {
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
});
}
const methods = new Map();
methods.set('/posts.get', function({response}){
SendJSON(response, posts);
//response.writeHead(statusOk, {'Content-Type': 'application/json'});
//response.end(JSON.stringify(posts));
});
methods.set('/posts.getById', function(){});
methods.set('/posts.post', function({response, searchParams}){
//const url = new URL(request.url, `http://${request.headers.host}`);
//const searchParams = url.searchParams;
if (!searchParams.has('content')) {
//response.writeHead(statusBadRequest);
//response.end();
sendResponse(response, {status: statusBadRequest});
return;
}
const content = searchParams.get('content');
const post = {
id:nextId++,
content: content,
create: Date.now(),
};
posts.unshift(post);
SendJSON(response, post);
//response.writeHead(statusOk, {'Content-Type': 'application/json'});
//response.end(JSON.stringify(post));
});
methods.set('/pos ts.edit', function(){});
methods.set('/posts.delete', function(){});
const server = http.createServer(function(request, response) {
//const url = new URL(request.url, `http://${request.headers.host}`);
//const searchParams = url.searchParams;
//response.end(searchParams.get('query'));
const {pathname, searchParams} = new URL(request.url, `http://${request.headers.host}`);
//const pathname = url.pathname;
//const searchParams = url.searchParams;
const method = methods.get(pathname);
if (method === undefined) {
//response.writeHead(statusNotFound);
//response.end();
sendResponse(response, {status: statusNotFound});
return;
}
const params = {
request,
response,
pathname,
searchParams,
}
//method(request, response);
method(params);
});
server.listen(port);
/*class Demo {
get property() {
console.log('get');
return 'property';
}
set property(value) {
console.log(`set${value}`);
}
}
const demo = new Demo();
const property = demo.property;
demo.property = 'new value';*/