all files / firebase/modules/database/ Query.js

90.91% Statements 20/22
75% Branches 9/12
100% Functions 7/7
94.74% Lines 18/19
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109                                      1334× 1334×                   18×             18×                   12×             12×                                                   2082×                 1775× 40× 40×         1775× 1775× 92× 92×   1775×   1775×      
/**
 * @flow
 * Query representation wrapper
 */
import { objectToUniqueId } from '../../utils';
 
import type { DatabaseModifier } from '../../types';
import type Reference from './Reference';
 
// todo doc methods
 
/**
 * @class Query
 */
export default class Query {
  _reference: Reference;
  modifiers: Array<DatabaseModifier>;
 
  constructor(ref: Reference, existingModifiers?: Array<DatabaseModifier>) {
    this.modifiers = existingModifiers ? [...existingModifiers] : [];
    this._reference = ref;
  }
 
  /**
   *
   * @param name
   * @param key
   * @return {Reference|*}
   */
  orderBy(name: string, key?: string) {
    this.modifiers.push({
      id: `orderBy-${name}:${key || ''}`,
      type: 'orderBy',
      name,
      key,
    });
 
    return this._reference;
  }
 
  /**
   *
   * @param name
   * @param limit
   * @return {Reference|*}
   */
  limit(name: string, limit: number) {
    this.modifiers.push({
      id: `limit-${name}:${limit}`,
      type: 'limit',
      name,
      limit,
    });
 
    return this._reference;
  }
 
  /**
   *
   * @param name
   * @param value
   * @param key
   * @return {Reference|*}
   */
  filter(name: string, value: any, key?: string) {
    this.modifiers.push({
      id: `filter-${name}:${objectToUniqueId(value)}:${key || ''}`,
      type: 'filter',
      name,
      value,
      valueType: typeof value,
      key,
    });
 
    return this._reference;
  }
 
  /**
   *
   * @return {[*]}
   */
  getModifiers(): Array<DatabaseModifier> {
    return [...this.modifiers];
  }
 
  /**
   *
   * @return {*}
   */
  queryIdentifier() {
    // sort modifiers to enforce ordering
    const sortedModifiers = this.getModifiers().sort((a, b) => {
      Iif (a.id < b.id) return -1;
      Eif (a.id > b.id) return 1;
      return 0;
    });
 
    // Convert modifiers to unique key
    let key = '{';
    for (let i = 0; i < sortedModifiers.length; i++) {
      if (i !== 0) key += ',';
      key += sortedModifiers[i].id;
    }
    key += '}';
 
    return key;
  }
}