🦁

【Next.js】基礎から始めるNext.js API Routes【8Refactoring2】

2022/12/17に公開約2,500字

【8Refactoring2】

YouTube: https://youtu.be/Z6Kp7LzdqpA

https://youtu.be/Z6Kp7LzdqpA

今回も引き続きリファクタリングを進めていきます。

lib/prisma/users.ts
import { prisma } from '../../utils/prismaClient'
import { User } from '@prisma/client'

export const prismaGetUsers = async () => {
  const users = await prisma.user.findMany({
    select: {
      id: true,
      name: true,
      email: true,
    },
  })
  return users
}

export const prismaCreateUser = async (
  body: Omit<User, 'id' | 'createdAt' | 'updatedAt'>
) => {
  const createdUser = await prisma.user.create({
    data: {
      email: body.email,
      name: body.name,
      password: body.password,
    },
    select: {
      id: true,
      name: true,
      email: true,
    },
  })
  return createdUser
}

export const prismaGetUserById = async (id: string | string[] | undefined) => {
  const user = await prisma.user.findUnique({
    where: {
      id: Number(id),
    },
    select: {
      id: true,
      name: true,
      email: true,
      posts: true,
    },
  })
  return user
}

export const prismaDeleteUser = async (id: string | string[] | undefined) => {
  const deletedUser = await prisma.user.delete({
    where: {
      id: Number(id),
    },
    select: {
      id: true,
    },
  })
  return deletedUser
}

export const prismaUpdateUser = async (
  id: string | string[] | undefined,
  body: Pick<User, 'email' | 'name'>
) => {
  const updateUser = await prisma.user.update({
    where: {
      id: Number(id),
    },
    data: {
      email: body.email,
      name: body.name,
    },
    select: {
      id: true,
      name: true,
      email: true,
    },
  })
  return updateUser
}
pages/api/users/[id].ts
import type { NextApiRequest, NextApiResponse } from 'next'
import {
  prismaDeleteUser,
  prismaGetUserById,
  prismaUpdateUser,
} from '../../../lib/prisma/user'

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const { method, body, query } = req

  switch (method) {
    case 'GET':
      const user = await prismaGetUserById(query.id)
      res.status(200).json(user)
      break

    case 'DELETE':
      const deletedUser = await prismaDeleteUser(query.id)
      res.status(200).json({ message: `UserID ${deletedUser.id} was deleted` })
      break

    case 'PUT':
      const updateUser = await prismaUpdateUser(query.id, body)
      res.status(200).json(updateUser)
      break

    default:
      res.setHeader('Allow', ['GET', 'DELETE', 'PUT'])
      res.status(405).end(`${method} method not allowed`)
  }
}

Discussion

ログインするとコメントできます