Skip to content

Commit 7cf83cd

Browse files
committed
refactor: ♻️ refactor and auto sync db at start
1 parent b7ec41b commit 7cf83cd

File tree

3 files changed

+24
-35
lines changed

3 files changed

+24
-35
lines changed

src/app.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import express from "express";
22
import logger from "morgan";
3-
import dbInit from "./db/init";
3+
import {dbSync} from "./db/connection";
44
import cors from "cors";
55
import { customRequest } from "./types/customDefinition";
66
import { deserializeUser } from "./middleware";
@@ -38,7 +38,7 @@ app.get("/api/", (req: customRequest, res) => {
3838
*/
3939
app.patch("/api/sync", async (req, res) => {
4040
try {
41-
const sync = await dbInit();
41+
const sync = await dbSync();
4242
res.status(200).json({ ...sync, error: false });
4343
} catch (err) {
4444
console.log("ERR", err);

src/db/connection.ts

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import { Sequelize } from "sequelize";
2-
32
import { dbConfig } from "../config/config";
3+
import logger from "../util/logger";
4+
5+
const isDev = process.env.NODE_ENV === "development";
46

57
const sequelizeConnection = new Sequelize(
68
dbConfig.database,
@@ -10,7 +12,26 @@ const sequelizeConnection = new Sequelize(
1012
host: dbConfig.host,
1113
port: dbConfig.port,
1214
dialect: dbConfig.dialect,
15+
logging: msg => logger.debug(msg),
1316
}
1417
);
1518

19+
const dbSync = async () => {
20+
try {
21+
await sequelizeConnection.sync({ alter: isDev });
22+
return { success: true };
23+
} catch (error) {
24+
throw error;
25+
}
26+
};
27+
dbSync()
28+
.then(res => {
29+
logger.info(`DB sync with status: ${res.success}`);
30+
})
31+
.catch(err => {
32+
logger.error("Failed to sync DB", err);
33+
});
34+
35+
export { dbSync };
36+
1637
export default sequelizeConnection;

src/db/init.ts

Lines changed: 0 additions & 32 deletions
This file was deleted.

0 commit comments

Comments
 (0)