All files / src/transform jsonSchema.ts

100% Statements 17/17
100% Branches 6/6
100% Functions 6/6
100% Lines 14/14

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 232x 2x 2x 29x 29x             29x 2x 29x 29x 29x   29x 29x 29x 27x    
import Ajv, { ErrorObject } from 'ajv'
import { loadJSON } from '../util.js'
export const jsonValidatorInit = () => {
  return new Ajv({
    loadSchema: async (uri: any) => loadJSON(uri)
  })
}
 
export type jsonValidationSuccess = {type:'success', errors? : (ErrorObject | string)[]};
export type jsonValidationError = {type:'error', errors : (ErrorObject | string)[]};
export type validateResult = jsonValidationSuccess | jsonValidationError;
export const isValidationError = (input:validateResult) : input is jsonValidationError => input && input.type === 'error'
export const validate = async (json: Object, data:any):
 Promise<validateResult> => {
  const validator = await jsonValidatorInit().compileAsync(json)
  const result = validator(data)
 
  const errors: (ErrorObject | string)[] = validator.errors || []
  errors.push(JSON.stringify(json, null, 2))
  if (!result) return { type: 'error', errors }
  return { type: 'success' }
}