All files / src/util validators.ts

57.44% Statements 27/47
9.09% Branches 1/11
27.27% Functions 3/11
52.77% Lines 19/36

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  39x 39x 39x 39x   39x                       39x                     39x             39x               39x 4x   4x   1x     39x 4x 3x 1x     39x     39x 39x                    
import { BuildInfo } from '../Http';
import { CACHE_TTL_LOWER_LIMIT, CACHE_TTL_UPPER_LIMIT } from '../InMemoryCache';
import { Range, throwIfOutsideRange } from '@cardano-sdk/util';
import { validate } from 'jsonschema';
import fs from 'fs';
 
const buildInfoSchema = {
  additionalProperties: false,
  properties: {
    extra: { type: 'object' },
    lastModified: { type: 'number' },
    lastModifiedDate: { type: 'string' },
    rev: { type: 'string' },
    shortRev: { type: 'string' }
  },
  type: 'object'
};
 
export const buildInfoValidator = (buildInfo: string): BuildInfo => {
  let result: BuildInfo;
  try {
    result = JSON.parse(buildInfo || '{}');
  } catch (error) {
    throw new Error(`Invalid JSON format of build-info: ${error}`);
  }
  validate(result, buildInfoSchema, { throwError: true });
  return result;
};
 
export const existingFileValidator = (filePath: string) => {
  Iif (fs.existsSync(filePath)) {
    return filePath;
  }
  throw new Error(`No file exists at ${filePath}`);
};
 
export const floatValidator = (description: string) => (float: string) => {
  const parsed = Number.parseFloat(float);
 
  Iif (parsed.toString() === float || (float.startsWith('.') && parsed.toString() === `0${float}`)) return parsed;
 
  throw new TypeError(`${description} - "${float}" is not a number`);
};
 
export const integerValidator = (description: string) => (integer: string) => {
  const parsed = Number.parseInt(integer, 10);
 
  if (parsed.toString() === integer) return parsed;
 
  throw new TypeError(`${description} - "${integer}" is not an integer`);
};
 
export const cacheTtlValidator = (ttlInSecs: string, range: Required<Range<number>>, description: string) => {
  const cacheTtlInSecs = integerValidator(description)(ttlInSecs);
  throwIfOutsideRange(cacheTtlInSecs, range, description);
  return cacheTtlInSecs;
};
 
export const dbCacheValidator = (description: string) => (ttl: string) =>
  cacheTtlValidator(ttl, { lowerBound: CACHE_TTL_LOWER_LIMIT, upperBound: CACHE_TTL_UPPER_LIMIT }, description);
 
export const urlValidator =
  (description: string, toString = false) =>
  (url: string) => {
    try {
      const parsed = new URL(url);
 
      return toString ? parsed.toString() : parsed;
    } catch {
      throw new Error(`${description} - "${url}" is not an URL`);
    }
  };