Skip to content

Commit

Permalink
feat: implement streamed HTTP queries
Browse files Browse the repository at this point in the history
  • Loading branch information
Kuruyia committed Dec 1, 2022
1 parent 6cad20f commit 481c202
Showing 1 changed file with 42 additions and 2 deletions.
44 changes: 42 additions & 2 deletions src/support/kuzzle.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { flags } from "@oclif/command";
import http from "http";

import { Http, WebSocket, Kuzzle } from "kuzzle-sdk";
import { flags } from "@oclif/command";
import { Http, WebSocket, Kuzzle, JSONObject } from "kuzzle-sdk";

const SECOND = 1000;

Expand Down Expand Up @@ -199,6 +200,45 @@ export class KuzzleSDK {
return this.sdk.query(request);
}

/**
* Query the Kuzzle API and return a streamed response.
* @param request The request to send to Kuzzle
* @returns The response stream
*/
public queryHttpStream(request: JSONObject): Promise<http.IncomingMessage> {
// Ensure the protocol is HTTP
if (this.protocol !== "http") {
throw new TypeError("HTTP streaming is only available with the HTTP protocol");
}

// Construct the URL
const url = `${this.ssl ? "https" : "http"}://${this.host}:${this.port}/_query`;

// Construct the request
const body = JSON.stringify(request);

const options = {
method: "POST",
headers: {
"Authorization": `Bearer ${this.sdk.jwt}`,
"Content-Length": Buffer.byteLength(body),
"Content-Type": "application/json",
},
};

// Send the request
return new Promise((resolve, reject) => {
const req = http.request(url, options, (res) => {
resolve(res);
});

req.on("error", reject);

req.write(body);
req.end();
});
}

get document() {
return this.sdk.document;
}
Expand Down

0 comments on commit 481c202

Please sign in to comment.