UNPKG

1.09 kBPlain TextView Raw
1import * as fs from 'fs'
2import { JsonSchema } from '@naturalcycles/js-lib'
3import { GlobbyOptions } from 'globby'
4import * as globby from 'globby'
5import { AjvSchema, AjvSchemaCfg } from './ajvSchema'
6
7/**
8 * Does fs.readFileSync + JSON.parse for ALL files matching the passed `glob` pattern.
9 * E.g `someDir/**\/*.schema.json`
10 *
11 * Returns them as an array of JsonSchema.
12 *
13 * @experimental
14 */
15export function readJsonSchemas(patterns: string | string[], opt?: GlobbyOptions): JsonSchema[] {
16 return globby.sync(patterns, opt).map(fileName => JSON.parse(fs.readFileSync(fileName, 'utf8')))
17}
18
19/**
20 * Reads json schemas from given dir (glob pattern).
21 * Creates new AjvSchema for each of them (ajv validates them upon creation).
22 * Passes `schemas` option to ajv, so, schemas may $ref each other and it'll be fine.
23 *
24 * @experimental
25 */
26export function readAjvSchemas(patterns: string | string[], cfg?: AjvSchemaCfg): AjvSchema[] {
27 const schemas = readJsonSchemas(patterns)
28 return schemas.map(schema =>
29 AjvSchema.create(schema, {
30 schemas,
31 ...cfg,
32 }),
33 )
34}