Skip to content

Commit

Permalink
[Chore] Clean up yaml parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
bcherny committed May 2, 2024
1 parent 13806bd commit 872a057
Showing 1 changed file with 16 additions and 15 deletions.
31 changes: 16 additions & 15 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,37 +113,38 @@ 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<Options> = DEFAULT_OPTIONS): Promise<string> {
const schema = parseAsJSONSchema(filename)
return compile(schema, stripExtension(filename), {cwd: dirname(filename), ...options})
}

export function compileFromFile(filename: string, options: Partial<Options> = DEFAULT_OPTIONS): Promise<string> {
function parseAsJSONSchema(filename: string): JSONSchema4 {
const contents = Try(
() => readFileSync(filename),
() => {
throw new ReferenceError(`Unable to read file "${filename}"`)
},
)

let schema: JSONSchema4

if (isYml(filename)) {
schema = Try<JSONSchema4>(
if (isYaml(filename)) {
return Try(
() => yaml.load(contents.toString()) as JSONSchema4,
() => {
throw new TypeError(`Error parsing YML in file "${filename}"`)
},
)
} else {
schema = Try<JSONSchema4>(
() => 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<Options> = {}): Promise<string> {
Expand Down

0 comments on commit 872a057

Please sign in to comment.