Skip to content

Commit

Permalink
Merge pull request #5 from ty-ras/issue/2-refine-code
Browse files Browse the repository at this point in the history
Issue/2 refine code
  • Loading branch information
stazz authored Sep 9, 2023
2 parents e8d6a80 + 24beab4 commit 25745e7
Show file tree
Hide file tree
Showing 9 changed files with 34 additions and 113 deletions.
6 changes: 3 additions & 3 deletions .github/workflows/build-and-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -66,14 +66,14 @@ jobs:
- '!code/*/**.md'
- name: Mark all components to be run
if: steps.changed-files-yaml.outputs.global_any_modified == 'true'
if: steps.changed-files-yaml.outputs.global_any_changed == 'true'
run: |
echo "$(find code -type d -maxdepth 1 -mindepth 1 -print0 | while IFS= read -r -d '' line; do jq -nM --arg dirname "$line" '$dirname'; done | jq -sMc)" > __output.txt
- name: Mark only affected components to be run
if: steps.changed-files-yaml.outputs.global_any_modified == 'false' && steps.changed-files-yaml.outputs.code_any_modified == 'true'
if: steps.changed-files-yaml.outputs.global_any_changed == 'false' && steps.changed-files-yaml.outputs.code_any_changed == 'true'
run: |
echo '${{ steps.changed-files-yaml.outputs.code_all_modified_files }}' > __output.txt
echo '${{ steps.changed-files-yaml.outputs.code_all_changed_files }}' > __output.txt
- name: Save job output
id: set_output
Expand Down
4 changes: 2 additions & 2 deletions code/client/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@ty-ras/client-axios",
"version": "2.0.0",
"version": "2.1.0",
"author": {
"name": "Stanislav Muhametsin",
"email": "[email protected]",
Expand Down Expand Up @@ -32,7 +32,7 @@
}
},
"dependencies": {
"@ty-ras/data-frontend": "^2.0.1"
"@ty-ras/data-frontend": "^2.1.1"
},
"peerDependencies": {
"axios": "^1.5.0"
Expand Down
9 changes: 4 additions & 5 deletions code/client/src/__test__/client.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,13 @@

import test, { type ExecutionContext } from "ava";
import getPort from "@ava/get-port";
import * as dataFE from "@ty-ras/data-frontend";
import * as http from "node:http";
import * as http2 from "node:http2";
import type * as stream from "node:stream";
import type * as net from "node:net";

import * as spec from "../client";
import * as errors from "../errors";
import * as internal from "../internal";

test("Verify that raw string variant works", async (c) => {
c.plan(2);
Expand Down Expand Up @@ -133,7 +132,7 @@ test("Test that non-2xx status code in is handled correctly", async (c) => {
await c.throwsAsync(
async () => await callback({ method: "GET", url: "/hello" }),
{
instanceOf: errors.Non2xxStatusCodeError,
instanceOf: dataFE.Non2xxStatusCodeError,
message: `Status code ${statusCode} was returned.`,
},
);
Expand Down Expand Up @@ -198,7 +197,7 @@ test("Validate that URL sanity check works", async (c) => {
});
};

await verifyURLSanity(internal.DUMMY_ORIGIN, `/${internal.DUMMY_ORIGIN}`);
await verifyURLSanity("ftp://__dummy__", `/ftp://__dummy__`);
await verifyURLSanity("http://example.com", "/http://example.com");
});

Expand Down Expand Up @@ -336,7 +335,7 @@ const getExpectedServerIncomingHeaders = (
? {}
: {
"content-length": `${Buffer.from(body, "utf8").byteLength}`,
"content-type": "application/json",
"content-type": "application/json; charset=utf-8",
}),
});

Expand Down
12 changes: 0 additions & 12 deletions code/client/src/__test__/errors.spec.ts

This file was deleted.

73 changes: 21 additions & 52 deletions code/client/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,13 @@
*/

import * as data from "@ty-ras/data";
import type * as dataFE from "@ty-ras/data-frontend";
import * as dataFE from "@ty-ras/data-frontend";
import axios, {
type CreateAxiosDefaults,
type AxiosInstance,
type AxiosRequestConfig,
AxiosHeaders,
} from "axios";
import * as errors from "./errors";
import * as internal from "./internal";

