-
Notifications
You must be signed in to change notification settings - Fork 101
/
Copy pathmain.js
62 lines (53 loc) · 1.81 KB
/
main.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
'use strict';
const http = require('node:http');
const pg = require('pg');
const hash = require('./hash.js');
const receiveArgs = require('./body.js');
const PORT = 8000;
const pool = new pg.Pool({
host: '127.0.0.1',
port: 5432,
database: 'example',
user: 'marcus',
password: 'marcus',
});
const routing = {
user: {
async get(id) {
if (!id) return pool.query('SELECT id, login FROM users');
const sql = 'SELECT id, login FROM users WHERE id = $1';
return await pool.query(sql, [id]);
},
async post({ login, password }) {
const sql = 'INSERT INTO users (login, password) VALUES ($1, $2)';
const passwordHash = await hash(password);
return await pool.query(sql, [login, passwordHash]);
},
async put(id, { login, password }) {
const sql = 'UPDATE users SET login = $1, password = $2 WHERE id = $3';
const passwordHash = await hash(password);
return await pool.query(sql, [login, passwordHash, id]);
},
async delete(id) {
const sql = 'DELETE FROM users WHERE id = $1';
return await pool.query(sql, [id]);
},
},
};
http.createServer(async (req, res) => {
const { method, url, socket } = req;
const [name, id] = url.substring(1).split('/');
const entity = routing[name];
if (!entity) return void res.end('Not found');
const handler = entity[method.toLowerCase()];
if (!handler) return void res.end('Not found');
const src = handler.toString();
const signature = src.substring(0, src.indexOf(')'));
const args = [];
if (signature.includes('(id')) args.push(id);
if (signature.includes('{')) args.push(await receiveArgs(req));
console.log(`${socket.remoteAddress} ${method} ${url}`);
const result = await handler(...args);
res.end(JSON.stringify(result.rows));
}).listen(PORT);
console.log(`Listen on port ${PORT}`);