-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
66 lines (58 loc) · 1.63 KB
/
index.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
const express = require('express');
const cors = require('cors');
const path = require('path');
const fs = require('fs');
const chalk = require('chalk');
const { create, del, update, getAll, getByID } = require('./controller.js');
class Server {
constructor() {
this.port = 7777;
this.app = express();
this.api = express.Router();
}
crudController() {
fs.readdir(path.join(__dirname, 'db'), (err, files) => {
if (err) {
return errLog('Unable to scan directory: ' + err);
} else {
files.forEach((file) => {
const route = `/${file.replace(".json", "")}`;
const routeByID = `${route}/:id`;
const routeDelete = `${route}/delete/:id`;
this.api.get(route, getAll);
this.api.get(routeByID, getByID);
this.api.post(route, create);
this.api.put(routeByID, update);
this.app.post(routeDelete, del);
});
}
});
};
logger() {
const typeLog = {
err: chalk.red('[ERROR]'),
ok: chalk.blue('[SUCCESS]'),
notFound: chalk.yellow('[Not Found]')
};
global.logger = ({ type, route, ctx }) => {
console.log(`${typeLog[type]} ${route} `, ctx);
};
};
init() {
const corsOptions = {
origin: '*',
methods: '*'
}
this.app.use(express.json());
this.app.use(express.urlencoded({ extended: true }));
this.app.use(cors(corsOptions));
this.app.use('/', this.api);
this.logger()
this.crudController();
this.app.listen(this.port, () => {
console.log(`Server running on port:${this.port}`);
});
};
};
const server = new Server();
server.init();