👌

Express & Prisma【10Post Route】

2022/09/27に公開

Express & Prisma【10Post Route】

YouTube: https://youtu.be/GA8qhGjMK00

index.ts
import express from 'express'
import helmet from 'helmet'
import morgan from 'morgan'
import cors from 'cors'
import userRoute from './routes/user'
import postRoute from './routes/post'

const app = express()
const port = 4000

app.use(express.json())
app.use(express.urlencoded({extended: true}))
app.use(cors())
app.use(helmet())
app.use(morgan('common'))

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.use('/api/users', userRoute)
app.use('/api/posts', postRoute)

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})
post.ts
import { Router } from "express";
import { prisma } from '../utils/prismaClient'

const router = Router()

router.get('/', async (_req, res) => {
  try {
    const posts = await prisma.post.findMany({
      select: {
        id: true,
        title: true,
        content: true,
        published: true,
        createdAt: true,
        updatedAt: true,
        author: {
          select: {
            id: true,
            name: true,
          }
        }
      }
    })
    res.status(200).json(posts)
  } catch (error) {
    res.status(500).json({"error": error})
  }
})

router.get('/:id', async (req, res) => {
  const id = Number(req.params.id)
  try {
    const post = await prisma.post.findUnique({
      where: {
        id: id,
      },
      select: {
        id: true,
        title: true,
        content: true,
        published: true,
        createdAt: true,
        updatedAt: true,
        author: {
          select: {
            id: true,
            name: true,
          }
        }
      }
    })
  if (post === null) {
    res.status(404).json({"message": "Post do not exist"})
    return
  }
  res.status(200).json(post)
  } catch (error) {
    res.status(500).json({"error": error})
  }
})

router.post('/', async (req, res) => {
  const {author_id, title, content} = req.body

  try {
    const post = await prisma.post.create({
      data: {
        title: title,
        content: content,
        authorId: author_id
      },
      select: {
        id: true,
        title: true,
        content: true,
        published: true,
        createdAt: true,
        updatedAt: true,
        author: {
          select: {
            id: true,
            name: true,
          }
        }
      }
    })
    res.status(200).json(post)
  } catch (error) {
    res.status(500).json({"error": error})
  }
})

router.delete('/:id', async (req, res) => {
  const id = Number(req.params.id)
  try {
    await prisma.post.delete({
      where: {
        id: id,
      },
    })
    res.status(200).json({"message": "post deleted success"})
  } catch (error) {
    res.status(500).json({"error": error})
  }
})

router.put('/:id', async (req, res) => {
  const id = Number(req.params.id)
  const { title, content, published } = req.body
  try {
    const updatePost = await prisma.post.update({
      where: {
        id: id,
      },
      data: {
        title: title,
        content: content,
        published: published
      },
      select: {
        id: true,
        title: true,
        content: true,
        published: true,
        createdAt: true,
        updatedAt: true,
        author: {
          select: {
            id: true,
            name: true,
          }
        }
      }
    })
    res.status(200).json({"message": "post updated success", "post": updatePost})
  } catch (error) {
    res.status(500).json({"error": error})
  }
})

export default router

Discussion