|
1 | 1 | import { parse } from 'yaml'; |
2 | | -import { readFileSync } from 'node:fs'; |
3 | | -import { RawServerlessIac } from '../types'; |
| 2 | +import { existsSync, readFileSync } from 'node:fs'; |
| 3 | +import { IacFunction, RawServerlessIac, ServerlessIac, Event } from '../types'; |
| 4 | +import { validateYaml } from './iacSchema'; |
4 | 5 |
|
5 | 6 | const mapToArr = (obj: Record<string, Record<string, unknown> | string>) => { |
6 | 7 | return Object.entries(obj).map(([key, value]) => |
7 | 8 | typeof value === 'string' ? { [key]: value } : { id: key, ...value }, |
8 | 9 | ); |
9 | 10 | }; |
10 | 11 |
|
11 | | -const transformYaml = (iacJson: RawServerlessIac) => { |
| 12 | +const validateExistence = (path: string) => { |
| 13 | + if (!existsSync(path)) { |
| 14 | + throw new Error(`File does not exist at path: ${path}`); |
| 15 | + } |
| 16 | +}; |
| 17 | + |
| 18 | +const transformYaml = (iacJson: RawServerlessIac): ServerlessIac => { |
12 | 19 | return { |
13 | 20 | service: iacJson.service, |
14 | 21 | version: iacJson.version, |
15 | 22 | provider: iacJson.provider, |
16 | 23 | vars: iacJson.vars, |
17 | 24 | stages: iacJson.stages, |
18 | | - functions: mapToArr(iacJson.functions), |
19 | | - events: mapToArr(iacJson.events), |
20 | | - tags: mapToArr(iacJson.tags), |
| 25 | + functions: mapToArr(iacJson.functions) as unknown as Array<IacFunction>, |
| 26 | + events: mapToArr(iacJson.events) as unknown as Array<Event>, |
| 27 | + tags: mapToArr(iacJson.tags) as unknown as Array<string>, |
21 | 28 | }; |
22 | 29 | }; |
23 | 30 |
|
24 | | -export const parseYaml = (path: string) => { |
25 | | - // read yaml from path |
| 31 | +export const parseYaml = (path: string): ServerlessIac => { |
| 32 | + validateExistence(path); |
| 33 | + |
26 | 34 | const yamlContent = readFileSync(path, 'utf8'); |
27 | 35 | const iacJson = parse(yamlContent) as RawServerlessIac; |
28 | 36 |
|
| 37 | + validateYaml(iacJson); |
| 38 | + |
29 | 39 | return transformYaml(iacJson); |
30 | 40 | }; |
0 commit comments