1
- import { ApiError , Problems } from "@zuplo/errors" ;
1
+ import { ProblemDetails , Problems } from "@zuplo/errors" ;
2
2
import { load } from "js-yaml" ;
3
3
import { OpenApiFileExtension } from "./types.js" ;
4
4
import spectralCore , { Document } from "@stoplight/spectral-core" ;
5
5
import SpectralParsers from "@stoplight/spectral-parsers" ;
6
6
7
7
export const checkFileIsJsonOrYaml = (
8
8
fileContentString : string ,
9
- ) : OpenApiFileExtension => {
9
+ ) : OpenApiFileExtension | ProblemDetails => {
10
10
try {
11
11
JSON . parse ( fileContentString ) ;
12
12
return "json" ;
@@ -21,16 +21,16 @@ export const checkFileIsJsonOrYaml = (
21
21
// Ignore
22
22
}
23
23
24
- throw new ApiError ( {
24
+ return {
25
25
...Problems . BAD_REQUEST ,
26
26
detail : "Invalid file format. Only JSON and YAML are supported." ,
27
- } ) ;
27
+ } ;
28
28
} ;
29
29
30
30
const validateOpenapi = ( options : {
31
31
fileContent : string ;
32
32
fileExtension : string ;
33
- } ) => {
33
+ } ) : { isValid : true } | { isValid : false ; error : ProblemDetails } => {
34
34
const parser =
35
35
options . fileExtension === "json"
36
36
? SpectralParsers . Json
@@ -44,27 +44,43 @@ const validateOpenapi = (options: {
44
44
options . fileExtension ,
45
45
) ;
46
46
} catch ( err ) {
47
- throw new ApiError ( {
48
- ...Problems . BAD_REQUEST ,
49
- detail : "Could not parse OpenAPI file. Possible syntax error." ,
50
- } ) ;
47
+ return {
48
+ isValid : false ,
49
+ error : {
50
+ ...Problems . BAD_REQUEST ,
51
+ detail : "Could not parse OpenAPI file. Possible syntax error." ,
52
+ } ,
53
+ } ;
51
54
}
52
55
53
- // TODO: clean this up
54
56
// eslint-disable-next-line @typescript-eslint/no-explicit-any
55
- const openAPIFileVersion = ( openApiSpectralDoc . data as any ) ?. openapi || "" ;
57
+ const openAPIFileVersion = ( openApiSpectralDoc . data as any ) ?. openapi ;
56
58
57
59
if ( ! openAPIFileVersion ) {
58
60
// if no version is specified, assume it's a swagger file
59
- return false ;
61
+ return {
62
+ isValid : false ,
63
+ error : {
64
+ ...Problems . BAD_REQUEST ,
65
+ detail : "No OpenAPI version specified. Only OpenAPI v3.x is supported." ,
66
+ } ,
67
+ } ;
60
68
}
61
69
62
70
const validVersionExists =
63
71
[ "3.0.0" , "3.0.1" , "3.0.2" , "3.0.3" , "3.1.0" ] . find ( ( version ) =>
64
72
openAPIFileVersion . includes ( version ) ,
65
73
) !== undefined ;
66
-
67
- return validVersionExists ;
74
+ if ( ! validVersionExists ) {
75
+ return {
76
+ isValid : false ,
77
+ error : {
78
+ ...Problems . BAD_REQUEST ,
79
+ detail : `Invalid OpenAPI version. Only OpenAPI v3.x is supported. Found: ${ openAPIFileVersion } .` ,
80
+ } ,
81
+ } ;
82
+ }
83
+ return { isValid : true } ;
68
84
} ;
69
85
70
86
export default validateOpenapi ;
0 commit comments