Skip to content

Commit

Permalink
pkg
Browse files Browse the repository at this point in the history
  • Loading branch information
pyramation committed May 25, 2024
1 parent c43ad2a commit 13994e9
Show file tree
Hide file tree
Showing 14 changed files with 291 additions and 6 deletions.
2 changes: 1 addition & 1 deletion __fixtures__/output/swagger-client.merged.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { APIClient } from "./api-client";
import { APIClient } from "@interweb/fetch-api-client";
export interface MutatingWebhook {
admissionReviewVersions: string[];
clientConfig: WebhookClientConfig;
Expand Down
2 changes: 1 addition & 1 deletion __fixtures__/output/swagger-client.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { APIClient } from "./api-client";
import { APIClient } from "@interweb/fetch-api-client";
/* io.k8s.api.admissionregistration.v1.MutatingWebhook */
/* MutatingWebhook describes an admission webhook and the resources and operations it applies to. */
export interface MutatingWebhook {
Expand Down
32 changes: 32 additions & 0 deletions packages/fetch-api-client/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Change Log

All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.

# [0.4.0](https://github.com/cosmology-tech/schema-typescript/compare/@interweb/node-api-client@0.3.0...@interweb/node-api-client@0.4.0) (2024-05-25)

**Note:** Version bump only for package @interweb/node-api-client





# 0.3.0 (2024-05-25)

**Note:** Version bump only for package @interweb/node-api-client





# [0.2.0](https://github.com/cosmology-tech/schema-typescript/compare/node-api-client@0.1.0...node-api-client@0.2.0) (2024-05-25)

**Note:** Version bump only for package node-api-client





# 0.1.0 (2024-05-25)

**Note:** Version bump only for package node-api-client
38 changes: 38 additions & 0 deletions packages/fetch-api-client/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# @interweb/node-api-client

<p align="center">
<img src="https://user-images.githubusercontent.com/545047/188804067-28e67e5e-0214-4449-ab04-2e0c564a6885.svg" width="80"><br />
Node.js API Client
</p>

`@interweb/node-api-client` is a lightweight and flexible HTTP client for interacting with RESTful APIs in Node.js. It supports common HTTP methods such as GET, POST, PUT, PATCH, and DELETE, with customizable options for headers, query parameters, and timeouts.

## install

```sh
npm install @interweb/node-api-client
```

## Usage

Here's an example of how to use `@interweb/node-api-client`:

```js
import { APIClient, APIClientOptions } from '@interweb/node-api-client';

const options: APIClientOptions = {
restEndpoint: 'http://localhost:8001/api'
};

const client = new APIClient(options);

// GET request
client.get('/endpoint')
.then(response => console.log(response))
.catch(error => console.error(error));

// POST request with JSON body
client.post('/endpoint', { key: 'value' })
.then(response => console.log(response))
.catch(error => console.error(error));
```
3 changes: 3 additions & 0 deletions packages/fetch-api-client/__tests__/first.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
it('works', () => {
console.log('hello test world!');
});
18 changes: 18 additions & 0 deletions packages/fetch-api-client/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
transform: {
'^.+\\.tsx?$': [
'ts-jest',
{
babelConfig: false,
tsconfig: 'tsconfig.json',
},
],
},
transformIgnorePatterns: [`/node_modules/*`],
testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$',
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
modulePathIgnorePatterns: ['dist/*'],
};
39 changes: 39 additions & 0 deletions packages/fetch-api-client/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
{
"name": "@interweb/fetch-api-client",
"version": "0.4.0",
"author": "Dan Lynch <pyramation@gmail.com>",
"description": "Node.js API Client",
"main": "index.js",
"module": "esm/index.js",
"types": "index.d.ts",
"homepage": "https://github.com/cosmology-tech/schema-typescript",
"license": "SEE LICENSE IN LICENSE",
"publishConfig": {
"access": "public",
"directory": "dist"
},
"repository": {
"type": "git",
"url": "https://github.com/cosmology-tech/schema-typescript"
},
"bugs": {
"url": "https://github.com/cosmology-tech/schema-typescript/issues"
},
"scripts": {
"copy": "copyfiles -f ../../LICENSE README.md package.json dist",
"clean": "rimraf dist/**",
"prepare": "npm run build",
"build": "npm run clean; tsc; tsc -p tsconfig.esm.json; npm run copy",
"lint": "eslint . --fix",
"test": "jest",
"test:watch": "jest --watch"
},
"keywords": [],
"gitHead": "06e20539d2cfce7522a29d7e9b20a9eb4d78fe2c",
"dependencies": {
"isomorphic-fetch": "^3.0.0"
},
"devDependencies": {
"@types/isomorphic-fetch": "^0.0.39"
}
}
117 changes: 117 additions & 0 deletions packages/fetch-api-client/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import fetch from 'isomorphic-fetch';

interface RequestOptions<Params> {
hostname: string;
path: string;
headers?: { [key: string]: string };
method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
params?: Params;
timeout?: number;
}

export interface APIClientOptions {
restEndpoint: string;
}

export class APIClient {
private baseUrl: string;
private defaultTimeout: number = 10000; // 10 seconds

constructor(options: APIClientOptions) {
this.baseUrl = options.restEndpoint;
}

private buildUrl(endpoint: string, query?: { [key: string]: any }): string {
const url = new URL(endpoint, this.baseUrl);
if (query) {
Object.keys(query).forEach(key => url.searchParams.append(key, query[key]));
}
return url.toString();
}

private async request<Resp>(options: RequestOptions<any>): Promise<Resp> {
const { path, headers, method, params, timeout } = options;
const url = this.buildUrl(path, method === 'GET' && params);
const fetchOptions: RequestInit = {
method,
headers,
body: method !== 'GET' && method !== 'DELETE' ? JSON.stringify(params) : null,
};

const controller = new AbortController();
const id = setTimeout(() => controller.abort(), timeout || this.defaultTimeout);
fetchOptions.signal = controller.signal;

const response = await fetch(url, fetchOptions);
clearTimeout(id);

if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}

return response.json() as Promise<Resp>;
}

get<Resp = unknown>(endpoint: string, query?: { [key: string]: any }, opts: { headers?: { [key: string]: string }, timeout?: number } = {}): Promise<Resp> {
return this.request<Resp>({
path: endpoint,
method: 'GET',
headers: opts.headers,
timeout: opts.timeout || this.defaultTimeout,
params: query, // Correctly use query parameters for GET
hostname: '',
});
}

post<Resp = unknown, Params = any>(endpoint: string, params: Params, opts: { headers?: { [key: string]: string }, timeout?: number } = {}): Promise<Resp> {
return this.request<Resp>({
path: endpoint,
method: 'POST',
headers: {
'Content-Type': 'application/json',
...opts.headers,
},
params,
timeout: opts.timeout || this.defaultTimeout,
hostname: '',
});
}

put<Resp = unknown, Params = any>(endpoint: string, params: Params, opts: { headers?: { [key: string]: string }, timeout?: number } = {}): Promise<Resp> {
return this.request<Resp>({
path: endpoint,
method: 'PUT',
headers: {
'Content-Type': 'application/json',
...opts.headers,
},
params,
timeout: opts.timeout || this.defaultTimeout,
hostname: '',
});
}

patch<Resp = unknown, Params = any>(endpoint: string, params: Params, opts: { headers?: { [key: string]: string }, timeout?: number } = {}): Promise<Resp> {
return this.request<Resp>({
path: endpoint,
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
...opts.headers,
},
params,
timeout: opts.timeout || this.defaultTimeout,
hostname: '',
});
}

