curiousroamers/src/server/routes/api.ts

106 lines
2.6 KiB
TypeScript

import express, {RequestHandler} from 'express';
import sequelize from './../dbobject';
import Article, {articleI} from './../models/article';
import Tag from './../models/tag';
import {authorize} from './../auth';
/* eslint-disable */
const router = express.Router();
/* eslint-enable */
/* eslint-disable */
declare global {
namespace Express {
interface Request {
article: articleI;
}
}
}
/* eslint-enable */
router.delete('/signout', async (_req, res) => {
res.cookie('accessToken', '', {expires: new Date()});
res.sendStatus(204);
});
router.get('/articletable', authorize, async (_req, res) => {
const articles = await Article.findAll({
attributes: [
'id',
'title',
'createdAt',
],
});
res.send(articles);
});
router.get('/new', authorize, (_req, res) => {
res.render('admin/new', {article: Article.build(), tags: []});
});
router.get('/edit/:id', authorize, async (req, res) => {
const article = await Article.findByPk(req.params.id,
{rejectOnEmpty: true});
const tags = await Tag.findAll({
where: {articleId: article.id},
attributes: [
'name',
],
});
res.render('admin/edit', {article, tags});
});
router.post('/', authorize, async (req, _res, next) => {
req.article = Article.build();
next();
}, saveArticleAndRedirect('new'));
router.put('/:id', authorize, async (req, _res, next) => {
req.article = await Article.findByPk(req.params.id, {rejectOnEmpty: true});
next();
}, saveArticleAndRedirect('edit'));
router.delete('/:id', authorize, async (req, _res) => {
await Article.destroy({where: {id: req.params.id}, cascade: true});
});
/**
* @param {string} path Path of redirection
* @return {RequestHandler} middleware
*/
function saveArticleAndRedirect(path: string): RequestHandler {
return async (req, res) => {
let article: any = req.article;
article.title = req.body.title;
article.description = req.body.description;
article.markdown = req.body.markdown;
try {
await sequelize.transaction(async (t) => {
let tagCount = 0;
while (req.body.articletags[tagCount] != '') {
tagCount++;
}
Tag.destroy({where: {articleId: article.id},
transaction: t});
article = await article.save();
for (let i = 0; i < tagCount; i++) {
await article.createTag({
articleId: article.id,
main: (i == 0) ? true : false,
name: req.body.articletags[i],
});
}
});
res.redirect(`/blog/post/${article.slug}`);
} catch (e) {
console.log(e);
req.flash('error', 'The operation has failed, please try again');
res.render(`admin/${path}`, {article: article});
}
};
}
export default router;