-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
78 lines (74 loc) · 1.67 KB
/
app.js
File metadata and controls
78 lines (74 loc) · 1.67 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
const express = require('express')
const bp = require('body-parser')
const app = express()
const shop = require('./routes/shop')
const admin = require('./routes/admin')
const { get404 } = require('./controllers/error')
const sequelize = require('./util/sequelize')
const Product = require('./models/product')
const User = require('./models/user')
const Cart = require('./models/cart')
const CartItem = require('./models/cart-item')
app.set('views', 'views')
app.set('view engine', 'ejs')
// midllewares
app.use(bp.urlencoded({ extended: true }))
app.use(express.static('public'))
app.use((req, res, next) => {
User.findByPk(1)
.then((user) => {
req.user = user
next()
})
.catch((err) => {
console.log(err)
})
})
app.use('/', shop)
app.use('/admin', admin)
app.use(get404)
// Aliasing Sequelize associations
Product.belongsTo(User, {
constraints: true,
onDelete: 'CASCADE',
})
User.hasMany(Product)
Cart.belongsTo(User)
User.hasOne(Cart)
Cart.belongsToMany(Product, { through: CartItem })
Product.belongsToMany(Cart, { through: CartItem })
// Sequelize syncing to build database as needed
sequelize
// .sync({ force: true })
.sync()
.then(() => {
return User.findByPk(1)
})
.then((user) => {
if (!user) {
return User.create({
name: 'Hushnudbek',
email: 'tobymarshal2802@gmail.com',
})
}
return user
})
.then((user) => {
user
.getCart()
.then((cart) => {
if (!cart) {
return user.createCart()
}
return
})
.catch((err) => {
console.log(err)
})
})
.then(() => {
app.listen(3003)
})
.catch((err) => {
console.log(err)
})