website/api/routes/blog.js

88 lines
2.3 KiB
JavaScript
Raw Normal View History

2023-06-11 20:19:35 +03:00
const express = require("express")
const { makeID } = require("../util.js")
const blog = express.Router()
blog.path = "/blog"
blog.get("/sum", async (req, res) => {
const db = req.db.db("ngn13")
const col = db.collection("posts")
const results = await col.find({ priv: { $eq: false } }).toArray()
2023-06-11 20:19:35 +03:00
let posts = []
for (let i = 0; i < results.length; i++) {
2023-06-11 20:19:35 +03:00
posts.push({
title: results[i]["title"],
desc:
results[i]["content"]
.substring(0, 140) // a short desc
.replaceAll("#", "") // remove all the markdown stuff
.replaceAll("*", "")
.replaceAll("`", "")
.replaceAll("-", "") + "...", // add "..." to make it look like desc
info: `${results[i]["author"]} | ${results[i]["date"]}`
2023-06-11 20:19:35 +03:00
})
}
// reversing so we can get
// the latest posts on the top
res.json({ error: 0, posts: posts.reverse() })
})
blog.get("/get", async (req, res) => {
2023-06-11 20:19:35 +03:00
const id = req.query.id
const db = req.db.db("ngn13")
const col = db.collection("posts")
2023-06-11 20:19:35 +03:00
const results = await col.find().toArray()
for (let i = 0; i < results.length; i++) {
2023-06-11 20:19:35 +03:00
// id is basically the title of the post
// but ve remove the whitespace
// and make it lowerspace
// for example:
// Online Privacy Guide -> onlineprivacyguide
if (makeID(results[i]["title"]) === id) {
return res.json({
error: 0,
post: {
title: results[i]["title"],
// info is the subtitle, for example:
// ngn | 01/06/2023
info: `${results[i]["author"]} | ${results[i]["date"]}`,
content: results[i]["content"]
2023-06-11 20:19:35 +03:00
}
})
2023-06-11 20:19:35 +03:00
}
}
res.json({ error: 3 })
})
blog.post("/add", async (req, res) => {
2023-06-11 20:19:35 +03:00
const title = req.body.title
const author = req.body.author
const content = req.body.content
const priv = req.body.priv
if (
typeof title !== "string" ||
typeof author !== "string" ||
typeof content !== "string" ||
2023-07-10 21:30:46 +03:00
typeof priv !== "boolean"
)
2023-06-11 20:19:35 +03:00
return res.json({ error: 1 })
const db = req.db.db("ngn13")
const col = db.collection("posts")
2023-06-11 20:19:35 +03:00
await col.insertOne({
title: title,
author: author,
date: new Date().toLocaleDateString(),
content: content,
priv: priv
2023-06-11 20:19:35 +03:00
})
res.json({ error: 0 })
})
module.exports = blog