mirror of
https://github.com/kmitresse/Compo-Service-Log-Project.git
synced 2026-07-09 12:07:45 +00:00
feat: Use Db with TypeORM to save logs
This commit is contained in:
@@ -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: [],
|
||||
});
|
||||
@@ -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
@@ -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);
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user