delete<Resp = unknown>(endpoint: string, opts: { headers?: { [key: string]: string }, timeout?: number } = {}): Promise<Resp> {
return this.request<Resp>({
path: endpoint,
method: 'DELETE',
headers: opts.headers,
timeout: opts.timeout || this.defaultTimeout,
hostname: '',
});
}
}
9 changes: 9 additions & 0 deletions packages/fetch-api-client/tsconfig.esm.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "dist/esm",
"module": "es2022",
"rootDir": "src/",
"declaration": false
}
}
9 changes: 9 additions & 0 deletions packages/fetch-api-client/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"outDir": "dist",
"rootDir": "src/"
},
"include": ["src/**/*.ts"],
"exclude": ["dist", "node_modules", "**/*.spec.*", "**/*.test.*"]
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`merged 1`] = `
"import { APIClient } from "./api-client";
"import { APIClient } from "@interweb/fetch-api-client";
export interface MutatingWebhook {
admissionReviewVersions: string[];
clientConfig: WebhookClientConfig;
Expand Down Expand Up @@ -13345,7 +13345,7 @@ export class KubernetesClient extends APIClient {
`;

exports[`swagger 1`] = `
"import { APIClient } from "./api-client";
"import { APIClient } from "@interweb/fetch-api-client";
/* io.k8s.api.admissionregistration.v1.MutatingWebhook */
/* MutatingWebhook describes an admission webhook and the resources and operations it applies to. */
export interface MutatingWebhook {
Expand Down
2 changes: 1 addition & 1 deletion packages/schema-sdk/src/openapi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -607,7 +607,7 @@ export function generateOpenApiClient(
t.identifier('APIClient')
),
],
t.stringLiteral('./api-client')
t.stringLiteral(options.npmApiClient)
),
...types,
...openApiTypes,
Expand Down
2 changes: 2 additions & 0 deletions packages/schema-sdk/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { defaultSchemaTSOptions, SchemaTSOptions } from 'schema-typescript';
export interface OpenAPIOptions extends SchemaTSOptions {
clientName: string;
version?: 'v1' | 'v1beta1' | 'v2beta1' | 'v2beta2';
npmApiClient?: '@interweb/fetch-api-client' | '@interweb/node-api-client' | string;
mergedParams?: boolean;
includeSwaggerUrl?: boolean;
operationNamingStrategy?: {
Expand Down Expand Up @@ -32,6 +33,7 @@ export interface OpenAPIOptions extends SchemaTSOptions {
export const defaultSchemaSDKOptions: Partial<OpenAPIOptions> = {
...defaultSchemaTSOptions,
clientName: 'Client',
npmApiClient: '@interweb/fetch-api-client',
mergedParams: false,
includeSwaggerUrl: false,
operationNamingStrategy: {
Expand Down
20 changes: 19 additions & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1264,6 +1264,11 @@
dependencies:
"@types/node" "*"

"@types/isomorphic-fetch@^0.0.39":
version "0.0.39"
resolved "https://registry.yarnpkg.com/@types/isomorphic-fetch/-/isomorphic-fetch-0.0.39.tgz#889573a72ca637bc1a665910a41ff1cb3b52011f"
integrity sha512-I0gou/ZdA1vMG7t7gMzL7VYu2xAKU78rW9U1l10MI0nn77pEHq3tQqHQ8hMmXdMpBlkxZOorjI4sO594Z3kKJw==

"@types/istanbul-lib-coverage@*", "@types/istanbul-lib-coverage@^2.0.0", "@types/istanbul-lib-coverage@^2.0.1":
version "2.0.6"
resolved "https://registry.yarnpkg.com/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.6.tgz#7739c232a1fee9b4d3ce8985f314c0c6d33549d7"
Expand Down Expand Up @@ -3527,6 +3532,14 @@ isobject@^3.0.1:
resolved "https://registry.yarnpkg.com/isobject/-/isobject-3.0.1.tgz#4e431e92b11a9731636aa1f9c8d1ccbcfdab78df"
integrity sha512-WhB9zCku7EGTj/HQQRz5aUQEUeoQZH2bWcltRErOpymJ4boYE6wL9Tbr23krRPSZ+C5zqNSrSw+Cc7sZZ4b7vg==

isomorphic-fetch@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/isomorphic-fetch/-/isomorphic-fetch-3.0.0.tgz#0267b005049046d2421207215d45d6a262b8b8b4"
integrity sha512-qvUtwJ3j6qwsF3jLxkZ72qCgjMysPzDfeV240JHiGZsANBYd+EEuu35v7dfrJ9Up0Ak07D7GGSkGhCHTqg/5wA==
dependencies:
node-fetch "^2.6.1"
whatwg-fetch "^3.4.1"

istanbul-lib-coverage@^3.0.0, istanbul-lib-coverage@^3.2.0:
version "3.2.2"
resolved "https://registry.yarnpkg.com/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz#2d166c4b0644d43a39f04bf6c2edd1e585f31756"
Expand Down Expand Up @@ -4666,7 +4679,7 @@ node-fetch@2.6.7:
dependencies:
whatwg-url "^5.0.0"

node-fetch@^2.6.7:
node-fetch@^2.6.1, node-fetch@^2.6.7:
version "2.7.0"
resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.7.0.tgz#d0f0fa6e3e2dc1d27efcd8ad99d550bda94d187d"
integrity sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==
Expand Down Expand Up @@ -6462,6 +6475,11 @@ webidl-conversions@^3.0.0:
resolved "https://registry.yarnpkg.com/webidl-conversions/-/webidl-conversions-3.0.1.tgz#24534275e2a7bc6be7bc86611cc16ae0a5654871"
integrity sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==

whatwg-fetch@^3.4.1:
version "3.6.20"
resolved "https://registry.yarnpkg.com/whatwg-fetch/-/whatwg-fetch-3.6.20.tgz#580ce6d791facec91d37c72890995a0b48d31c70"
integrity sha512-EqhiFU6daOA8kpjOWTL0olhVOF3i7OrFzSYiGsEMB8GcXS+RrzauAERX65xMeNWVqxA6HXH2m69Z9LaKKdisfg==

whatwg-url@^5.0.0:
version "5.0.0"
resolved "https://registry.yarnpkg.com/whatwg-url/-/whatwg-url-5.0.0.tgz#966454e8765462e37644d3626f6742ce8b70965d"
Expand Down

0 comments on commit 13994e9

Please sign in to comment.