the-forest/server/routes/pages.js

81 lines
2.6 KiB
JavaScript

const express = require('express');
const app = express.Router();
const sqlite = require('better-sqlite3');
const db = new sqlite('the_big_db.db', { verbose: console.log });
const { loginRequired } = require('../authStuff.js');
const showdown = require('showdown');
const converter = new showdown.Converter();
app.get('/pages', (req, res) => {
try {
const pages = db.prepare('select number, title from pages').all();
res.status(200).json(pages);
} catch (error) {
res.status(500).json({"error": error});
}
});
app.post('/page/new', loginRequired, (req, res) => {
try {
const maxPageNumber = db.prepare('select max(number) from pages').get()
console.log('maxPageNumber is ', maxPageNumber);
const newPage = db.prepare('insert into pages (title, description, author) values (?, ?, ?) returning number')
.get("new page", "this page is new!", req.session.userId);
res.status(200).json(newPage);
} catch (error) {
res.status(500).json({"error": error});
}
});
app.get('/page/:number', (req, res) => {
try {
const page = db.prepare('select * from pages where number=:number order by time desc').get(req.params);
if (page === undefined) res.status(404).json({"error": "page not found"});
else res.status(200).json(page);
} catch (error) {
res.status(500).json({"error": error});
}
});
app.post('/page/:number', loginRequired, (req, res) => {
try {
const html = converter.makeHtml(req.body.description);
const changes = db.prepare('insert into pages (number, title, description, html, author) values (?, ?, ?, ?, ?)')
.run(req.params.number, req.body.title, req.body.description, html, req.session.userId);
res.status(200).json(changes);
} catch (error) {
res.status(500).json({"error": error});
}
});
app.delete('/page/:id', loginRequired, (req, res) => {
try {
const changes = db.prepare('delete from pages where number = ?').run(req.params.id);
res.status(200).json({id: req.params.id});
} catch (error) {
res.status(500).json({"error": error});
}
});
app.get('/page/:number/history', (req, res) => {
try {
const all = db.prepare('select number, id, time, author from pages where number=:number order by time desc').all(req.params);
res.status(200).json(all);
} catch (error) {
res.status(500).json({"error": error});
}
});
app.get('/page/:number/:id', (req, res) => {
try {
const page = db.prepare('select * from pages where number=:number and id=:id').get(req.params);
if (page === undefined) res.status(404).json({"error": "page not found"});
else res.status(200).json(page);
} catch (error) {
res.status(500).json({"error": error});
}
});
module.exports = app;