const express = require('express'); const showdown = require('showdown'); const db_url = 'http://localhost:8000' 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}`); }); // Define a route to handle incoming requests app.post('/', (req, res) => { res.send('Hello, Express!'); }); app.get('/pages', (req, res) => { fetch(db_url, { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ statements: ['select id from pages'] }) }).then((rsp) => rsp.json()) .then((data) => data[0].results.rows) .then((rows) => rows.map(([id]) => id)) .then((ids) => res.json(ids)) .catch((error) => res.status(404).json({"error": "error"})); }); app.get('/page/:id', (req, res) => { fetch(db_url, { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ statements: [{ q: 'select * from pages where id=?', params: [req.params.id] }] }) }).then((rsp) => rsp.json()) .then((data) => data[0].results.rows[0]) .then((row) => res.json(row)) .catch((error) => res.status(404).json({"error": error})); }); app.post('/page/new', (req, res) => { fetch(db_url, { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ statements: [{ q: 'insert into pages (title, description) values (?, ?) returning id', params: ["new page", "this page is new!"] }] }) }).then((rsp) => rsp.json()) .then((data) => data[0].results.rows[0][0]) .then((row) => res.status(200).json({id: row})) .catch((error) => res.status(404).json({"error": error})) }); app.post('/page/:id', (req, res) => { console.log(`got a post for /page/${req.params.id}`, req.body); console.log(`rendering new input ${req.params.id}`); const html = converter.makeHtml(req.body.description); console.log(`the output was ${html}`) console.log("done rendering"); fetch(db_url, { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ statements: [{ q: 'replace into pages (id, title, description, html) values (?, ?, ?, ?)', params: [Number(req.params.id), req.body.title, req.body.description, html], }] }) }).then(() => res.status(200).json({})) .catch((error) => res.status(404).json({"error": error})); });