@@ -86,8 +86,7 @@ Promise.all(
86
86
try {
87
87
resolve ( readFile ( path . resolve ( filePath ) ) )
88
88
} catch ( error ) {
89
- console . error ( error )
90
- reject ( filePath )
89
+ reject ( error )
91
90
}
92
91
93
92
// Check if file is in a remote location
@@ -97,24 +96,21 @@ Promise.all(
97
96
resolve ( remoteContent )
98
97
} )
99
98
. catch ( error => {
100
- console . error ( error )
101
- reject ( filePath )
99
+ reject ( error )
102
100
} )
103
101
104
102
// Cannot determine location of file
105
103
} else {
106
- reject ( filePath )
104
+ reject ( `File path ' ${ filePath } ' is invalid` )
107
105
}
108
106
} )
109
107
} )
110
108
)
111
109
. then ( oass => {
112
110
startGraphQLServer ( oass , portNumber )
113
111
} )
114
- . catch ( filePath => {
115
- console . error (
116
- `OpenAPI-to-GraphQL cannot read file. File '${ filePath } ' does not exist.`
117
- )
112
+ . catch ( error => {
113
+ console . error ( error )
118
114
process . exit ( 1 )
119
115
} )
120
116
@@ -125,14 +121,15 @@ Promise.all(
125
121
* @return {object } Content of read file
126
122
*/
127
123
function readFile ( path ) {
128
- try {
129
- const doc = / j s o n $ / . test ( path )
130
- ? JSON . parse ( fs . readFileSync ( path , 'utf8' ) )
131
- : yaml . safeLoad ( fs . readFileSync ( path , 'utf8' ) )
132
- return doc
133
- } catch ( e ) {
134
- console . error ( 'Error: failed to parse YAML/JSON' )
135
- return null
124
+ if ( / j s o n $ / . test ( path ) ) {
125
+ return JSON . parse ( fs . readFileSync ( path , 'utf8' ) )
126
+
127
+ } else if ( / y a m l $ / . test ( path ) || / y m l $ / . test ( path ) ) {
128
+ return yaml . safeLoad ( fs . readFileSync ( path , 'utf8' ) )
129
+
130
+ } else {
131
+ throw new Error ( `Failed to parse JSON/YAML. Ensure file '${ path } ' has ` +
132
+ `the correct extension (i.e. '.json', '.yaml', or '.yml).` )
136
133
}
137
134
}
138
135
@@ -144,16 +141,31 @@ function getRemoteFileSpec(uri) {
144
141
return new Promise ( ( resolve , reject ) => {
145
142
request (
146
143
{
147
- uri,
148
- json : true
144
+ uri
149
145
} ,
150
146
( err , res , body ) => {
151
147
if ( err ) {
152
148
reject ( err )
153
- } else if ( res . statusCode !== 200 ) {
154
- reject ( new Error ( `Error: ${ JSON . stringify ( body ) } ` ) )
149
+ } else if ( res . statusCode < 200 && res . statusCode <= 300 ) {
150
+ reject (
151
+ new Error (
152
+ `Could not retrieve file. Received unsuccessful status code '${ res . statusCode } .`
153
+ )
154
+ )
155
155
} else {
156
- resolve ( body )
156
+ if ( typeof body === 'string' ) {
157
+ try {
158
+ resolve ( JSON . parse ( body ) )
159
+ } catch ( e ) {
160
+ try {
161
+ resolve ( yaml . safeLoad ( body ) )
162
+ } catch ( f ) {
163
+ console . error ( `JSON parse error: ${ e } \nYAML parse error: ${ f } ` )
164
+ }
165
+ }
166
+ }
167
+
168
+ reject ( new Error ( `Cannot parse remote file` ) )
157
169
}
158
170
}
159
171
)
0 commit comments