/**
* This function will create a {@link dataFE.CallHTTPEndpoint} callback using new or given Axios instance.
Expand Down Expand Up @@ -43,7 +41,7 @@ export const createCallHTTPEndpoint = (
} = await instance(await getAxiosArgs(args, processRequestConfig));

if (status < 200 || status >= 300) {
throw new errors.Non2xxStatusCodeError(status);
throw new dataFE.Non2xxStatusCodeError(status);
}

return {
Expand All @@ -52,8 +50,11 @@ export const createCallHTTPEndpoint = (
([, header]) => header !== undefined && header !== null,
),
),
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
body: (body as string).length > 0 ? JSON.parse(body, reviver) : undefined,
body:
((body as string | undefined)?.length ?? 0) > 0
? // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
JSON.parse(body, reviver)
: undefined,
};
};
};
Expand Down Expand Up @@ -133,27 +134,29 @@ const getAxiosArgs = async (
{ method, url, query, body, headers }: dataFE.HTTPInvocationArguments,
processRequestConfig: AxiosRequestConfigProcessor | undefined,
): Promise<AxiosRequestConfig> => {
const urlObject = new URL(url, internal.DUMMY_ORIGIN);
if (urlObject.origin !== internal.DUMMY_ORIGIN || urlObject.origin === url) {
// We were passed an absolute URL -> "escape" it by prepending forward slash so that Axios will always use baseURL
url = `/${url}`;
}

if (body !== undefined) {
headers = { ...(headers ?? {}), "content-type": "application/json" }; // TODO ;charset ?
headers = {
...(headers ?? {}),
"content-type": `application/json; charset=${ENCODER.encoding}`,
};
}

const requestConfig: AxiosRequestConfig = {
method,
url: ensureNoQueryOrFragment(url),
url: dataFE.ensurePathname(url),
...(headers === undefined
? {}
: {
headers: new AxiosHeaders(getOutgoingHeaders(headers)),
headers: new AxiosHeaders(dataFE.getOutgoingHeaders(headers)),
}),
...(query === undefined ? {} : { params: getURLSearchParams(query) }),
...(body === undefined ? {} : { data: JSON.stringify(body) }),
...(query === undefined
? {}
: { params: dataFE.getURLSearchParams(query) }),
...(body === undefined
? {}
: { data: new TextEncoder().encode(JSON.stringify(body)) }),
};

await processRequestConfig?.(requestConfig);
return {
...requestConfig,
Expand All @@ -164,38 +167,4 @@ const getAxiosArgs = async (
};
};

const getURLSearchParams = (query: Record<string, unknown>) =>
new URLSearchParams(
Object.entries(query)
.filter(([, value]) => value !== undefined)
.flatMap<[string, string]>(([qKey, qValue]) =>
Array.isArray(qValue)
? qValue.map<[string, string]>((value) => [qKey, `${value}`])
: [[qKey, `${qValue}`]],
),
);

const ensureNoQueryOrFragment = (path: string) =>
path.replaceAll(
/\?|#/g,
(char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`,
);

const getOutgoingHeaders = (headers: Record<string, unknown> | undefined) =>
headers === undefined
? undefined
: Object.fromEntries(
Object.entries(headers)
.filter(([, header]) => header !== undefined)
.map(
([headerName, header]) =>
[headerName, getOutgoingHeader(header)] as const,
),
);

const getOutgoingHeader = (header: unknown): string | number | Array<string> =>
typeof header === "string" || typeof header === "number"
? header
: Array.isArray(header)
? header.filter((v) => v !== undefined).map((v) => `${v}`)
: `${header}`;
const ENCODER = new TextEncoder();
26 changes: 0 additions & 26 deletions code/client/src/errors.ts

This file was deleted.

4 changes: 0 additions & 4 deletions code/client/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,3 @@
*/

export * from "./client";
export type { Non2xxStatusCodeError } from "./errors";
export { isNon2xxStatusCodeError } from "./errors";

// Don't export anything from internal.ts
5 changes: 0 additions & 5 deletions code/client/src/internal.ts

This file was deleted.

8 changes: 4 additions & 4 deletions code/client/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -402,10 +402,10 @@
resolved "https://registry.yarnpkg.com/@tsconfig/node16/-/node16-1.0.4.tgz#0b92dcc0cc1c81f6f306a381f28e31b1a56536e9"
integrity sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==

"@ty-ras/data-frontend@^2.0.1":
version "2.0.1"
resolved "https://registry.yarnpkg.com/@ty-ras/data-frontend/-/data-frontend-2.0.1.tgz#0181d5e2785b70fd0c7ad8585308bac8ad2235b3"
integrity sha512-Ff9DngCLaGcVd4OzlCQ0gMJ0Qc2A8Emv3ysZcuFiivxSwCaHiE8QCLRg7iHuiDGWZj5fPg6k9CzAJlIptGCjYQ==
"@ty-ras/data-frontend@^2.1.1":
version "2.1.1"
resolved "https://registry.yarnpkg.com/@ty-ras/data-frontend/-/data-frontend-2.1.1.tgz#0975e50eec3e04368b6e46ac42f321f21406112f"
integrity sha512-MBJYz7jxgL6sb5TkrT9PEWKSciGG71hMMid7TbGmbTBDj56ACdSXwPLlMSGYfpqoZr9IyO7+WSaI3tP9DbZnng==
dependencies:
"@ty-ras/data" "^2.1.0"

Expand Down

0 comments on commit 25745e7

Please sign in to comment.