I’m unable to get this “Upsert” recipe to work. I keep getting an “instance already exists” error with the following implementation:
import { query as q } from 'faunadb'
import faunadbClient from '/components/api/faunadb/client'
export default async(req, res) => {
try {
await faunadbClient.query(
q.CreateFunction({
name: 'upsert',
body: q.Query(
q.Lambda(
['ref', 'data'],
q.If(
q.Exists(q.Var('ref')),
q.Update(q.Var('ref'), q.Var('data')),
q.Create(q.Var('ref'), q.Var('data'))
)
)
)
})
)
await faunadbClient.query(
q.Call(
q.Function('upsert'),
q.Ref(q.Collection(req.query.collection), req.query.id),
{
data: req.body
}
)
)
res.status(200).end()
} catch (e) {
res.status(500).json({ error: e.message })
}
}
However, if I run the same query on a Update
specific endpoint, the document values are updated fine without error, like so:
import { query as q } from 'faunadb'
import faunadbClient from '/components/api/faunadb/client'
export default async(req, res) => {
try {
await faunadbClient.query(
q.Update(
q.Ref(q.Collection(req.query.collection), req.query.id),
{
data: req.body,
}
)
)
res.status(200).end()
} catch (e) {
res.status(500).json({ error: e.message })
}
}
Any ideas on what is going wrong here?