Skip to content

Commit

Permalink
Merge pull request #231 from Nainah23/feat/127-Allow_User_To_Get_Own_…
Browse files Browse the repository at this point in the history
…Blog_Posts

feat: get all blog posts with pagination
  • Loading branch information
incredible-phoenix246 authored Jul 24, 2024
2 parents e38eb55 + f2dd55d commit dc4e16b
Show file tree
Hide file tree
Showing 4 changed files with 146 additions and 43 deletions.
2 changes: 1 addition & 1 deletion contributors.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@


[Nainah23](https://github.com/Nainah23)
Erasmus Tayviah (StarmannRassy)

178 changes: 138 additions & 40 deletions src/controllers/BlogController.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,116 @@
import { Request, Response } from "express";
import { BlogService } from "../services";
import { Request, Response } from 'express';
import { BlogService } from '../services';

export class BlogController {
private blogService = new BlogService();

/**
* @swagger
* /api/v1/blogs:
* get:
* summary: Get a paginated list of blogs by user
* description: Retrieve a paginated list of blog posts created by the authenticated user
* tags: [Blog]
* parameters:
* - in: query
* name: page
* schema:
* type: integer
* default: 1
* description: Page number for pagination
* - in: query
* name: limit
* schema:
* type: integer
* default: 10
* description: Number of blog posts per page
* responses:
* 200:
* description: A paginated list of blog posts
* content:
* application/json:
* schema:
* type: object
* properties:
* status:
* type: string
* example: success
* status_code:
* type: integer
* example: 200
* data:
* type: array
* items:
* type: object
* properties:
* title:
* type: string
* example: My First Blog
* content:
* type: string
* example: This is the content of my first blog post.
* author:
* type: string
* example: John Doe
* published_date:
* type: string
* format: date-time
* example: 2023-07-21T19:58:00.000Z
* pagination:
* type: object
* properties:
* current_page:
* type: integer
* example: 1
* per_page:
* type: integer
* example: 10
* total_pages:
* type: integer
* example: 2
* total_items:
* type: integer
* example: 15
* 400:
* description: Invalid query parameters
* content:
* application/json:
* schema:
* type: object
* properties:
* status:
* type: string
* example: bad request
* message:
* type: string
* example: Invalid query params passed
* status_code:
* type: integer
* example: 400
* 500:
* description: Internal server error
* content:
* application/json:
* schema:
* type: object
* properties:
* status:
* type: string
* example: error
* message:
* type: string
* example: Internal server error
* status_code:
* type: integer
* example: 500
*/
async listBlogs(req: Request, res: Response): Promise<void> {
try {
const user = req.user;
const page = parseInt(req.query.page as string) || 1;
const limit = parseInt(req.query.limit as string) || 10;

if (page <= 0 || limit <= 0) {
if (!user || page <= 0 || limit <= 0) {
res.status(400).json({
status: "bad request",
message: "Invalid query params passed",
Expand All @@ -18,19 +119,17 @@ export class BlogController {
return;
}

const { blogs, totalItems } = await this.blogService.getPaginatedblogs(
page,
limit,
);
const { blogs, totalItems } =
await this.blogService.getPaginatedblogs(user.id, page, limit);

res.json({
status: "success",
status_code: 200,
data: blogs.map((blog) => ({
title: blog.title,
content: blog.content,
author: blog.author,
published_at: blog.published_at,
author: blog.author.name,
published_date: blog.published_at,
})),
pagination: {
current_page: page,
Expand All @@ -48,37 +147,6 @@ export class BlogController {
}
}

async deleteBlogPost(req: Request, res: Response): Promise<void> {
try {
const { id } = req.params;
if (!id) {
res.status(401).json({
status_code: 401,
error: "Unauthorized",
});
}

const deletedPost = await this.blogService.deleteBlogPost(id);
if (!deletedPost) {
res.status(404).json({
status_code: 404,
error: "Blog post not found",
});
}

res.status(200).json({
status_code: 200,
message: "Blog post deleted successfully",
});
} catch (error) {
res.status(500).json({
status_code: 500,
error: "Internal server error",
details: error.message,
});
}
}

/**
* @swagger
* /api/v1/blog/{id}:
Expand Down Expand Up @@ -137,4 +205,34 @@ export class BlogController {
* type: string
* example: Error message
*/
async deleteBlogPost(req: Request, res: Response): Promise<void> {
try {
const { id } = req.params;
if (!id) {
res.status(401).json({
status_code: 401,
error: "Unauthorized",
});
}

const deletedPost = await this.blogService.deleteBlogPost(id);
if (!deletedPost) {
res.status(404).json({
status_code: 404,
error: "Blog post not found",
});
}

res.status(200).json({
status_code: 200,
message: "Blog post deleted successfully",
});
} catch (error) {
res.status(500).json({
status_code: 500,
error: "Internal server error",
details: error.message,
});
}
}
}
2 changes: 1 addition & 1 deletion src/routes/blog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const blogRouter = Router();
const blogController = new BlogController();

blogRouter.post("/create", authMiddleware, createBlogController);
blogRouter.get("/", blogController.listBlogs.bind(blogController));
blogRouter.get("/", authMiddleware, blogController.listBlogs.bind(blogController));

blogRouter.delete("/:id", blogController.deleteBlogPost.bind(blogController));

Expand Down
7 changes: 6 additions & 1 deletion src/services/blog.services.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,27 @@ export class BlogService {
}

async getPaginatedblogs(
userId: string,
page: number,
limit: number,
): Promise<{ blogs: Blog[]; totalItems: number }> {
const [blogs, totalItems] = await this.blogRepository.findAndCount({
where: { author: { id: userId } },
skip: (page - 1) * limit,
take: limit,
relations: ['author'],
});

return { blogs, totalItems };
}

async deleteBlogPost(id: string): Promise<boolean> {
try {
const result = await this.blogRepository.delete(id);
return result.affected !== 0;
} catch (error) {
throw new Error("Error deleting blog post");
console.error('Error deleting blog post:', error);
throw new Error('Error deleting blog post');
}
}
}

0 comments on commit dc4e16b

Please sign in to comment.