💬

Express & Prisma【7CreateUser】

2022/09/24に公開

Express & Prisma【7CreateUser】

YouTube: https://youtu.be/-hm6vOn5NOw

prisma crud: https://www.prisma.io/docs/concepts/components/prisma-client/crud#create

user.ts
import { Router } from "express";
import { prisma } from '../utils/prismaClient'

const router = Router()

router.get('/', async (_req, res) => {
  try {
    const users = await prisma.user.findMany({
      select: {
        id: true,
        email: true,
        name: true,
      }}
    )
    res.status(200).json(users)
  } catch (error) {
    res.status(500).json({"error": error})
  }

})

router.get('/:id', async (req, res) => {
  const id = Number(req.params.id)
  try {
  const user = await prisma.user.findUnique({
    where: {
      id: id,
    },
    select: {
      id: true,
      email: true,
      name: true,
    }
  })
  if (user === null) {
    res.status(404).json({"message": "User do not exist"})
    return
  }
  res.status(200).json(user)
  } catch (error) {
    res.status(500).json({"error": error})
  }
})

router.post('/', async (req, res) => {
  const { email, name, password, confirm_password } = req.body

  if (password !== confirm_password ) {
    res.status(400).json({
      'message': "Password do not match confirm password."
    })
    return
  }

  try {
    const user = await prisma.user.create({
      data: {
        email: email,
        name: name,
        password: password
      },
    })
    res.status(200).json(user)
  } catch (error) {
    res.status(500).json({"error": error})
  }
})

export default router

Discussion