caching layer implementation for improved performance

This commit is contained in:
2025-05-12 16:45:28 +02:00
parent 8022fceff4
commit e1c6a35325
3 changed files with 139 additions and 27 deletions

View File

@@ -2,6 +2,7 @@ import type { NextApiRequest, NextApiResponse } from 'next'
import sqlite3 from 'sqlite3'
import path from 'path'
import { rateLimit, getRateLimitHeaders } from '../../../lib/rate-limiter'
import { cache, getCacheKey } from '../../../lib/cache'
type CheckResponse = {
is_problematic: boolean
@@ -79,6 +80,14 @@ export default async function handler(
return res.status(400).json({ error: 'Invalid URL format' })
}
// Check cache first
const cacheKey = getCacheKey('domain_check', domain)
const cachedResult = cache.get<CheckResponse>(cacheKey)
if (cachedResult) {
return res.status(200).json(cachedResult)
}
const dbPath = path.join(process.cwd(), 'database', 'antihoax.db')
const db = new sqlite3.Database(dbPath)
@@ -99,42 +108,50 @@ export default async function handler(
)
})
let result: CheckResponse
if (sources.length === 0) {
return res.status(200).json({
result = {
is_problematic: false,
risk_level: 0,
categories: [],
message: 'Stránka nie je v našej databáze problematických zdrojov',
source_count: 0
})
}
const maxRiskLevel = Math.max(...sources.map(s => s.risk_level))
const allCategories = sources
.map(s => s.categories)
.filter(Boolean)
.join(',')
.split(',')
.filter(Boolean)
const uniqueCategories = Array.from(new Set(allCategories))
let message = ''
if (maxRiskLevel >= 4) {
message = 'VYSOKÉ RIZIKO: Táto stránka šíri nebezpečné obsahy'
} else if (maxRiskLevel >= 3) {
message = 'STREDNÉ RIZIKO: Táto stránka môže obsahovať problematické informácie'
}
} else {
message = 'NÍZKE RIZIKO: Táto stránka je označená ako problematická'
const maxRiskLevel = Math.max(...sources.map(s => s.risk_level))
const allCategories = sources
.map(s => s.categories)
.filter(Boolean)
.join(',')
.split(',')
.filter(Boolean)
const uniqueCategories = Array.from(new Set(allCategories))
let message = ''
if (maxRiskLevel >= 4) {
message = 'VYSOKÉ RIZIKO: Táto stránka šíri nebezpečné obsahy'
} else if (maxRiskLevel >= 3) {
message = 'STREDNÉ RIZIKO: Táto stránka môže obsahovať problematické informácie'
} else {
message = 'NÍZKE RIZIKO: Táto stránka je označená ako problematická'
}
result = {
is_problematic: true,
risk_level: maxRiskLevel,
categories: uniqueCategories,
message,
source_count: sources.length
}
}
return res.status(200).json({
is_problematic: true,
risk_level: maxRiskLevel,
categories: uniqueCategories,
message,
source_count: sources.length
})
// Cache the result (5 minutes for non-problematic, 15 minutes for problematic)
const cacheTtl = result.is_problematic ? 900 : 300
cache.set(cacheKey, result, cacheTtl)
return res.status(200).json(result)
} catch (error) {
console.error('Database error:', error)