Last active
May 1, 2018 01:06
-
-
Save good-idea/e75beb2f938f9db03b6d9bc3ba2bbc9e to your computer and use it in GitHub Desktop.
AQL Queries with optional filters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import db from '../../database' | |
import type { PaginationArgs, PageType } from './types' | |
// Sample Usage: | |
// const tenJapaneseUsers = await getUsers({ first: 10, filter: [{ key: 'locale', value: 'jp' }]) | |
const getUsers = async ({ first = 50, filter, after = 0 }: PaginationArgs): Promise<PageType | null | Error> => { | |
const filterQuery = filter | |
? filter.reduce((acc, { key, operator }) => `${acc}FILTER u.${key} ${operator || '=='} @${key}`, '') | |
: '' | |
const query = ` | |
RETURN { | |
"edges": ( | |
FOR u IN users LIMIT @after, @first | |
${filterQuery} | |
RETURN { | |
"cursor": u._id, | |
"node": u | |
} | |
) | |
}` | |
const filterValues = filter ? filter.reduce((acc, { key, value }) => ({ ...acc, [key]: value }), {}) : {} | |
const values = { | |
after, | |
first, | |
...filterValues, | |
} | |
const q = await db.query(query, values) | |
const { edges } = head(q._result) | |
return { | |
pageInfo: { | |
hasNextPage: q.hasNext(), | |
hasPreviousPage: first !== 0, | |
}, | |
edges, | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// @flow | |
export type Operator = '==' | '!=' | '<' | '<=' | '>' | '>=' | 'IN' | 'NOT IN' | 'LIKE' | '=~' | '!~' | |
// == equality | |
// != inequality | |
// < less than | |
// <= less or equal | |
// > greater than | |
// >= greater or equal | |
// IN test if a value is contained in an array | |
// NOT IN test if a value is not contained in an array | |
// LIKE tests if a string value matches a pattern | |
// =~ tests if a string value matches a regular expression | |
// !~ tests if a string value does not match a regular expression | |
type Filter = { | |
key: string, | |
value: string, | |
operator?: Operator, | |
} | |
export type PaginationArgs = { | |
first: number, | |
after: number, | |
filter?: [Filter], | |
} | |
type Edge = { | |
cursor: string, | |
node: Object, | |
} | |
type PageInfo = { | |
hasNextPage: boolean, | |
hasPreviousPage: boolean, | |
} | |
export type PageType = { | |
pageInfo: PageInfo, | |
edges: [Edge], | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment