Skip to content

Commit

Permalink
feat: basic error handling in api
Browse files Browse the repository at this point in the history
  • Loading branch information
Paulijuz committed Oct 13, 2023
1 parent c59977e commit 81f13e9
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
2 changes: 1 addition & 1 deletion src/app/api/users/[id]/route.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import prisma from "@/prisma"
export async function GET(request, { params }) {
const user = await prisma.user.findUnique({
where: {
id: params.id
id: Number(params.id)
}
})
return Response.json(user)
Expand Down
23 changes: 18 additions & 5 deletions src/app/api/users/route.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,39 @@
import { NextResponse } from "next/server"
import { Prisma } from '@prisma/client'

import prisma from "@/prisma"

export async function GET() {
const users = await prisma.user.findMany()

return NextResponse.json(users)
return Response.json(users)
}

export async function POST(req) {
const body = await req.json()

const { email } = body;
const { email, firstname, lastname } = body;

if (!email) {
return NextResponse.json({}, { status: 400 })
return Response.json({}, { status: 400 })
}

try {
const user = await prisma.user.create({
data: {
email: email
email: email,
firstname: firstname,
lastname: lastname
}
})

return Response.json(user)
} catch (error) {
// synes dette er en veldig stygg måte å håndtere feil på
if (
error instanceof Prisma.PrismaClientKnownRequestError &&
error.code === 'P2002'
) {
return Response.json({}, { status: 409 })
}
}
}

0 comments on commit 81f13e9

Please sign in to comment.