-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb_objects.js
68 lines (58 loc) · 1.52 KB
/
db_objects.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
const Sequelize = require('sequelize');
const sequelize = new Sequelize(process.env.DATABASE_URL, {
logging: false,
dialectOptions: {
ssl: {
require: true,
rejectUnauthorized: false,
},
},
});
const Shop = require('./models/Shop.js')(sequelize, Sequelize.DataTypes);
const Users = require('./models/Users.js')(sequelize, Sequelize.DataTypes);
const UsersShop = require('./models/UsersShop.js')(sequelize, Sequelize.DataTypes);
const Lottery = require('./models/Lottery.js')(sequelize, Sequelize.DataTypes);
UsersShop.belongsTo(Shop, {
foreignKey: 'itemId',
as: 'item',
});
Lottery.belongsTo(Users, {
foreignKey: 'userId',
as: 'user',
});
Reflect.defineProperty(Users.prototype, 'addItem', {
value: async function addItem(item) {
const userItem = await UsersShop.findOne({
where: {
userId: this.userId,
itemId: item.itemId,
},
});
if (userItem) {
userItem.amount += 1;
return userItem.save();
}
return UsersShop.create({
userId: this.userId,
itemId: item.itemId,
amount: 1,
});
},
});
Reflect.defineProperty(Users.prototype, 'getItems', {
value: function getItems() {
return UsersShop.findAll({
where: { userId: this.userId },
include: ['item'],
});
},
});
Reflect.defineProperty(Lottery.prototype, 'getUser', {
value: function getUser() {
return Lottery.findOne({
where: { userId: this.userId },
include: ['user'],
});
},
});
module.exports = { Users, Shop, UsersShop, Lottery };