All files fluentSQL.js

100% Statements 96/96
100% Branches 29/29
100% Functions 12/12
100% Lines 96/96

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 969x 9x 9x 9x 9x 9x 8x 8x 8x 8x 1x 1x 9x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 5x 5x 5x 5x 5x 9x 2x 2x 2x 2x 9x 9x 14x 14x 14x 14x 14x 14x 9x 9x 19x 19x 13x 13x 9x 14x 14x 14x 14x 14x 14x 14x 14x 42x 42x 9x 7x 7x 5x 7x 2x 2x 2x 4x 4x 9x 7x 19x 19x 19x 19x 19x 14x 14x 14x 7x 7x 7x 7x 7x 9x 1x 1x 1x 1x 1x
export class FluentSQLBuilder {
  #database = [];
  #limit = 0;
  #select = [];
  #where = [];
  #orderBy = '';
 
  constructor ({ database }) {
    this.#database = database;
  };
 
  static for(database) {
    return new FluentSQLBuilder({ database });
  };
 
  limit (max) {
    this.#limit = max;
    return this;
  };
 
  where (query) {
    // { category: 'developer' }
    // { category: /developer/ }
    const [[ prop, selectedValue ]] = Object.entries(query);
      /* Exemplo:
        [
          [category, 'developer']
        ]
      */
 
    const whereFilter = selectedValue instanceof RegExp ? 
      selectedValue : new RegExp(selectedValue);
        // transforma qualquer valor em uma regex
 
    
    this.#where.push({ prop, filter: whereFilter }); 
    return this;
  };
 
  select (props) {
    this.#select = props;
    return this;
  };
 
  orderBy (field) {
    this.#orderBy = field;
    return this;
  };
 
  #performLimit (results) {
    return this.#limit && results.length === this.#limit;
  };
 
  #performWhere (item) {
    for (const { filter, prop } of this.#where) {
      if (!filter.test(item[prop])) return false;
    };
 
    return true;
  };
 
  #performSelect (item) {
    const currentItem = {};
    const entries = Object.entries(item);
    for (const [key, value] of entries) {
      if (this.#select.length && !this.#select.includes(key)) continue; 
      currentItem[key] = value;
    };
 
    return currentItem;
  };
 
  #performOrderBy (results) {
    if (!this.#orderBy) return results;
 
    return results.sort((prev, next) => {
      return prev[this.#orderBy].localeCompare(next[this.#orderBy]);
    });
  };
 
  build () {
    const results = [];
    for (const item of this.#database) {
      if (!this.#performWhere(item)) continue;
      
      const currentItem = this.#performSelect(item);
 
      results.push(currentItem);
      
      if(this.#performLimit(results)) break;
    };
 
    const finalResult = this.#performOrderBy(results);
    return finalResult;
  };
};