Skip to content

Commit 8ffbe84

Browse files
authored
Get content type from request (#516)
1 parent d98ab73 commit 8ffbe84

File tree

2 files changed

+25
-10
lines changed

2 files changed

+25
-10
lines changed

bin/loaders/index.js

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,7 @@ async function load(pathToSpec, { auth }) {
99
// option 1: remote URL
1010
if (/^https?:\/\//.test(pathToSpec)) {
1111
try {
12-
const rawSpec = await loadFromHttp(pathToSpec, { auth });
13-
return rawSpec;
12+
return loadFromHttp(pathToSpec, { auth });
1413
} catch (e) {
1514
if (e.code === "ENOTFOUND") {
1615
throw new Error(
@@ -22,35 +21,48 @@ async function load(pathToSpec, { auth }) {
2221
}
2322

2423
// option 2: local file
25-
return loadFromFs(pathToSpec);
24+
return {
25+
body: loadFromFs(pathToSpec),
26+
contentType: mime.getType(pathToSpec),
27+
};
2628
}
2729

2830
async function loadSpec(pathToSpec, { auth, log = true }) {
2931
if (log === true) {
3032
console.log(yellow(`🔭 Loading spec from ${bold(pathToSpec)}…`)); // only log if not writing to stdout
3133
}
3234

33-
const contentType = mime.getType(pathToSpec);
34-
const rawSpec = await load(pathToSpec, { auth });
35+
const { body, contentType } = await load(pathToSpec, { auth });
3536

3637
switch (contentType) {
38+
case "application/openapi+yaml":
3739
case "text/yaml": {
3840
try {
39-
return yaml.load(rawSpec);
41+
return yaml.load(body);
4042
} catch (err) {
4143
throw new Error(`YAML: ${err.toString()}`);
4244
}
4345
}
4446
case "application/json":
45-
case "application/json5": {
47+
case "application/json5":
48+
case "application/openapi+json": {
4649
try {
47-
return JSON.parse(rawSpec);
50+
return JSON.parse(body);
4851
} catch (err) {
4952
throw new Error(`JSON: ${err.toString()}`);
5053
}
5154
}
5255
default: {
53-
throw new Error(`Unknown format${contentType ? `: "${contentType}"` : ""}. Only YAML or JSON supported.`);
56+
try {
57+
return JSON.parse(body); // unknown attempt 1: JSON
58+
} catch (err1) {
59+
try {
60+
return yaml.load(body); // unknown attempt 2: YAML
61+
} catch (err2) {
62+
// give up: unknown type
63+
throw new Error(`Unknown format${contentType ? `: "${contentType}"` : ""}. Only YAML or JSON supported.`);
64+
}
65+
}
5466
}
5567
}
5668
}

bin/loaders/loadFromHttp.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,10 @@ function fetch(url, opts, { redirectCount = 0 } = {}) {
2323
res.on("end", () => {
2424
// 2xx: OK
2525
if (res.statusCode >= 200 && res.statusCode < 300) {
26-
return resolve(rawData);
26+
return resolve({
27+
body: rawData,
28+
contentType: res.headers["content-type"].split(";")[0].trim(),
29+
});
2730
}
2831

2932
// 3xx: follow redirect (if given)

0 commit comments

Comments
 (0)