All files / src/faker FakerFaker.ts

88.46% Statements 23/26
100% Branches 9/9
100% Functions 6/6
88.46% Lines 23/26

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 621x     1x 13x 13x   13x                 1x       6x     6x 13x 17x   17x   7x 4x 4x 7x         3x   7x     10x 10x     17x             6x 6x 6x            
import { fake } from "faker"
import { IFaker } from "./IFaker"
 
const generateFake = (fieldName: string, fakeSpec: string): any => {
  try {
    const result = fake(fakeSpec)
 
    return Number(result) || result
  } catch (e) {
    console.error(
      `Failed to parse specification ${fieldName}: ${fakeSpec} ${e}`
    )
    throw e
  }
}
 
export default class FakerFaker implements IFaker {
  schema: string
 
  constructor(schema: string) {
    this.schema = schema
  }
 
  private schemaReducer = (schema: any): any =>
    Object.keys(schema).reduce((acc: any, key: string) => {
      const value = schema[key]
      let generatedFake
      switch (typeof value) {
        case "object":
          if (Array.isArray(value)) {
            const [{ quantity }, s] = value
            generatedFake = [...Array(quantity)].map(() =>
              typeof s === "string"
                ? generateFake(`${key}[]`, s)
                : this.schemaReducer(s)
            )
          } else {
            generatedFake = this.schemaReducer(value)
          }
          break
        case "string":
        default:
          generatedFake = generateFake(key, value)
          break
      }
 
      return {
        ...acc,
        [key]: generatedFake,
      }
    }, {})
 
  Fake(): any {
    try {
      const schema = JSON.parse(this.schema)
      return this.schemaReducer(schema)
    } catch (e) {
      throw new Error("Failed to parse schema file")
    }
  }
}