#Interacting with a REST API for Upsert Operations

17 messages · Page 1 of 1 (latest)

fathom streamBOT
#

Im pulling my hair tryna figure this out. How do you interact with the generated REST API?

Im trying to upsert a collection, But no specific examples:
export async function patchCartItems(userId, cartItems, onSuccess, onError) {
try {
const res = await fetch("/api/carts" + stringify({
where: {
user: {
equals: userId
}
}
}, { addQueryPrefix: true }),
{
method: "POST",
body: JSON.stringify(
{
user: userId,
items: cartItems
}
)
}
);

if (!res.ok) {
  const error = new Error("Failed to fetch card");
  error.info = await res.json();
  error.status = res.status;
  throw error;
}

const data = await res.json();
onSuccess && onSuccess(data);
return data;

} catch (error) {
console.log(error);
onError && onError(error);
return error;
}
}
How do you even do this?

sharp shoalBOT
#

Original message from @spring cedar - Moved from #general message

#
celest temple
#

Hey @spring cedar

Looks like your where query is malformed for the REST api

#

What does stringify do? Is that your own fn?

#

Give qs-esm a shot for properly creating where queries for REST

spring cedar
#

stringify is from the recommended qs-esm library

celest temple
#

Also, double check that your collection slug is indeed 'carts'

#

Aha, I see

#

Can you try including the credentials

#

In your request, credentials: 'include'

spring cedar
#

Yes, sorry for not being more specific. What im trying to do is to Upsert an item via the Rest. That is:
if Entry doesnt exists, create one, else update kind of thing.

I tried using PATCH, it would not update unless I have an existing record for Carts, if im trying to insert/update cart items.
and I cant call POST twice

celest temple
#

Yeah an update would be a PATCH but a create is a POST

#

You can check easily if the operation is a create or update based on react hooks, if the doc already has an id it should be an update, if no id then must be a create

#

But yeah, try adding this to the request:

credentials: "include",
headers: {
  "Content-Type": "application/json",
},
spring cedar
#

Thank you!
Yeah, im trying to figure out how to make it run as a single operation, perhaps field hooks might be able to do it. im not sure yet.

celest temple
#

If you consider using the Local API, then you can pass the req you get in hooks/endpoints to the operation to turn it into a transaction