const express = require('express') const sqlite3 = require('sqlite3') const app = express() const db = new sqlite3.Database(':memory:'); const getCurrentUnixTimestamp = () => Math.floor(Date.now() / 1000); db.serialize(() => { db.run(`CREATE TABLE cache ( id TEXT PRIMARY KEY, response TEXT, time TEXT )`); }); app.get('/', async (req, res) => { const url = req.query.url; if (!url) { res.status(400).send("nop"); return; } db.get(`SELECT * FROM cache WHERE id = ?`, [url], async (err, row) => { if (err) { console.error(err); res.status(500).send("damn"); return; } if (row) { const currentTime = getCurrentUnixTimestamp(); const twoHoursInSeconds = 10; if (currentTime - row.time > twoHoursInSeconds) { db.run(`DELETE FROM cache WHERE id = ?`, [url], async (err) => { if (err) { console.error(err); res.status(500).send("damn"); return; } const resp = await getinfosl(url) const insertStmt = db.prepare(`INSERT INTO cache (id, response, time) VALUES (?, ?, ?)`); const currentTime = getCurrentUnixTimestamp(); insertStmt.run(url, resp, currentTime, (err) => { if (err) { console.error(err); res.status(500).send("damn"); return; } res.contentType("application/json"); res.send(resp) console.log("old response (entry readded)"); }); insertStmt.finalize(); }); } else { console.log("cache valid") res.contentType("application/json"); res.send(row.response); } } else { const insertStmt = db.prepare(`INSERT INTO cache (id, response, time) VALUES (?, ?, ?)`); const currentTime = getCurrentUnixTimestamp(); const resp = await getinfosl(url) insertStmt.run(url, resp, currentTime, (err) => { if (err) { console.error(err); res.status(500).send("damn"); return; } res.contentType("application/json"); res.send(resp) console.log("New entry added"); }); insertStmt.finalize(); } }); }); async function getinfosl(url) { const response = await fetch(`https://api.song.link/v1-alpha.1/links?url=${url}`); const meow = await response.text(); return meow; } app.listen(3000, async () => { console.log("running") })