FaunaDB Query builder + test
import { Expr } from 'faunadb'; | |
import QueryBuilder from './query-builder'; | |
describe('QueryBuilder', () => { | |
it('builds FaunaDB query', () => { | |
const testCollection = new QueryBuilder<any>('test'); | |
expect(testCollection.create({ test: 'my-test' })).toBeInstanceOf(Expr); | |
expect( | |
testCollection.update('id', { test: 'my-test-updated' }), | |
).toBeInstanceOf(Expr); | |
expect(testCollection.delete('id')).toBeInstanceOf(Expr); | |
expect(testCollection.get('id')).toBeInstanceOf(Expr); | |
expect(QueryBuilder.select('test')).toBeInstanceOf(Expr); | |
expect( | |
QueryBuilder.selectWhereUnion({ | |
index: 'test', | |
where: 'where', | |
indexUnion: 'test2', | |
whereUnion: 'where', | |
}), | |
).toBeInstanceOf(Expr); | |
}); | |
}); |
import faunadb from 'faunadb'; | |
import Expr from 'faunadb/src/types/Expr'; | |
const q = faunadb.query; | |
export default class QueryBuilder<T> { | |
private name: string; | |
constructor(name: string) { | |
this.name = name; | |
} | |
buildReference(collection: string, index: string) { | |
return q.Ref(q.Collection(collection), index); | |
} | |
create(data: T): Expr { | |
return q.Create(q.Collection(this.name), { data }); | |
} | |
update(index: any, data: T) { | |
return q.Update(q.Ref(q.Collection(this.name), index), { data }); | |
} | |
delete(index: string): Expr { | |
return q.Delete(this.buildReference(this.name, index)); | |
} | |
get(index: string): Expr { | |
return q.Get(this.buildReference(this.name, index)); | |
} | |
static select(index: string, { after, size }: any = {}): Expr { | |
return q.Map( | |
q.Paginate(q.Match(q.Index(index)), { size: size || 30, after }), | |
q.Lambda('X', q.Get(q.Var('X'))), | |
); | |
} | |
static selectWhereUnion( | |
{ index, where, indexUnion, whereUnion }, | |
{ after, size }: any = {}, | |
): Expr { | |
return q.Map( | |
q.Paginate( | |
q.Union( | |
q.Match(q.Index(index), where), | |
q.Match(q.Index(indexUnion), whereUnion), | |
), | |
{ size: size || 100, after }, | |
), | |
q.Lambda('X', q.Get(q.Var('X'))), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment