Created
June 19, 2020 21:04
-
-
Save TracyNgot/291738b403cfa012fe7bf05614c22408 to your computer and use it in GitHub Desktop.
Revisions
-
TracyNgot created this gist
Jun 19, 2020 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,23 @@ 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); }); }); This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,55 @@ 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'))), ); } }