# All files / src ddfcsv-reader.ts

69.23% Statements 45/65
62.5% Branches 25/40
53.33% Functions 8/15
69.23% Lines 45/65

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
    1451x
    1x

    1x
    1x
    1x
    1x

    1x
    1x

    1x
    1x
    5524x

    5543x

    5543x
    5543x
    5543x
    5543x

    5543x

    5543x

    2x
    2x
    2x

    2x
    2x
    2x

    3x
    1x

    2x
    2x

    2x

    5540x

    5540x

    5540x

    5540x
    5540x
    4x
    4x
    4x
    4x

    5536x

    5516x

    5516x

    5516x

    24x
    24x

    5516x

     import * as isEmpty from 'lodash.isempty';
    import { ddfCsvReader } from './ddf-csv';
    import { IResourceRead } from './interfaces';
    import { getRepositoryPath } from 'ddf-query-validator';
    import { DdfCsvError } from './ddfcsv-error';
    import { createDiagnosticManagerOn, EndpointDiagnosticManager, getLevelByLabel } from 'cross-project-diagnostics';
    import { DiagnosticManager, Level } from 'cross-project-diagnostics/lib';
    import { githubPathAdapter } from './file-readers/github-path-adapter';

    const myName = '';
    const myVersion = '';

    export function prepareDDFCsvReaderObject (defaultResourceReader?: IResourceRead) {
      return function(externalResourceReader?: IResourceRead, logger?: any) {
        return {
          init (readerInfo) {
            // TODO: check validity of base path
            this._basePath = githubPathAdapter(readerInfo.path || '');

            this._lastModified = readerInfo._lastModified;
            this.fileReader = externalResourceReader || defaultResourceReader;
            this.logger = logger;
            this.resultTransformer = readerInfo.resultTransformer;

            this.readerOptions = {
              basePath: this._basePath,
              fileReader: this.fileReader,
              logger: this.logger,
            };

            this.reader = ddfCsvReader(this.logger);
          },

          getDatasetInfo(): Object {
            return {name: this._basePath.slice(this._basePath.indexOf('ddf--'))};
          },

          async checkFile(path: string): Promise<any> {
            return new Promise((resolve, reject) => {
              const status = this.fileReader.checkFile(path);
              return resolve({status, url: path});
            });
          },

          async getFile (filePath: string, isJsonFile: boolean, options: object): Promise<any> {
            return new Promise((resolve, reject) => {
              this.fileReader.readText(filePath, (err, data) => {
                Iif (err) {
                  return reject(err);
                }

                try {
                  Eif (isJsonFile) {
                    return resolve(JSON.parse(data));
                  }

                  return resolve(data);
                } catch (jsonErr) {
                  return reject(jsonErr);
                }
              }, options);
            });
          },

          async checkIfAssetExists (filePath: string, repositoryPath: string = ''): Promise<any> {
            if (isEmpty(repositoryPath) && isEmpty(this._basePath)) {
              throw new DdfCsvError(`Neither initial 'path' nor 'repositoryPath' as a second param were found.`, `Happens in 'checkIfAssetExists' function`, filePath);
            }

            const assetPath = `${repositoryPath || this._basePath}/assets/${filePath}`;

            return await this.checkFile(assetPath);
          },

          async getAsset (filePath: string, repositoryPath: string = ''): Promise<any> {
            if (isEmpty(repositoryPath) && isEmpty(this._basePath)) {
              throw new DdfCsvError(`Neither initial 'path' nor 'repositoryPath' as a second param were found.`, `Happens in 'getAsset' function`, filePath);
            }

            const assetPath = `${repositoryPath || this._basePath}/${filePath}`;
            const isJsonAsset = (assetPath).slice(-'.json'.length) === '.json';

            return await this.getFile(assetPath, isJsonAsset);
          },

          async read (queryParam, parsers, parentDiagnostic?: DiagnosticManager) {
            const diagnostic = parentDiagnostic ?
              createDiagnosticManagerOn(myName, myVersion).basedOn(parentDiagnostic) :
              createDiagnosticManagerOn(myName, myVersion).forRequest('').withSeverityLevel(Level.OFF);
            const { debug, error, fatal } = diagnostic.prepareDiagnosticFor('read');

            let result;

            debug('start reading', queryParam);

            try {
              if (isEmpty(queryParam.repositoryPath) && isEmpty(this._basePath)) {
                const message = `Neither initial 'path' nor 'repositoryPath' in query were found.`;
                const err = new DdfCsvError(message, JSON.stringify(queryParam));
                error(message, err);
                throw err;
              }

              result = await this.reader.query(queryParam, {
                basePath: queryParam.repositoryPath || this._basePath,
                fileReader: this.fileReader,
                logger: this.logger,
                conceptsLookup: new Map<string, any>(),
                diagnostic
              });
              result = parsers ? this._prettifyData(result, parsers) : result;

              Iif (this.resultTransformer) {
                result = this.resultTransformer(result);
              }

              Iif (this.logger && this.logger.log) {
                logger.log(JSON.stringify(queryParam), result.length);
                logger.log(result);
              }
            } catch (err) {
              fatal('global data reading error', err);
              throw err;
            }

            return result;
          },

          _prettifyData (data, parsers) {
            return data.map(record => {
              const keys = Object.keys(record);

              keys.forEach(key => {
                if (parsers[ key ]) {
                  record[ key ] = parsers[ key ](record[ key ]);
                }
              });

              return record;
            });
          }
        };
      };
    }