-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
96 lines (87 loc) · 2.3 KB
/
server.js
File metadata and controls
96 lines (87 loc) · 2.3 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
import http from 'node:http';
import fs from 'node:fs';
import path from 'node:path';
import mime from 'mime-types';
import hbs from 'handlebars';
import env from '#app/env';
import db from '#app/db';
import router from '#app/router';
import Response from '#app/response';
import FileHelper from '#helpers/file';
import '#app/preloads/index';
class Application {
constructor() {
this.booted = false;
this.server = http.createServer();
this.router = router;
this.db = db;
this.hbs = hbs;
}
async run() {
try {
await this.#connectDb(this.db.client);
this.#handle();
this.booted = true;
} catch (error) {
throw new Error(error);
}
}
/**
* This function will initialize the connection to Database
* @param {pg.Client} client
*/
async #connectDb(client) {
await client.connect().catch((error) => {
console.error(error);
throw new Error(error);
});
}
#handle() {
this.server.on('request', async (req, res) => {
const response = new Response(req, res);
await this.router.call(req, response);
});
this.server.listen(env.app.port, () =>
console.log(`[LOG]: Server is running on port "${env.app.port}"`)
);
}
/**
* Serve folder with static files
*
* @param {string} folder Path to static files
*/
serve(folder) {
const files = FileHelper.readDirRecursive(folder);
/**
* At the moment, this process is called only once.
* It would be nice to watch for directory changes and declare new routes again
*/
for (const file of files) {
router.define('GET', `/${file}`, (req, { res }) => {
const data = fs.readFileSync(file);
const contentType = mime.lookup(file);
res.writeHead(200, { 'Content-Type': contentType });
res.end(data);
});
}
}
/**
* Register handlebars partials
*
* @param {string} folder Path to `partials` folder
*/
partials(folder) {
const partials = FileHelper.readDirRecursive(folder);
/**
* Register partials from files
*/
for (const partial of partials) {
const fileName = path.basename(partial);
this.hbs.registerPartial(
path.parse(fileName).name,
fs.readFileSync(partial, 'utf8').toString()
);
}
}
}
export default Application;