52 lines
1.6 KiB
JavaScript
52 lines
1.6 KiB
JavaScript
const express = require("express");
|
|
const router = express.Router();
|
|
const pool = require("../../db");
|
|
const { strictInput } = require("../../middleware/strict_input");
|
|
const { authenticateToken } = require("../../middleware/authenticate_token");
|
|
const {
|
|
handlePostUpload,
|
|
imageLinkForFile,
|
|
removeUploadedFile,
|
|
} = require("../../middleware/post_upload");
|
|
|
|
async function create_post(req, res) {
|
|
try {
|
|
const { title, text } = req.body;
|
|
const author_id = req.user.id;
|
|
if (!title || !text) {
|
|
await removeUploadedFile(req.file);
|
|
return res.status(400).send("Title or text was not provided");
|
|
} else {
|
|
const imageLink = imageLinkForFile(req.file);
|
|
try {
|
|
const { rows } = await pool.query(
|
|
"WITH created AS (INSERT INTO posts (title, text, author_id, image_link) VALUES ($1, $2, $3, $4) RETURNING id, title, text, author_id, image_link, created_at) SELECT created.*, people.username AS author_username FROM created LEFT JOIN people ON people.id = created.author_id",
|
|
[title, text, author_id, imageLink],
|
|
);
|
|
res.status(201).json(rows[0]);
|
|
} catch (err) {
|
|
await removeUploadedFile(req.file);
|
|
throw err;
|
|
}
|
|
}
|
|
} catch (err) {
|
|
console.error("database query failed", {
|
|
message: err.message,
|
|
code: err.code,
|
|
detail: err.detail,
|
|
hint: err.hint,
|
|
stack: err.stack,
|
|
});
|
|
res.status(500).send("Data was not pushed, request failed");
|
|
}
|
|
}
|
|
|
|
router.post(
|
|
"/",
|
|
authenticateToken,
|
|
handlePostUpload,
|
|
strictInput({ body: ["title", "text"], cleanupUploadedFile: true }),
|
|
create_post,
|
|
);
|
|
module.exports = router;
|