Prisma does not have any JSON filter (See this issue). This repo is to showcase a way to filter the JSON data using mingo.
We create a minimal graphql server with graphql-yoga
, however it could be express or anything else. It has one query which returns json data.
fakeData generates 5 to 20 fake objects so we don't need a database to test out how it works.
It has a simple query people
which takes a schemaless raw JSON data. The data can be anything but since we are trying to filter, we assume it's an array (of objects).
Fetch all results
{
people
}
filterData is simply a function that takes the fake data and applies mongodb like cursor.
It has skip
and first
just like we need in a prisma/graphql filter.
Fetch result with some filter
{
people(first: 2, skip: 1)
}
This query skips the first element and then returns 2 results. In prisma, first
is like an alias for limit
.
Warning! Beyond this point, it gets really complex. Caution adviced. You probably don't need these.
Example
The query
filter takes a stringified json. Consider the following query you would do on mongodb,
{
id: {
$gte: 50000;
}
}
You need to turn this into an string and pass that,
JSON.stringify(JSON.stringify({ id: { $gte: 50000 } }));
// "{\"id\":{\"$gte\":50000}}"
So now the query becomes:
{
people(query: "{\"id\":{\"$gte\":50000}}")
}
You can probably implement all other type of filter based on the above logic.
Another Example
For example, filter all element which has name with letter a
, with Regex:
JSON.stringify(JSON.stringify({ name: { $regex: "a" } }))
// "{\"name\":{\"$regex\":\"a\"}}"
The query becomes:
{
people(query: "{\"name\":{\"$regex\":\"a\"}}")
}
To understand what kind of filter you can probably use, check the mingo repository.