how to upsert
Answered
Wirehaired Vizsla posted this in #help-forum
Wirehaired VizslaOP
this is on my client side
this is on my api route
it said method not allowed
const response = await fetch(`/api/items/${itemId}`, {
method: "POST",
body: JSON.stringify(data),
headers: {
"Content-Type": "application/json",
},
})this is on my api route
export async function UPSERT(
request: Request,
{ params }: { params: { id: string } }
) {
const paramId = params.id
console.log("id", paramId)
var result = ""
try {
const { items } = await request.json()
console.log("body", items)
const upsertedItems = await Promise.all(
items &&
items.map(async (item) => {
const upserted = await prisma.itemDetails.upsert({
where: {
id: item.id,
},
update: {
name: item.name,
price: item.price,
unit: item.unit,
itemId: paramId,
},
create: {
name: item.name,
price: item.price,
unit: item.unit,
itemId: paramId,
},
})
return upserted
})
)
console.log(upsertedItems)
result = "success"
} catch (error) {
console.error("Error in UPSERT API:", error)
result = "error"
}
return NextResponse.json(result)
}it said method not allowed
Answered by B33fb0n3
@Wirehaired Vizsla You need to set one of this names as function names if you are using the app dir: POST, DELETE, PUT, GET.
In your case you want to upsert. For that you should use PUT to make it useful. You can read about why you want to use PUT here: https://stackoverflow.com/questions/18470588/in-rest-is-post-or-put-best-suited-for-upsert-operation
In your case you want to upsert. For that you should use PUT to make it useful. You can read about why you want to use PUT here: https://stackoverflow.com/questions/18470588/in-rest-is-post-or-put-best-suited-for-upsert-operation
5 Replies
@Wirehaired Vizsla You need to set one of this names as function names if you are using the app dir: POST, DELETE, PUT, GET.
In your case you want to upsert. For that you should use PUT to make it useful. You can read about why you want to use PUT here: https://stackoverflow.com/questions/18470588/in-rest-is-post-or-put-best-suited-for-upsert-operation
In your case you want to upsert. For that you should use PUT to make it useful. You can read about why you want to use PUT here: https://stackoverflow.com/questions/18470588/in-rest-is-post-or-put-best-suited-for-upsert-operation
Answer
@Wirehaired Vizsla solved?
Wirehaired VizslaOP
Yes it has been solved
Thank you very much
I will mark as solved when im home