Spaces:
Runtime error
Runtime error
File size: 1,302 Bytes
c20600f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | const fs = require('fs')
const path = require('path')
const dirPath = path.join(process.cwd(), 'src/source')
const dbPath = path.join(dirPath, 'data.json')
const defaultData = {
total_requests: 0,
success: 0,
failed: 0,
endpoints: {}
}
const ensureDir = () => {
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true })
}
}
const load = () => {
ensureDir()
if (!fs.existsSync(dbPath)) {
fs.writeFileSync(dbPath, JSON.stringify(defaultData, null, 2))
return { ...defaultData }
}
try {
const raw = fs.readFileSync(dbPath, 'utf8')
return JSON.parse(raw)
} catch (error) {
return { ...defaultData }
}
}
const save = (data) => {
ensureDir()
try {
fs.writeFileSync(dbPath, JSON.stringify(data, null, 2))
} catch (error) {
return false
}
}
const addRequest = (endpoint) => {
const data = load()
data.total_requests += 1
data.endpoints[endpoint] = (data.endpoints[endpoint] || 0) + 1
save(data)
}
const addSuccess = () => {
const data = load()
data.success += 1
save(data)
}
const addFailed = () => {
const data = load()
data.failed += 1
save(data)
}
module.exports = { load, save, addRequest, addSuccess, addFailed } |