-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
65 lines (49 loc) · 1.61 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
const express = require('express');
// middlewares and routing
const bodyParser = require('body-parser');
const cors = require('cors');
const contextMiddleware = require('./middlewares/context');
const errorMiddleware = require('./middlewares/error');
const routes = require('./routes');
// context
const fileStorage = require('./fileStorage');
const inmemoryStorage = require('./inmemoryStorage');
const initContext = () => {
const memoryStorage = inmemoryStorage();
return { fileStorage, memoryStorage: memoryStorage };
};
const initInMemoryStorage = async context => {
const todos = await context.fileStorage.readTodoFile();
const users = await context.fileStorage.readUserFile();
context.memoryStorage.setTodos(todos);
context.memoryStorage.setUsers(users);
};
const initApp = context => {
const app = express();
app.use(cors());
app.use(bodyParser.json());
// const todos = express.Router();
// todos.use(contextMiddleware(context));
app.use(contextMiddleware(context));
routes.forEach(route => {
const method = route.method ? route.method.toLowerCase() : 'get';
const handlers = route.preHandlers ? route.preHandlers.concat(route.handler) : route.handler
return app[method](route.path, handlers);
});
// app.use('/todos', todos);
app.use(errorMiddleware);
return app;
};
const start = async port => {
const context = initContext();
await initInMemoryStorage(context);
const app = initApp(context);
app.listen(port, err => {
if (err) {
console.log(err);
return process.exit(1);
}
console.log(`Fut a szerver a ${port} porton.`);
});
};
start(8000);