Files
forum-backend/routes/create.js
T

58 lines
2.6 KiB
JavaScript

const db = require('../surreal');
const router = require('express').Router();
router.post('/', async (req, res) => {
try{
const username = req.user;
const {title, content, category} = req.body;
if(title.length > process.env.MAXTITLELENGTH) return res.status(400).json({error: "Title is too long"});
if(content.length > process.env.MAXCONTENTLENGTH) return res.status(400).json({error: "Content is too long"});
if(!title || !content) return res.status(400).json({error: "Missing title or content"});
if(title.length < process.env.MINTITLELENGTH) return res.status(400).json({error: "Title is too short"});
if(content.length < process.env.MINCONTENTLENGTH) return res.status(400).json({error: "Content is too short"});
if(!username) return res.status(400).json({error: "Missing username"});
if(!category) return res.status(400).json({error: "Missing category"});
const currentDate = new Date();
const formattedDateAndTime = currentDate.toLocaleTimeString('en-gb', { timeStyle: 'short' });
const formattedDate = currentDate.toLocaleDateString('en-gb');
const date = formattedDateAndTime + " " + formattedDate;
const newPost = await db.create('posts', {category: category, title: title, content: content, author: username, date: date});
postId = (newPost[0].id).slice(6);
const update = await db.query(`UPDATE users SET posts += "${postId}" WHERE username = string::lowercase("${username}")`)
res.status(200).json({message: "Post created"});
}
catch(err){
console.log(err);
res.status(500).json({error: "Internal server error"});
}
});
router.delete('/:id', async (req, res) => {
try{
const username = req.user;
const id = 'posts:' + req.params.id;
if(!username) return res.status(400).json({error: "Missing username"});
if(!id) return res.status(400).json({error: "Missing id"});
const post = await db.query(`SELECT * FROM posts WHERE id = "${id}"`);
if(post.length == 0) return res.status(400).json({error: "Post does not exist"});
if(post[0].author != username) return res.status(400).json({error: "You are not the author of this post"});
const deletePost = await db.query(`DELETE FROM posts WHERE id = "${id}"`);
const update = await db.query(`UPDATE users SET posts -= "${id}" WHERE username = string::lowercase("${username}")`)
res.status(200).json({message: "Post deleted"});
}
catch(err){
console.log(err);
res.status(500).json({error: "Internal server error"});
}
});
module.exports = router;