node-backend-example/src/app.js

39 lines
1.1 KiB
JavaScript

import express from 'express'
import db from './db.js';
/*
* utility function to either get the value in the post data
* or send an error message to the response.
*/
function valOrMissing(data, key, res) {
if (!data[key]) {
res.status(403).json({"error": `missing "${key}"`})
return null;
}
return data[key];
}
// Creating an instance of Express
const app = express();
app.use(express.json()) // for parsing application/json
app.put("/note", async (req, res) => {
const title = valOrMissing(req.body, "title", res);
if (!title) return;
const text = valOrMissing(req.body, "text", res);
if (!text) return;
const created = req.body["created"] ? Date.parse(req.body["created"]) : new Date();
const id = await db("note").insert({
title, text, created
}, ["id"])
return res.status(202).send({ "note": id[0].id });
});
app.get("/note/:id", async (req, res, next) => {
const note = await db.from("note").where({ id: req.params.id });
return res.status(200).send({ "note": note[0] });
});
export default app;