All files / src/repositories search.view.repository.ts

39.29% Statements 11/28
0% Branches 0/18
33.33% Functions 1/3
36% Lines 9/25

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 671x 1x 1x 1x   1x   1x   1x           1x     20x                                                                                                
import { inject } from '@loopback/core';
import { LogChainDataSource } from '../datasources';
import { BaseCrudRepository } from './base-crud.repository.base';
import { SearchView, SearchViewRelations } from '@logchain/models/views';
import { UserProfile } from '../components/aws';
import { SecurityBindings } from '@loopback/security';
import { AnyObject, FilterBuilder, Options } from '@loopback/repository';
import { Constants } from '@logchain/configs';
 
export class SearchViewRepository extends BaseCrudRepository<
  SearchView,
  typeof SearchView.prototype.id,
  SearchViewRelations
> {
  @inject(SecurityBindings.USER, { optional: true })
  public current_user: UserProfile;
 
  constructor(@inject('datasources.logchain') dataSource: LogChainDataSource) {
    super(SearchView, dataSource);
  }
  
  /**
   * Query on database based on search all filter
   * @param  {FilterBuilder} filterBuilder
   * @param  {Options={}} options
   */
  async fillRelation(filterBuilder: FilterBuilder, options: Options = {}) {
    const where = filterBuilder.build().where as AnyObject;
    if (where['ownership'] === 'Own') {
      filterBuilder.impose({ company_id: this.current_user.company_id });
    } else if (where['ownership'] === 'Other') {
      filterBuilder.impose({ company_id: { neq: this.current_user.company_id }});
    }
    delete where['ownership'];
    const filter = filterBuilder.build();
    const { offset = 0, limit = Constants.DefaultLimit, order = []} = filter;
    const sort = (order?.[0] ? order : ['id ASC']);
    const params = [
      this.current_user.company_id,
      offset, limit
    ];
    const flows = await this.find({
      fields: ['search_id'],
      where
    });
    const searchIds = flows.map((item) => item.search_id);
    const sql = `SELECT * FROM (
      SELECT
        *,
        CASE WHEN company_id = $1 THEN 'Own' ELSE 'Other' END AS ownership
      FROM "search_view"
    ) AS sv
    ${searchIds.length ? 'WHERE sv.search_id IN (\'' + searchIds.join('\', \'') + '\')' : 'WHERE 1!=1'}
    ${sort ? 'ORDER BY ' + sort.join(', ') : ''}
    OFFSET $2 LIMIT $3`;
 
    const data = await this.execute(sql, params) as unknown as SearchView[];
    const count = await this.count({ search_id: { inq: searchIds } }, options);
 
    return {
      total: count.count,
      has_more: count.count > offset + limit,
      data,
    };
  }
}