import express from 'express';
import Database from 'better-sqlite3';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
app.use(express.json());
// Open (or create) the SQLite database file
const db = new Database(path.join(__dirname, 'nexus.db'));
db.exec(`
CREATE TABLE IF NOT EXISTS links (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
url TEXT NOT NULL,
sort_order INTEGER DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
`);
app.use(express.static(__dirname));
app.get('/api/links', (req, res) => {
try {
const rows = db.prepare('SELECT * FROM links ORDER BY sort_order ASC, id ASC').all();
res.json(rows);
} catch (err) { res.status(500).json({ error: err.message }); }
});
app.post('/api/links', (req, res) => {
const { title, url } = req.body;
try {
const max = db.prepare('SELECT COALESCE(MAX(sort_order),-1) as m FROM links').get().m;
const r = db.prepare('INSERT INTO links (title, url, sort_order) VALUES (?,?,?)').run(title, url, max+1);
res.json({ id: r.lastInsertRowid, title, url });
} catch (err) { res.status(500).json({ error: err.message }); }
});
app.put('/api/links/:id', (req, res) => {
const { title, url } = req.body;
try {
db.prepare('UPDATE links SET title=?, url=? WHERE id=?').run(title, url, req.params.id);
res.json({ id: req.params.id, title, url });
} catch (err) { res.status(500).json({ error: err.message }); }
});
app.delete('/api/links/:id', (req, res) => {
try {
db.prepare('DELETE FROM links WHERE id=?').run(req.params.id);
res.sendStatus(200);
} catch (err) { res.status(500).json({ error: err.message }); }
});
app.put('/api/links/reorder', (req, res) => {
const { order } = req.body;
try {
const update = db.prepare('UPDATE links SET sort_order=? WHERE id=?');
db.transaction((items) => items.forEach((id, i) => update.run(i, id)))(order);
res.sendStatus(200);
} catch (err) { res.status(500).json({ error: err.message }); }
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Nexus running on http://localhost:${PORT}`));
-- SQLite schema (auto-created by server on first run)
-- File: nexus.db (created in the project folder)
CREATE TABLE IF NOT EXISTS links (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
url TEXT NOT NULL,
sort_order INTEGER DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
-- Demo data (optional, insert via the UI or run manually)
INSERT INTO links (title, url, sort_order) VALUES
('GitHub', 'https://github.com', 0),
('Figma', 'https://figma.com', 1),
('Vercel', 'https://vercel.com', 2),
('YouTube', 'https://youtube.com', 3);