an experiment in putting together a wiki and an object-oriented mud.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
the-forest/server/server.js

59 lines
2.0 KiB

const express = require('express');
const showdown = require('showdown');
const { query } = require('./dbHelper.js');
const port = process.env.PORT || 3001; // Use the port provided by the host or default to 3000
const app = express();
app.use(express.json());
app.use(function (req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader('Access-Control-Allow-Methods', '*');
res.setHeader("Access-Control-Allow-Headers", "*");
next();
});
const converter = new showdown.Converter();
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
app.get('/pages', (req, res) => {
query('select id from pages', [])
.then((r) => r.rows)
.then((row) => row.map(([id]) => id))
.then((ids) => res.status(200).json(ids))
.catch((error) => res.status(500).json({"error": error}));
});
app.post('/page/new', (req, res) => {
query('insert into pages (title, description) values (?, ?) returning id',
["new page", "this page is new!"])
.then((r) => r.rows[0][0])
.then((row) => res.status(200).json({id: row}))
.catch((error) => res.status(500).json({"error": error}))
});
app.get('/page/:id', (req, res) => {
query('select * from pages where id=?', [req.params.id])
.then((r) => {
if (r.rows.length == 0) return res.status(404).json({"error": "page not found in db"});
return r.rows[0];
}).then((row) => res.status(200).json(row))
.catch((error) => res.status(500).json({"error": error}));
});
app.post('/page/:id', (req, res) => {
const html = converter.makeHtml(req.body.description);
query('replace into pages (id, title, description, html) values (?, ?, ?, ?)',
[req.params.id, req.body.title, req.body.description, html])
.then(() => res.status(200).json({}))
.catch((error) => res.status(500).json({"error": error}));
});
app.delete('/page/:id', (req, res) => {
query('delete from pages where id = ?', [req.params.id])
.then(() => res.status(200).json({id: req.params.id}))
.catch((error) => res.status(500).json({"error": error}))
})