refacto(db): TTL conf in mongo

This commit is contained in:
Julien Froidefond
2025-02-14 17:07:44 +01:00
parent 5d47b307bd
commit ca36f4ce6a
5 changed files with 203 additions and 27 deletions

View File

@@ -0,0 +1,46 @@
import mongoose from "mongoose";
const ttlConfigSchema = new mongoose.Schema(
{
userId: {
type: String,
required: true,
unique: true,
},
defaultTTL: {
type: Number,
default: 5,
},
homeTTL: {
type: Number,
default: 5,
},
librariesTTL: {
type: Number,
default: 1440,
},
seriesTTL: {
type: Number,
default: 5,
},
booksTTL: {
type: Number,
default: 5,
},
imagesTTL: {
type: Number,
default: 1440,
},
},
{
timestamps: true,
}
);
// Middleware pour mettre à jour le champ updatedAt avant la sauvegarde
ttlConfigSchema.pre("save", function (next) {
this.updatedAt = new Date();
next();
});
export const TTLConfig = mongoose.models.TTLConfig || mongoose.model("TTLConfig", ttlConfigSchema);

View File

@@ -1,6 +1,7 @@
import { cookies } from "next/headers";
import connectDB from "@/lib/mongodb";
import { KomgaConfig } from "@/lib/models/config.model";
import { TTLConfig } from "@/lib/models/ttl-config.model";
interface User {
id: string;
@@ -13,6 +14,15 @@ interface KomgaConfigData {
password: string;
}
interface TTLConfigData {
defaultTTL: number;
homeTTL: number;
librariesTTL: number;
seriesTTL: number;
booksTTL: number;
imagesTTL: number;
}
export class ConfigDBService {
private static async getCurrentUser(): Promise<User> {
const userCookie = cookies().get("stripUser");
@@ -59,4 +69,48 @@ export class ConfigDBService {
return config;
}
static async saveTTLConfig(data: TTLConfigData) {
const user = await this.getCurrentUser();
await connectDB();
const config = await TTLConfig.findOneAndUpdate(
{ userId: user.id },
{
userId: user.id,
...data,
},
{ upsert: true, new: true }
);
return config;
}
static async getTTLConfig() {
const user = await this.getCurrentUser();
await connectDB();
const config = await TTLConfig.findOne({ userId: user.id });
if (!config) {
// Retourner la configuration par défaut si aucune configuration n'existe
return {
defaultTTL: 5,
homeTTL: 5,
librariesTTL: 1440,
seriesTTL: 5,
booksTTL: 5,
imagesTTL: 1440,
};
}
return {
defaultTTL: config.defaultTTL,
homeTTL: config.homeTTL,
librariesTTL: config.librariesTTL,
seriesTTL: config.seriesTTL,
booksTTL: config.booksTTL,
imagesTTL: config.imagesTTL,
};
}
}