Skip to content

Commit 872a057

Browse files
committed
[Chore] Clean up yaml parsing
1 parent 13806bd commit 872a057

File tree

1 file changed

+16
-15
lines changed

1 file changed

+16
-15
lines changed

src/index.ts

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -113,37 +113,38 @@ export const DEFAULT_OPTIONS: Options = {
113113
unknownAny: true,
114114
}
115115

116-
function isYml(filename: string) {
117-
return filename.endsWith('.yaml') || filename.endsWith('.yml')
116+
export function compileFromFile(filename: string, options: Partial<Options> = DEFAULT_OPTIONS): Promise<string> {
117+
const schema = parseAsJSONSchema(filename)
118+
return compile(schema, stripExtension(filename), {cwd: dirname(filename), ...options})
118119
}
119120

120-
export function compileFromFile(filename: string, options: Partial<Options> = DEFAULT_OPTIONS): Promise<string> {
121+
function parseAsJSONSchema(filename: string): JSONSchema4 {
121122
const contents = Try(
122123
() => readFileSync(filename),
123124
() => {
124125
throw new ReferenceError(`Unable to read file "${filename}"`)
125126
},
126127
)
127128

128-
let schema: JSONSchema4
129-
130-
if (isYml(filename)) {
131-
schema = Try<JSONSchema4>(
129+
if (isYaml(filename)) {
130+
return Try(
132131
() => yaml.load(contents.toString()) as JSONSchema4,
133132
() => {
134133
throw new TypeError(`Error parsing YML in file "${filename}"`)
135134
},
136135
)
137-
} else {
138-
schema = Try<JSONSchema4>(
139-
() => JSON.parse(contents.toString()),
140-
() => {
141-
throw new TypeError(`Error parsing JSON in file "${filename}"`)
142-
},
143-
)
144136
}
145137

146-
return compile(schema, stripExtension(filename), {cwd: dirname(filename), ...options})
138+
return Try(
139+
() => JSON.parse(contents.toString()),
140+
() => {
141+
throw new TypeError(`Error parsing JSON in file "${filename}"`)
142+
},
143+
)
144+
}
145+
146+
function isYaml(filename: string) {
147+
return filename.endsWith('.yaml') || filename.endsWith('.yml')
147148
}
148149

149150
export async function compile(schema: JSONSchema4, name: string, options: Partial<Options> = {}): Promise<string> {

0 commit comments

Comments
 (0)