Skip to content

Commit

Permalink
feat(types): only necessary types are exported
Browse files Browse the repository at this point in the history
  • Loading branch information
Michael committed Nov 18, 2022
1 parent a2ba671 commit 9d2c67a
Show file tree
Hide file tree
Showing 14 changed files with 447 additions and 537 deletions.
5 changes: 2 additions & 3 deletions lib/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,8 @@ export const PROTOCOL_REGEXP = /^([a-z0-9]+):\/\//i;
export const HOSTNAME_REGEXP = /^(?:https?:\/\/)?(?:[^@\/\n]+@)?([^:\/\n]+)/i;
export const PORT_REGEXP = /:(\d{2,5})$/;

export const URL_REGEXP = new RegExp(
/^(https?:\/\/)?((([a-z\d]([a-z\d-]*[a-z\d])*)\.)+[a-z]{2,}|((\d{1,3}\.){3}\d{1,3}))(:\d+)?(\/[-a-z\d%_.~+]*)*(\?[;&a-z\d%_.~+=-]*)?(\#[-a-z\d_]*)?$/i
);
export const URL_REGEXP =
/^(https?:\/\/)?((([a-z\d]([a-z\d-]*[a-z\d])*)\.)+[a-z]{2,}|((\d{1,3}\.){3}\d{1,3}))(:\d+)?(\/[-a-z\d%_.~+]*)*(\?[;&a-z\d%_.~+=-]*)?(\#[-a-z\d_]*)?$/i;

export const URI_TEMPLATE_REGEXP_LEFT = "[{][^{{]*\\b";
export const URI_TEMPLATE_REGEXP_RIGHT = "\\b[^{}]*[}]";
Expand Down
127 changes: 50 additions & 77 deletions lib/core/api/http.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,11 @@
import { InternalConfiguration } from "../../exportable-types";
import type { DispatchedResponse, UrbexRequestApi } from "../../types";

import http from "http";
import https from "https";
import url from "url";

import type {
DispatchedResponse,
UrbexRequestApi,
URLProtocol,
ParsedClientConfiguration
} from "../types";

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

function formProtocol(protocol: string): string {
if (protocol.endsWith(":")) {
Expand All @@ -37,77 +28,59 @@ function constructBody(body: any): Buffer {
}

export class NodeRequest implements UrbexRequestApi {
private getAgentFromProtocol(
protocol: URLProtocol
): typeof http | typeof https {
if (protocol === "http") {
return http;
}

private getAgentFromProtocol(protocol: string): typeof http | typeof https {
if (protocol === "https") {
return https;
}

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

public async send(config: ParsedClientConfiguration): DispatchedResponse {
public async send(config: InternalConfiguration): 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);
// 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);
});
}
}
39 changes: 22 additions & 17 deletions lib/core/api/request-api.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,41 @@
import { CacheClock } from "cache-clock";

import type { UrbexContext } from "../../environment";
import type {
DispatchedResponse,
ParsedClientConfiguration,
UrbexRequestApi
} from "../types";
import type { InternalConfiguration } from "../../exportable-types";
import type { DispatchedResponse, UrbexRequestApi } from "../../types";

import { NodeRequest } from "./http";
import { BrowserRequest } from "./xhr";
import { environment } from "../../environment";
import { UrbexHeaders } from "../headers";
import {
createPromise,
replaceObjectProperty,
isEmpty,
isObject,
merge
} from "../../utils";
import { createPromise, replaceObjectProperty, isEmpty, isObject, merge } from "../../utils";
import { convertURIComponentToString } from "../url";

// here all of the interceptors are checked
// cache clocks are checked here
// the response is created here

export class RequestApi {
protected $api: UrbexRequestApi = null;
/**
* The internal api that is used to send requests.
*/
protected $api: UrbexRequestApi;
/**
* An isolated cache module that is used to cache requests.
*/
protected $cache: CacheClock;

constructor() {
this.register(environment.context);

this.$cache = new CacheClock({
autoStart: false,
debug: false
});
}

private register(context: UrbexContext) {
if (context === "browser" && typeof XMLHttpRequest !== "undefined") {
if (context === "browser") {
this.$api = new BrowserRequest();
return;
}
Expand All @@ -45,9 +50,9 @@ export class RequestApi {
);
}

protected async dispatchRequest(
config: ParsedClientConfiguration
): DispatchedResponse {
protected async dispatchRequest(config: InternalConfiguration): DispatchedResponse {
console.log(config);

return this.$api.send(config);
}
}
9 changes: 3 additions & 6 deletions lib/core/api/xhr.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
import type {
DispatchedResponse,
UrbexRequestApi,
ParsedClientConfiguration
} from "../types";
import type { InternalConfiguration } from "../../exportable-types";
import type { DispatchedResponse, UrbexRequestApi } from "../../types";

import { createPromise } from "../../utils";

export class BrowserRequest implements UrbexRequestApi {
public send(config: ParsedClientConfiguration): DispatchedResponse {
public send(config: InternalConfiguration): DispatchedResponse {
return createPromise(() => {});
}
}
5 changes: 3 additions & 2 deletions lib/core/constants.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { ParsedClientConfiguration, URIComponent, PipelineExecutorsManager } from "./types";
import type { InternalConfiguration, URIComponent } from "../exportable-types";
import type { PipelineExecutorsManager } from "../types";

import { merge } from "../utils";

Expand All @@ -22,7 +23,7 @@ export const DEFAULT_PIPELINE_EXECUTORS: PipelineExecutorsManager = {
response: []
};

export const DEFAULT_CLIENT_OPTIONS: ParsedClientConfiguration = {
export const DEFAULT_CLIENT_OPTIONS: InternalConfiguration = {
url: merge(DEFAULT_URI_COMPONENT, {
protocol: "http",
urlMount: "/api"
Expand Down
37 changes: 10 additions & 27 deletions lib/core/headers.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type { Headers, HeaderValues, NormalizedHeaders } from "../types";

import {
isArray,
isObject,
Expand All @@ -13,14 +15,6 @@ import { debug } from "../debug";
import { environment } from "../environment";
import { DEFAULT_HEADERS } from "./constants";

// refactor types at a later date
type UrbexHeaderValues = string | number | boolean | null | undefined;
type ObjectHeaders = Record<string, UrbexHeaderValues>;
type NormalizedHeaders = Record<string, string>;
type ArrayHeaders = Array<[string, UrbexHeaderValues]>;

export type BaseUrbexHeaders = ObjectHeaders;

function parseHeaderKey(key: string): string {
if (key) {
return formatHeaderKey(key.toLowerCase()).trim();
Expand All @@ -29,7 +23,7 @@ function parseHeaderKey(key: string): string {
return undefined;
}

function parseHeaderValue(value: UrbexHeaderValues): string {
function parseHeaderValue(value: HeaderValues): string {
if (isUndefined(value) || value === false || value === null) {
return undefined;
}
Expand All @@ -45,7 +39,7 @@ function parseHeaderValue(value: UrbexHeaderValues): string {
return String(value);
}

function normalizeHeaders(headers: BaseUrbexHeaders): NormalizedHeaders {
function normalizeHeaders(headers: Headers): NormalizedHeaders {
const newHeaders: NormalizedHeaders = {};

forEach(headers, (key, value) => {
Expand All @@ -71,7 +65,7 @@ function formatHeaderKey(key: string): string {
export class UrbexHeaders {
protected $headers: NormalizedHeaders = {};

constructor(headers?: BaseUrbexHeaders, withDefaults: boolean = true) {
constructor(headers?: Headers, withDefaults: boolean = true) {
if (withDefaults) {
if (environment.isNode) {
this.set(
Expand All @@ -89,10 +83,7 @@ export class UrbexHeaders {
}
}

static construct(
headers: BaseUrbexHeaders = {},
withDefaults: boolean = true
): UrbexHeaders {
static construct(headers: Headers = {}, withDefaults: boolean = true): UrbexHeaders {
return new UrbexHeaders(headers, withDefaults);
}

Expand All @@ -110,22 +101,14 @@ export class UrbexHeaders {
* @param headers The headers to set
* @param forceMerge Whether to merge the headers with the existing configuration
*/
public set(
headers?: BaseUrbexHeaders,
forceMerge: boolean = true
): BaseUrbexHeaders {
public set(headers?: Headers, forceMerge: boolean = true): Headers {
if (!isObject(headers)) {
debug(
"error",
`Attempted to set headers with a non-object value: ${typeof headers}`
);
debug("error", `Attempted to set headers with a non-object value: ${typeof headers}`);
return headers;
}

const normalizedHeaders = this.normalize(headers);
const merged = forceMerge
? merge(this.$headers, normalizedHeaders)
: normalizedHeaders;
const merged = forceMerge ? merge(this.$headers, normalizedHeaders) : normalizedHeaders;

return (this.$headers = merged);
}
Expand Down Expand Up @@ -171,7 +154,7 @@ export class UrbexHeaders {
* Normalize an incoming headers object
*/

public normalize(headers: BaseUrbexHeaders): NormalizedHeaders {
public normalize(headers: Headers): NormalizedHeaders {
if (argumentIsNotProvided(headers) || !isObject(headers)) {
return {};
}
Expand Down
Loading

0 comments on commit 9d2c67a

Please sign in to comment.