Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ My Node.js packages

## Packages

- [`api-client`](./packages/api-client) [![npm version](https://img.shields.io/npm/v/@ffflorian/api-client.svg)](https://npmjs.com/packages/@ffflorian/api-client)
- [`auto-merge`](./packages/auto-merge) [![npm version](https://img.shields.io/npm/v/@ffflorian/auto-merge.svg)](https://npmjs.com/packages/@ffflorian/auto-merge)
- [`crates-updater`](./packages/crates-updater) [![npm version](https://img.shields.io/npm/v/crates-updater.svg)](https://npmjs.com/packages/crates-updater)
- [`double-linked-list`](./packages/double-linked-list)
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
"eslint-plugin-sort-keys-fix": "1.1.2",
"eslint-plugin-typescript-sort-keys": "3.3.0",
"eslint-plugin-unused-imports": "4.3.0",
"lerna": "9.0.0",
"lerna": "9.0.1",
"oxlint": "1.25.0",
"prettier": "3.6.2",
"rimraf": "6.1.0",
Expand Down
674 changes: 674 additions & 0 deletions packages/api-client/LICENSE

Large diffs are not rendered by default.

27 changes: 27 additions & 0 deletions packages/api-client/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# api-client [![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0) [![npm version](https://img.shields.io/npm/v/@ffflorian/api-client.svg?style=flat)](https://www.npmjs.com/package/@ffflorian/api-client)

Simple API client using fetch ([Node.js](https://nodejs.org/api/globals.html#fetch) / [Web](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API))

## Prerequisites

- [Node.js](https://nodejs.org) >= 14
- npm (preinstalled) or [yarn](https://classic.yarnpkg.com)

## Installation

ℹ️ This is a pure [ESM](https://nodejs.org/api/esm.html#introduction) module.

Run `yarn global add @ffflorian/api-client` or `npm i -g @ffflorian/api-client`.

## Usage

```ts
import {APIClient} from '@ffflorian/api-client';

const apiClient = new APIClient();
try {
const data = await apiClient.get('https://example.com');
} catch (error) {
console.error(error);
}
```
31 changes: 31 additions & 0 deletions packages/api-client/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{
"author": "Florian Imdahl <git@ffflorian.de>",
"description": "Simple API client using fetch",
"devDependencies": {
"rimraf": "6.1.0",
"typescript": "5.9.3"
},
"engines": {
"node": ">= 18.0"
},
"exports": "./dist/index.js",
"files": [
"dist"
],
"keywords": [
"cli",
"typescript"
],
"license": "GPL-3.0",
"module": "dist/index.js",
"name": "@ffflorian/api-client",
"repository": "https://github.com/ffflorian/node-packages/tree/main/packages/api-client",
"scripts": {
"build": "tsc -p tsconfig.build.json",
"clean": "rimraf dist",
"dist": "yarn clean && yarn build",
"test": "exit 0"
},
"type": "module",
"version": "2.0.0"
}
150 changes: 150 additions & 0 deletions packages/api-client/src/APIClient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
import type {
APIResponse,
BasicRequestOptions,
ApiClientConfig,
RequestInterceptor,
ResponseInterceptor,
RequestInitWithMethod,
RequestOptions,
} from './types.js';

export class APIClient {
public interceptors: {request: RequestInterceptor[]; response: ResponseInterceptor[]} = {
request: [],
response: [],
};

constructor(
private baseUrl: string,
private config?: ApiClientConfig
) {}

setBaseURL(baseUrl: string): void {
this.baseUrl = baseUrl;
}

setConfig(config: Partial<RequestInit>): void {
this.config = config;
}

private formatData(response: Response, options?: BasicRequestOptions): Promise<any> {
const responseType = options?.responseType || 'json';
switch (responseType) {
case 'arraybuffer':
return response.arrayBuffer();
case 'blob':
return response.blob();
case 'text':
return response.text();
case 'json':
default:
return response.json();
}
}

async request(endpoint: string, options: RequestOptions): Promise<Response> {
const url = new URL(endpoint, this.baseUrl);

if (options.params) {
for (const [key, param] of Object.entries(options.params)) {
if (param !== null && param !== undefined) {
url.searchParams.append(key, String(param));
}
}
}

let requestOptions: RequestInitWithMethod = {
method: options.method.toUpperCase(),
...this.config,
};

if (options.headers) {
requestOptions.headers = {
...requestOptions.headers,
...options.headers,
};
}

if (this.config?.auth) {
const {username, password} = this.config.auth;
const encoded = btoa(`${username}:${password}`);

requestOptions.headers = {
...requestOptions.headers,
Authorization: `Basic ${encoded}`,
};
}

if (options.data) {
if (options.data instanceof Object) {
requestOptions.headers = {
...requestOptions.headers,
'Content-Type': 'application/json',
};
options.data = JSON.stringify(options.data);
}
requestOptions.body = options.data;
}

if (this.interceptors.request.length > 0) {
for (const interceptor of this.interceptors.request) {
requestOptions = await interceptor(url, requestOptions);
}
}

const response = await fetch(url, requestOptions);
if (!response.ok) {
throw new Error(`${options.method.toUpperCase()} request failed: ${response.statusText}`);
}

if (this.interceptors.response.length > 0) {
for (const interceptor of this.interceptors.response) {
await interceptor(response);
}
}

return response;
}

async delete<T = any>(endpoint: string, options?: BasicRequestOptions): Promise<APIResponse<T>> {
const request = await this.request(endpoint, {...options, method: 'DELETE'});
const requestData = await this.formatData(request, options);
return {data: requestData, headers: request.headers, status: request.status};
}

async get<T = any>(endpoint: string, options?: BasicRequestOptions): Promise<APIResponse<T>> {
const request = await this.request(endpoint, {...options, method: 'GET'});
const requestData = await this.formatData(request, options);
return {data: requestData, headers: request.headers, status: request.status};
}

async head<T = any>(endpoint: string, options?: BasicRequestOptions): Promise<APIResponse<T>> {
const request = await this.request(endpoint, {...options, method: 'HEAD'});
const requestData = await this.formatData(request, options);
return {data: requestData, headers: request.headers, status: request.status};
}

async patch<T = any>(endpoint: string, data?: any, options?: BasicRequestOptions): Promise<APIResponse<T>> {
const request = await this.request(endpoint, {...options, data, method: 'PATCH'});
const requestData = await this.formatData(request, options);
return {data: requestData, headers: request.headers, status: request.status};
}

async options<T = any>(endpoint: string, options?: BasicRequestOptions): Promise<APIResponse<T>> {
const request = await this.request(endpoint, {...options, method: 'OPTIONS'});
const requestData = await this.formatData(request, options);
return {data: requestData, headers: request.headers, status: request.status};
}

async post<T = any>(endpoint: string, data?: any, options?: BasicRequestOptions): Promise<APIResponse<T>> {
const request = await this.request(endpoint, {data, ...options, method: 'POST'});
const requestData = await this.formatData(request, options);
return {data: requestData, headers: request.headers, status: request.status};
}

async put<T = any>(endpoint: string, data?: any, options?: BasicRequestOptions): Promise<APIResponse<T>> {
const request = await this.request(endpoint, {data, ...options, method: 'PUT'});
const requestData = await this.formatData(request, options);
return {data: requestData, headers: request.headers, status: request.status};
}
}
2 changes: 2 additions & 0 deletions packages/api-client/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './APIClient.js';
export * from './types.js';
40 changes: 40 additions & 0 deletions packages/api-client/src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
export interface RequestOptions {
data?: any;
headers?: HeadersInit;
method:
| 'GET'
| 'POST'
| 'PUT'
| 'DELETE'
| 'PATCH'
| 'HEAD'
| 'OPTIONS'
| 'get'
| 'post'
| 'put'
| 'delete'
| 'patch'
| 'head'
| 'options';
params?: object;
responseType?: 'arraybuffer' | 'json' | 'text' | 'blob';
}

export type ApiClientConfig = Partial<Omit<RequestInit, 'method'>> & {auth?: {password: string; username: string}};

export type BasicRequestOptions = Omit<RequestOptions, 'method'>;

export type RequestInitWithMethod = Required<Pick<RequestInit, 'method'>> & Omit<RequestInit, 'method'>;

export type RequestInterceptor = (
url: URL,
options: RequestInitWithMethod
) => RequestInitWithMethod | Promise<RequestInitWithMethod>;

export type ResponseInterceptor = (response: Response) => void | Promise<void>;

export interface APIResponse<T> {
data: T;
headers: Headers;
status: number;
}
4 changes: 4 additions & 0 deletions packages/api-client/tsconfig.build.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"exclude": ["dist", "node_modules", "**/*.test.ts"],
"extends": "./tsconfig.json"
}
12 changes: 12 additions & 0 deletions packages/api-client/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"compilerOptions": {
"esModuleInterop": true,
"module": "NodeNext",
"moduleResolution": "NodeNext",
"outDir": "dist",
"rootDir": "src",
"target": "ES2018"
},
"exclude": ["dist", "node_modules"],
"extends": "../../tsconfig.json"
}
Loading