const express = require('express') const sqlite3 = require('sqlite3') const cors = require('cors') 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.use(cors()); app.get('/', async (req, res) => { const url = req.query.url; if (!url) { res.status(400).contentType("text/plain").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 = 7200; 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.header("cache", "stale - invalidated"); res.send(resp) console.log("old response (entry readded)"); }); insertStmt.finalize(); }); } else { res.header("cache", "fresh"); 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.header("cache", "wasnt"); 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") })