feat: Use Db with TypeORM to save logs

This commit is contained in:
Lucàs
2024-10-16 00:51:11 +02:00
parent 4a04814901
commit c95c92e987
9 changed files with 1290 additions and 52 deletions
+17
View File
@@ -0,0 +1,17 @@
import "reflect-metadata";
import { DataSource } from "typeorm";
import { Log } from "./entity/Log";
export const AppDataSource = new DataSource({
type: "mariadb",
host: "localhost",
port: 3306,
username: "root",
password: "root",
database: "db",
synchronize: true,
logging: true,
entities: [Log],
subscribers: [],
migrations: [],
});
+29
View File
@@ -0,0 +1,29 @@
import { Column, Entity, PrimaryGeneratedColumn } from "typeorm";
@Entity()
export class Log {
@PrimaryGeneratedColumn()
id: number = 0;
@Column("timestamp")
timestamp: Date = new Date();
@Column("text")
url: string;
@Column("text")
method: "GET" | "POST" | "PUT" | "DELETE" = "GET";
@Column("blob")
body: string = "";
constructor(
url: string,
method: "GET" | "POST" | "PUT" | "DELETE",
body: string
) {
this.url = url;
this.method = method;
this.body = body;
}
}
+3 -1
View File
@@ -1,10 +1,12 @@
import dotenv from "dotenv";
import Server from "./Server";
import { DatasetCollection } from "./services/dataset";
import { AppDataSource } from "./AppDataSource";
dotenv.config();
DatasetCollection.loadAll()
AppDataSource.initialize()
.then(() => DatasetCollection.loadAll())
.then(() => console.log("All datasets are loaded"))
.then(() => new Server().start())
.catch(console.error);
+11 -1
View File
@@ -1,10 +1,20 @@
import { NextFunction, Request, Response } from "express";
import { Log } from "../entity/Log";
import { AppDataSource } from "../AppDataSource";
export default function logger(
export default async function logger(
req: Request,
res: Response,
next: NextFunction
) {
console.info(`[${req.method}] ${req.url}`);
// Put the log into the database
const log: Log = new Log(
req.url,
req.method as any,
JSON.stringify(req.body)
);
await AppDataSource.manager.save(log);
next();
}