All files / resource resource.service.ts

91.94% Statements 57/62
79.49% Branches 31/39
100% Functions 9/9
91.67% Lines 55/60

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 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211          18x 18x   18x         18x           18x   34x 34x                   2x     2x                       523x         523x 522x   1x   1x               519x   519x 519x           2x           1x                             11x         11x 10x   4x             4x     4x   4x 2x   2x     8x           8x   4x         2x         2x     1x                         2x     2x 48x   2x 2x   44x 44x   2x 2x     48x     2x                 3x       3x 72x   3x       3x   66x       66x   3x 3x     72x        
/**
 * Resource service.
 * @packageDocumentation
 */
 
import { Injectable, Inject, forwardRef } from '@nestjs/common';
import { DBService } from '../db/db.service';
import { NBResource, ResourceMap } from './resource.interface';
import { ServiceException } from '../service.exception';
 
/**
 * Resource table name.
 */
export const resourceTableName = 'NB_RESOURCE';
 
/**
 * Resource table service.
 */
@Injectable()
export class ResourceService {
  constructor(
    @Inject(forwardRef(() => DBService))
    private readonly dbService: DBService,
  ) {}
 
  /**
   * Determine whether or not an app resource exists.
   *
   * @param name The name of the resource.
   * @returns Whether or not the resource exists.
   */
  public async resourceExists(name: string): Promise<boolean> {
    const resource = await this.dbService.getByFields<
      NBResource<boolean | number | string>
    >(resourceTableName, { name });
    return !!resource;
  }
 
  /**
   * Get an app resource.
   *
   * @param name The name of the resource.
   * @returns The value of the requested resource.
   */
  public async getResource<T extends boolean | number | string>(
    name: string,
  ): Promise<T> {
    const resource = await this.dbService.getByFields<NBResource<T>>(
      resourceTableName,
      { name },
    );
 
    if (resource) {
      switch (resource.type) {
        case 'BOOLEAN':
          switch (resource.value) {
            case 'true':
              return true as T;
            case 'false':
              return false as T;
            default:
              throw new ServiceException('Failed to parse resource to boolean');
          }
 
        case 'NUMBER':
          const value = parseFloat(resource.value as string);
 
          Eif (!isNaN(value)) {
            return value as T;
          } else {
            throw new ServiceException('Failed to parse resource to number');
          }
 
        case 'STRING':
          return resource.value as T;
 
        default:
          throw new ServiceException('Invalid resource type');
      }
    } else {
      throw new ServiceException('Resource does not exist');
    }
  }
 
  /**
   * Set an app resource's value.
   *
   * @param name The name of the resource.
   * @param value The new value of the resource.
   * @returns The updated resource record.
   */
  public async setResource<T extends boolean | number | string>(
    name: string,
    value: T,
  ): Promise<NBResource<T>> {
    const resource = await this.dbService.getByFields<NBResource<T>>(
      resourceTableName,
      { name },
    );
 
    if (resource) {
      switch (resource.type) {
        case 'BOOLEAN':
          Iif (
            typeof value !== 'boolean' &&
            value !== 'true' &&
            value !== 'false'
          ) {
            throw new ServiceException('Resource type must be boolean');
          }
          break;
 
        case 'NUMBER':
          const numberValue = parseFloat(value.toString());
 
          if (typeof value !== 'number' && isNaN(numberValue)) {
            throw new ServiceException('Resource type must be number');
          }
          break;
      }
 
      const resources = await this.dbService.updateByFields<NBResource<T>>(
        resourceTableName,
        { name },
        { value: value.toString() },
      );
 
      switch (resources[0].type) {
        case 'BOOLEAN':
          return {
            ...resources[0],
            value: (resources[0].value === 'true' ? true : false) as T,
          };
        case 'NUMBER':
          return {
            ...resources[0],
            value: parseFloat(resources[0].value as string) as T,
          };
        case 'STRING':
          return resources[0];
      }
    } else {
      throw new ServiceException('Resource does not exist');
    }
  }
 
  /**
   * Reset an app resource's value.
   *
   * @param name The name of the resource.
   * @returns The updated resource record.
   */
  public async resetResource<T extends boolean | number | string>(
    name: string,
  ): Promise<NBResource<T>> {
    const resourceArray = await this.dbService.getStaticTable(
      resourceTableName,
    );
    const defaultResources = resourceArray.reduce((acc, resource) => {
      switch (resource.type) {
        case 'BOOLEAN':
          acc[resource.name] = resource.value === 'true' ? true : false;
          break;
        case 'NUMBER':
          acc[resource.name] = parseFloat(resource.value as string);
          break;
        case 'STRING':
          acc[resource.name] = resource.value;
          break;
      }
 
      return acc;
    }, {});
 
    return this.setResource<T>(name, defaultResources[name]);
  }
 
  /**
   * Get all app resources.
   *
   * @returns All resources.
   */
  public async getResources(): Promise<ResourceMap> {
    const resources = await this.dbService.list<
      NBResource<boolean | number | string>
    >(resourceTableName, { fieldName: 'name', sortOrder: 'ASC' });
 
    return resources.reduce((acc, resource) => {
      switch (resource.type) {
        case 'BOOLEAN':
          acc[resource.name] = {
            value: resource.value === 'true' ? true : false,
            type: resource.type,
          };
          break;
        case 'NUMBER':
          acc[resource.name] = {
            value: parseFloat(resource.value as string),
            type: resource.type,
          };
          break;
        case 'STRING':
          acc[resource.name] = { value: resource.value, type: resource.type };
          break;
      }
 
      return acc;
    }, {});
  }
}