-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
81 lines (63 loc) · 2.1 KB
/
app.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
const express = require('express');
const app = express();
const listeningPort = 7321;
// sequelize
const { db } = require('./src/db');
// routers:
const { libraryRouter } = require('./src/routes')
const { bookRouter } = require('./src/routes')
const { userRouter } = require('./src/routes')
// auth
const { logInRouter } = require('./src/routes')
//middwares
const { consoleLoggingMIDWW } = require('./src/middlewares');
// models
const { Library } = require('./src/models/');
const { Book } = require('./src/models')
const { User } = require('./src/models')
//middw
// the order is important, all the middw must be before any other middw that tries to send a response to the client.
app.use(consoleLoggingMIDWW)
app.use(express.json());
// CRUD routes
app.use('/library', libraryRouter);
app.use('/book', bookRouter);
app.use('/user', userRouter);
// get token api routes
app.use('/login', logInRouter);
// i'm a teapot
app.use('/coffe-break',(req, res) => {
res.status(418).json({error: 'The server refuses the attempt to brew coffee with a teapot.'}).end();
})
//initializateDB
async function initializateDB(){
try {
// initializate the db from 0
await db.sync();
await db.authenticate()
Library.hasMany(Book);
Book.belongsTo(Library)
// snycing the Library & Book tables
await Library.sync();
console.log('Library table synchronized');
await Book.sync();
console.log('Book table synchronized');
await User.sync();
// we define the admin user here
const existAdmin = await User.findOne({where: {
username: 'admin'
}})
if(!existAdmin){
let adminUser = await User.build({username: 'admin', name: null, email: 'myexampleofmygmail@gmail.com', password: 'admin'})
await adminUser.save()
}
console.log('User table synchronized');
} catch(err) {
console.log(err);
}
}
//listening
app.listen(listeningPort, async () => {
await initializateDB()
console.log(`Server started on port ${listeningPort}`);
})