From 872a057d8b98409dad7933975e8ef010e1abf4f2 Mon Sep 17 00:00:00 2001 From: Boris Cherny Date: Thu, 2 May 2024 15:16:45 +0900 Subject: [PATCH] [Chore] Clean up yaml parsing --- src/index.ts | 31 ++++++++++++++++--------------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/src/index.ts b/src/index.ts index e8ea599b..48035e84 100644 --- a/src/index.ts +++ b/src/index.ts @@ -113,11 +113,12 @@ export const DEFAULT_OPTIONS: Options = { unknownAny: true, } -function isYml(filename: string) { - return filename.endsWith('.yaml') || filename.endsWith('.yml') +export function compileFromFile(filename: string, options: Partial = DEFAULT_OPTIONS): Promise { + const schema = parseAsJSONSchema(filename) + return compile(schema, stripExtension(filename), {cwd: dirname(filename), ...options}) } -export function compileFromFile(filename: string, options: Partial = DEFAULT_OPTIONS): Promise { +function parseAsJSONSchema(filename: string): JSONSchema4 { const contents = Try( () => readFileSync(filename), () => { @@ -125,25 +126,25 @@ export function compileFromFile(filename: string, options: Partial = DE }, ) - let schema: JSONSchema4 - - if (isYml(filename)) { - schema = Try( + if (isYaml(filename)) { + return Try( () => yaml.load(contents.toString()) as JSONSchema4, () => { throw new TypeError(`Error parsing YML in file "${filename}"`) }, ) - } else { - schema = Try( - () => JSON.parse(contents.toString()), - () => { - throw new TypeError(`Error parsing JSON in file "${filename}"`) - }, - ) } - return compile(schema, stripExtension(filename), {cwd: dirname(filename), ...options}) + return Try( + () => JSON.parse(contents.toString()), + () => { + throw new TypeError(`Error parsing JSON in file "${filename}"`) + }, + ) +} + +function isYaml(filename: string) { + return filename.endsWith('.yaml') || filename.endsWith('.yml') } export async function compile(schema: JSONSchema4, name: string, options: Partial = {}): Promise {