Skip to content

Commit

Permalink
Fix empty raw responses parsed as json
Browse files Browse the repository at this point in the history
  • Loading branch information
fmauNeko committed Nov 6, 2023
1 parent e4bdf50 commit c522bee
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 5 deletions.
14 changes: 12 additions & 2 deletions src/protocols/Http.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
"use strict";

import staticHttpRoutes from "./routes.json";
import { KuzzleAbstractProtocol } from "./abstract/Base";
import { HttpRoutes, JSONObject } from "../types";
import { RequestPayload } from "../types/RequestPayload";
import { KuzzleAbstractProtocol } from "./abstract/Base";
import staticHttpRoutes from "./routes.json";

/**
* Http protocol used to connect to a Kuzzle server.
Expand Down Expand Up @@ -405,6 +405,11 @@ export default class HttpProtocol extends KuzzleAbstractProtocol {
);
}

const contentType = response.headers["content-type"];
if (!contentType || !contentType.includes("application/json")) {
return response.body;
}

return JSON.parse(response.body);
});
}
Expand Down Expand Up @@ -435,6 +440,11 @@ export default class HttpProtocol extends KuzzleAbstractProtocol {

xhr.onload = () => {
try {
const contentType = xhr.getResponseHeader("Content-Type");
if (!contentType || !contentType.includes("application/json")) {
resolve(xhr.responseText);
return;
}
const json = JSON.parse(xhr.responseText);
resolve(json);
} catch (err) {
Expand Down
10 changes: 7 additions & 3 deletions test/protocol/Http.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -677,9 +677,12 @@ describe("HTTP networking module", () => {
let httpRequestStub;

beforeEach(() => {
httpRequestStub = sinon
.stub()
.resolves({ body: JSON.stringify(mockResponseBody) });
httpRequestStub = sinon.stub().resolves({
body: JSON.stringify(mockResponseBody),
headers: {
"content-type": "application/json",
},
});

const { default: MockHttp } = proxyquire("../../src/protocols/Http", {
"min-req-promise": { request: httpRequestStub },
Expand Down Expand Up @@ -793,6 +796,7 @@ describe("HTTP networking module", () => {
open: sinon.stub(),
send: sinon.stub(),
setRequestHeader: sinon.stub(),
getResponseHeader: sinon.stub().returns("application/json"),
onreadystatechange: sinon.stub(),
timeout: 0,
};
Expand Down

0 comments on commit c522bee

Please sign in to comment.