-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.js
147 lines (141 loc) · 2.65 KB
/
db.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
const { Sequelize, DataTypes, Op } = require("sequelize");
const cron = require("node-cron");
const { logger } = require("./log");
const sequelize = new Sequelize(
"database",
process.env.DB_USER,
process.env.DB_PASS,
{
host: "0.0.0.0",
dialect: "sqlite",
dialectOptions: {
supportBigNumbers: true,
bigNumberStrings: true,
},
pool: {
max: 5,
min: 0,
idle: 10000,
},
storage: ".data/database.sqlite",
logging: (msg) => logger.debug(msg),
}
);
const Auth = sequelize.define("Auth", {
snowflake: {
type: DataTypes.STRING,
allowNull: false,
primaryKey: true,
},
token: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
},
handle: {
type: DataTypes.STRING,
allowNull: false,
unique: "handleDiscriminator",
},
discriminator: {
type: DataTypes.INTEGER(8),
allowNull: false,
unique: "handleDiscriminator",
},
lastSeenAt: {
type: DataTypes.DATE,
allowNull: false,
defaultValue: DataTypes.NOW,
},
});
const Match = sequelize.define("Match", {
snowflake: {
type: DataTypes.STRING,
allowNull: false,
primaryKey: true,
},
guesserId: {
type: DataTypes.STRING,
references: {
model: Auth,
key: "snowflake",
},
allowNull: false,
},
enemyId: {
type: DataTypes.STRING,
references: {
model: Auth,
key: "snowflake",
},
allowNull: false,
},
isLive: {
type: DataTypes.BOOLEAN,
allowNull: false,
},
winnerId: {
type: DataTypes.STRING,
},
board: {
type: DataTypes.JSON,
allowNull: false,
},
metadata: {
type: DataTypes.JSON,
allowNull: false,
},
});
const dbSetup = async function () {
try {
await sequelize.authenticate();
} catch (e) {
logger.error("Cannot connect to db.", e);
}
await dbClean();
cron.schedule("0 * * * *", async () => {
await dbClean();
});
};
const dbClean = async function () {
const dateThreshold = new Date(
Date.now() - process.env.DB_CLEAN_TTL_DAYS * 24 * 60 * 60 * 1000
);
await Match.destroy({
where: {
isLive: true,
createdAt: {
[Op.lt]: dateThreshold,
},
},
});
await sequelize.query(
`
Delete FROM
Auths
WHERE
Auths.snowflake IN (
Select
Auths.snowflake
FROM
Auths
LEFT JOIN Matches ON Auths.snowflake = Matches.guesserId
OR Auths.snowflake = Matches.enemyId
WHERE
Matches.snowflake IS NULL
AND Auths.lastSeenAt < :dateThreshold
);
`,
{
replacements: {
dateThreshold,
},
}
);
};
module.exports = {
sequelize,
dbSetup,
Auth,
Match,
};