Tech4biz-channel/Channel-Backend/src/controllers/blog.controller.ts

92 lines
2.6 KiB
TypeScript

import { Response, NextFunction } from 'express';
import { BlogService } from '../services/blog.service';
import { AuthRequest } from '../middleware/auth.middleware';
import prisma from '../utils/db';
export class BlogController {
private blogService = new BlogService();
public listBlogPosts = async (req: AuthRequest, res: Response, next: NextFunction) => {
try {
const { status, tag, search, author } = req.query;
const filters: any = {};
if (typeof tag === 'string') filters.tag = tag;
if (typeof search === 'string') filters.search = search;
if (typeof author === 'string') filters.author = author;
// Restrict status access if user is not admin
if (req.user?.role !== 'ADMIN') {
filters.status = 'published';
} else if (typeof status === 'string') {
filters.status = status;
}
const posts = await this.blogService.getBlogPosts(filters);
res.status(200).json(posts);
} catch (err) {
next(err);
}
};
public getBlogPost = async (req: AuthRequest, res: Response, next: NextFunction) => {
try {
const post = await this.blogService.getBlogPostById(req.params.id);
if (!post) {
return res.status(404).json({ error: 'Blog post not found' });
}
// Clients cannot view drafts
if (post.status !== 'published' && req.user?.role !== 'ADMIN') {
return res.status(403).json({ error: 'Access forbidden' });
}
res.status(200).json(post);
} catch (err) {
next(err);
}
};
public createBlogPost = async (req: AuthRequest, res: Response, next: NextFunction) => {
try {
let authorVal = req.body.author || 'Technical Architect';
if (!req.body.author && req.user?.userId) {
const user = await prisma.user.findUnique({
where: { id: req.user.userId }
});
if (user) {
authorVal = user.email;
}
}
const postData = {
...req.body,
author: authorVal,
};
const post = await this.blogService.createBlogPost(postData);
res.status(201).json(post);
} catch (err) {
next(err);
}
};
public updateBlogPost = async (req: AuthRequest, res: Response, next: NextFunction) => {
try {
const post = await this.blogService.updateBlogPost(req.params.id, req.body);
res.status(200).json(post);
} catch (err) {
next(err);
}
};
public deleteBlogPost = async (req: AuthRequest, res: Response, next: NextFunction) => {
try {
await this.blogService.deleteBlogPost(req.params.id);
res.status(204).send();
} catch (err) {
next(err);
}
};
}