Skip to content

Commit

Permalink
feat(http): perform basic http requests in node environments
Browse files Browse the repository at this point in the history
  • Loading branch information
Michael committed Oct 27, 2022
1 parent 85fa778 commit 37d9da2
Showing 1 changed file with 100 additions and 4 deletions.
104 changes: 100 additions & 4 deletions lib/core/api/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,109 @@ import url from "url";
import type {
DispatchedResponse,
UrbexRequestApi,
InternalUrbexConfiguration
URLProtocol,
ParsedClientConfiguration
} from "../types";

import { createPromise } from "../../utils";
import {
createPromise,
combineStrings,
argumentIsNotProvided,
toStringCall
} from "../../utils";

function formProtocol(protocol: string): string {
if (protocol.endsWith(":")) {
return protocol;
}

return `${protocol}:`;
}

function constructBody(body: any): Buffer {
if (argumentIsNotProvided(body)) {
return undefined;
}

if (Buffer.isBuffer(body)) {
return body;
} else if (toStringCall(body) === "ArrayBuffer") {
return Buffer.from(new Uint8Array(body));
}
}

export class NodeRequest implements UrbexRequestApi {
public send(config: InternalUrbexConfiguration): DispatchedResponse {
return createPromise(() => {});
private getAgentFromProtocol(
protocol: URLProtocol
): typeof http | typeof https {
if (protocol === "http") {
return http;
}

if (protocol === "https") {
return https;
}

throw new Error(
`Urbex expected a valid protocol to create a request agent, but got ${protocol}.`
);
}

public async send(config: ParsedClientConfiguration): DispatchedResponse {
return createPromise((resolve, reject) => {
const agent = this.getAgentFromProtocol(config.url.protocol);

const agentRequestconfig: https.RequestOptions = {
protocol: formProtocol(config.url.protocol),
hostname: config.url.hostname,
path: combineStrings(
"",
config.url.endpoint,
config.url.params as string
),
headers: config.headers.get(),
port: config.url.port
};

const req = agent.request(agentRequestconfig, (res) => {
const { statusCode } = res;

let error: Error | null = null;

if (error) {
res.resume();
reject(error);
return;
}

res.setEncoding("utf8");

let rawData = "";

res.on("data", (chunk) => {
rawData += chunk;
});

res.on("end", () => {
try {
resolve({
data: rawData,
headers: res.headers,
status: statusCode,
statusText: res.statusMessage,
request: req
});
} catch (e) {
reject(e);
}
});
});

req.on("error", (e) => {
reject(e);
});

req.end(config.data);
});
}
}

0 comments on commit 37d9da2

Please sign in to comment.