Skip to content

Instantly share code, notes, and snippets.

@TracyNgot
Created June 19, 2020 21:04
Show Gist options
  • Select an option

  • Save TracyNgot/291738b403cfa012fe7bf05614c22408 to your computer and use it in GitHub Desktop.

Select an option

Save TracyNgot/291738b403cfa012fe7bf05614c22408 to your computer and use it in GitHub Desktop.

Revisions

  1. TracyNgot created this gist Jun 19, 2020.
    23 changes: 23 additions & 0 deletions query-builder.test.ts
    Original 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);
    });
    });
    55 changes: 55 additions & 0 deletions query-builder.ts
    Original 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'))),
    );
    }
    }