115 lines
2.5 KiB
JavaScript
115 lines
2.5 KiB
JavaScript
import { BlogRepository } from '../../infrastructure/repositories/BlogRepository.js';
|
|
|
|
export class BlogController {
|
|
constructor() {
|
|
this.blogRepository = new BlogRepository();
|
|
}
|
|
|
|
async getAll(req, res) {
|
|
try {
|
|
const blogs = await this.blogRepository.findAll();
|
|
res.json({
|
|
success: true,
|
|
data: blogs
|
|
});
|
|
} catch (error) {
|
|
res.status(500).json({
|
|
success: false,
|
|
error: error.message
|
|
});
|
|
}
|
|
}
|
|
|
|
async getById(req, res) {
|
|
try {
|
|
const blog = await this.blogRepository.findById(req.params.id);
|
|
if (!blog) {
|
|
return res.status(404).json({
|
|
success: false,
|
|
error: 'Blog not found'
|
|
});
|
|
}
|
|
res.json({
|
|
success: true,
|
|
data: blog
|
|
});
|
|
} catch (error) {
|
|
res.status(500).json({
|
|
success: false,
|
|
error: error.message
|
|
});
|
|
}
|
|
}
|
|
|
|
async create(req, res) {
|
|
try {
|
|
const { title, content, published } = req.body;
|
|
|
|
if (!title || !content) {
|
|
return res.status(400).json({
|
|
success: false,
|
|
error: 'Title and content are required'
|
|
});
|
|
}
|
|
|
|
const blog = await this.blogRepository.create({
|
|
title,
|
|
content,
|
|
published: published || false,
|
|
authorId: req.user.id
|
|
});
|
|
|
|
res.status(201).json({
|
|
success: true,
|
|
data: blog,
|
|
message: 'Blog created successfully'
|
|
});
|
|
} catch (error) {
|
|
res.status(500).json({
|
|
success: false,
|
|
error: error.message
|
|
});
|
|
}
|
|
}
|
|
|
|
async update(req, res) {
|
|
try {
|
|
const { title, content, published } = req.body;
|
|
|
|
const updateData = {};
|
|
if (title) updateData.title = title;
|
|
if (content) updateData.content = content;
|
|
if (typeof published !== 'undefined') updateData.published = published;
|
|
|
|
const blog = await this.blogRepository.update(req.params.id, updateData);
|
|
|
|
res.json({
|
|
success: true,
|
|
data: blog,
|
|
message: 'Blog updated successfully'
|
|
});
|
|
} catch (error) {
|
|
res.status(500).json({
|
|
success: false,
|
|
error: error.message
|
|
});
|
|
}
|
|
}
|
|
|
|
async delete(req, res) {
|
|
try {
|
|
await this.blogRepository.delete(req.params.id);
|
|
|
|
res.json({
|
|
success: true,
|
|
message: 'Blog deleted successfully'
|
|
});
|
|
} catch (error) {
|
|
res.status(500).json({
|
|
success: false,
|
|
error: error.message
|
|
});
|
|
}
|
|
}
|
|
}
|