fix: add admin
This commit is contained in:
30
server/utils/mongodb.ts
Normal file
30
server/utils/mongodb.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { MongoClient, type Db } from "mongodb";
|
||||
|
||||
let client: MongoClient | null = null;
|
||||
let db: Db | null = null;
|
||||
|
||||
export async function getDb(): Promise<Db> {
|
||||
if (db) return db;
|
||||
|
||||
const uri = useRuntimeConfig().db;
|
||||
if (!uri) throw new Error("NUXT_DB is not configured");
|
||||
|
||||
client = new MongoClient(uri);
|
||||
await client.connect();
|
||||
db = client.db("vat-api");
|
||||
|
||||
// Create indexes for the requests collection
|
||||
const requests = db.collection("requests");
|
||||
await requests.createIndex({ timestamp: -1 });
|
||||
await requests.createIndex({ ip: 1, timestamp: -1 });
|
||||
|
||||
return db;
|
||||
}
|
||||
|
||||
export async function closeDb(): Promise<void> {
|
||||
if (client) {
|
||||
await client.close();
|
||||
client = null;
|
||||
db = null;
|
||||
}
|
||||
}
|
||||
24
server/utils/redis.ts
Normal file
24
server/utils/redis.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import Redis from "ioredis";
|
||||
|
||||
let redis: Redis | null = null;
|
||||
|
||||
function getRedisUrl(): string {
|
||||
return useRuntimeConfig().redisUrl || "redis://localhost:6379";
|
||||
}
|
||||
|
||||
export function getRedis(): Redis {
|
||||
if (redis) return redis;
|
||||
redis = new Redis(getRedisUrl(), { maxRetriesPerRequest: null });
|
||||
return redis;
|
||||
}
|
||||
|
||||
export function createRedisClient(): Redis {
|
||||
return new Redis(getRedisUrl(), { maxRetriesPerRequest: null });
|
||||
}
|
||||
|
||||
export async function closeRedis(): Promise<void> {
|
||||
if (redis) {
|
||||
await redis.quit();
|
||||
redis = null;
|
||||
}
|
||||
}
|
||||
17
server/utils/requestLogger.ts
Normal file
17
server/utils/requestLogger.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
export interface RequestLogEntry {
|
||||
ip: string;
|
||||
path: string;
|
||||
method: string;
|
||||
statusCode: number;
|
||||
userAgent: string;
|
||||
timestamp: string;
|
||||
}
|
||||
|
||||
export function logRequest(data: RequestLogEntry): void {
|
||||
try {
|
||||
const redis = getRedis();
|
||||
redis.lpush("request-logs", JSON.stringify(data)).catch(() => {});
|
||||
} catch {
|
||||
// Never let logging break API responses
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user