// src/routes/posts/index.ts
import { Router } from 'express'
import Post from '../../models/post'
import {
CreatePostSchema,
ListPostsQuerySchema,
UpdatePostSchema
} from './schemas'
const router = Router()
router.get('/', async (request, response) => {
const { page, perPage } = ListPostsQuerySchema.parse(request.query)
const { data, ...pagination } = await Post.where('published', true)
.orderBy('createdAt', 'desc')
.paginate(page, perPage)
response.json({ posts: data, pagination })
})
router.get('/:id', async (request, response) => {
const post = await Post.find(request.params.id)
if (!post) {
return response.status(404).json({ error: 'Post not found' })
}
response.json({ post })
})
router.post('/', async (request, response) => {
const input = CreatePostSchema.parse(request.body)
const post = await Post.create({
title: input.title,
body: input.body,
authorId: input.authorId,
published: input.published
})
response.status(201).json({ post })
})
router.patch('/:id', async (request, response) => {
const post = await Post.find(request.params.id)
if (!post) {
return response.status(404).json({ error: 'Post not found' })
}
const input = UpdatePostSchema.parse(request.body)
if (input.title !== undefined) post.title = input.title
if (input.body !== undefined) post.body = input.body
if (input.published !== undefined) post.published = input.published
await post.save()
response.json({ post })
})
router.delete('/:id', async (request, response) => {
const post = await Post.find(request.params.id)
if (!post) {
return response.status(404).json({ error: 'Post not found' })
}
await post.delete()
response.status(204).end()
})
export default router