Here is the relevant code…
const faunadb = require('faunadb')
const order = (a, b) => {
return a.data ? a.data.order - b.data.order : a.order - b.order
}
const DB = new faunadb.Client({
secret: process.env.FAUNA_KEY
})
const {
Ref,
Paginate,
Get,
Match,
Intersection,
Select,
Index,
Create,
Update,
Collection,
Join,
Call,
Lambda,
Var,
Map,
Union,
Function: Fn,
} = faunadb.query;
const merge = async (ands) => {
const { data } = await DB.query(Map(
Paginate(
Intersection(
ands.map(({ index, search }) => {
return Match(Index(index), search)
})
)
),
Lambda("X", Get(
Var("X")
))
))
return data
}
const all = async (index) => {
const { data } = await DB.query(Map(
Paginate(
Match(
Index(index)
)
),
Lambda("X", Get(
Var("X")
))
))
return data.sort(order)
}
const some = async (index, search) => {
const { data } = await DB.query(Map(
Paginate(
Match(
Index(index), search
)
),
Lambda("X", Get(
Var("X")
))
))
return data.sort(order)
}
const includes = async (index, searches) => {
const { data } = await DB.query(Map(
Paginate(
Union(
searches.map(search => {
return Match(
Index(index), search
)
})
)
),
Lambda("X", Get(
Var("X")
))
))
return data.sort(order)
}
const one = async (index, search) => {
const { data } = await DB.query(Map(
Paginate(
Union(
Match(
Index(index), search
)
)
),
Lambda("X", Get(
Var("X")
))
))
return data.length ? data[0] : data
}
const add = async (collection, obj) => {
const doc = await DB.query(Create(Collection(collection), { data: obj }))
return doc
}
const update = async (collection, ref, obj) => {
const doc = await DB.query(Update(Ref(Collection(collection), ref), { data: obj }))
return doc
}
module.exports = {
merge,
one,
all,
some,
includes,
add,
update,
order
}