68 lines
2.2 KiB
JavaScript
68 lines
2.2 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");
|
|
const driver = require("../../graph_db");
|
|
|
|
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],
|
|
);
|
|
const post = rows[0];
|
|
try {
|
|
await driver.executeQuery(
|
|
"CREATE (p:Post {db_id: $db_id, author_id: $author_id, created_at: datetime()})",
|
|
{ db_id: Number(post.id), author_id: Number(post.author_id) },
|
|
{ database: process.env.GRAPH_DB_NAME },
|
|
);
|
|
} catch (graphErr) {
|
|
await pool.query("DELETE FROM posts WHERE id = $1", [post.id]).catch(() => {});
|
|
throw graphErr;
|
|
}
|
|
res.status(201).json({
|
|
...post,
|
|
like_count: 0,
|
|
liked_by_me: false,
|
|
});
|
|
} 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;
|