@constructive-io/fetch-api-client 0.7.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Constructive <developers@constructive.io>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,88 @@
1
+ # @constructive-io/fetch-api-client
2
+
3
+ <p align="center">
4
+ <img src="https://raw.githubusercontent.com/constructive-io/constructive/refs/heads/main/assets/outline-logo.svg" height="250"><br />
5
+ Fetch API Client
6
+ <br />
7
+ <a href="https://github.com/constructive-io/dev-utils/actions/workflows/ci.yml">
8
+ <img height="20" src="https://github.com/constructive-io/dev-utils/actions/workflows/ci.yml/badge.svg" />
9
+ </a>
10
+ <a href="https://github.com/constructive-io/dev-utils/blob/main/LICENSE">
11
+ <img height="20" src="https://img.shields.io/badge/license-MIT-blue.svg"/>
12
+ </a>
13
+ </p>
14
+
15
+ `@constructive-io/fetch-api-client` is a lightweight and flexible HTTP client for interacting with RESTful APIs in Node.js or the Browser. It supports common HTTP methods such as GET, POST, PUT, PATCH, and DELETE, with customizable options for headers, query parameters, and timeouts.
16
+
17
+ ## install
18
+
19
+ ```sh
20
+ npm install @constructive-io/fetch-api-client
21
+ ```
22
+
23
+ ## Usage
24
+
25
+ Here's an example of how to use `@constructive-io/fetch-api-client`:
26
+
27
+ ```js
28
+ import { APIClient, APIClientOptions } from '@constructive-io/fetch-api-client';
29
+
30
+ const options: APIClientOptions = {
31
+ restEndpoint: 'http://localhost:8001/api'
32
+ };
33
+
34
+ const client = new APIClient(options);
35
+
36
+ // GET request
37
+ client.get('/endpoint')
38
+ .then(response => console.log(response))
39
+ .catch(error => console.error(error));
40
+
41
+ // GET request with query params
42
+ client.get('/endpoint', { search: 'value' })
43
+ .then(response => console.log(response))
44
+ .catch(error => console.error(error));
45
+
46
+ // POST request with JSON body
47
+ client.post('/endpoint', null, { key: 'value' })
48
+ .then(response => console.log(response))
49
+ .catch(error => console.error(error));
50
+ ```
51
+
52
+ ---
53
+
54
+ ## Development
55
+
56
+ ### Setup
57
+
58
+ 1. Clone the repository:
59
+
60
+ ```bash
61
+ git clone https://github.com/constructive-io/dev-utils.git
62
+ ```
63
+
64
+ 2. Install dependencies:
65
+
66
+ ```bash
67
+ cd dev-utils
68
+ pnpm install
69
+ pnpm build
70
+ ```
71
+
72
+ 3. Test the package of interest:
73
+
74
+ ```bash
75
+ cd packages/<packagename>
76
+ pnpm test:watch
77
+ ```
78
+
79
+ ## Credits
80
+
81
+ Built for developers, with developers.
82
+ 👉 https://launchql.com | https://hyperweb.io
83
+
84
+ ## Disclaimer
85
+
86
+ AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
87
+
88
+ No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
package/esm/index.js ADDED
@@ -0,0 +1,126 @@
1
+ import { createHTTPError } from '@constructive-io/http-errors';
2
+ import { URLSearchParams } from 'url';
3
+ export class NotFoundError extends Error {
4
+ }
5
+ export class UnauthorizedError extends Error {
6
+ }
7
+ export class InternalServerError extends Error {
8
+ }
9
+ export class APIClient {
10
+ baseUrl;
11
+ defaultTimeout = 10000; // 10 seconds
12
+ constructor(options) {
13
+ this.baseUrl = options.restEndpoint;
14
+ }
15
+ buildFullPath(endpoint, query) {
16
+ const url = new URL(endpoint, this.baseUrl);
17
+ if (query) {
18
+ Object.keys(query).forEach(key => url.searchParams.append(key, query[key]));
19
+ }
20
+ return url.toString();
21
+ }
22
+ async request(options) {
23
+ const { path, headers, method, params, timeout } = options;
24
+ const url = this.buildFullPath(path, method === 'GET' ? params : undefined);
25
+ const controller = new AbortController();
26
+ const id = setTimeout(() => controller.abort(), timeout || this.defaultTimeout);
27
+ const fetchOptions = {
28
+ method,
29
+ headers,
30
+ signal: controller.signal,
31
+ body: method !== 'GET' && method !== 'DELETE' ? JSON.stringify(params) : null,
32
+ };
33
+ try {
34
+ const response = await fetch(url, fetchOptions);
35
+ clearTimeout(id);
36
+ if (!response.ok) {
37
+ // Use the factory function to create an error based on the status code
38
+ throw createHTTPError(response.status);
39
+ }
40
+ return response.json();
41
+ }
42
+ catch (error) {
43
+ clearTimeout(id);
44
+ throw error;
45
+ }
46
+ }
47
+ get(endpoint, query, body, opts = {}) {
48
+ return this.request({
49
+ path: endpoint,
50
+ method: 'GET',
51
+ // @ts-ignore
52
+ headers: opts.headers,
53
+ timeout: opts.timeout || this.defaultTimeout,
54
+ params: query,
55
+ });
56
+ }
57
+ post(endpoint, query, body, opts = {}) {
58
+ const headers = opts.isFormData
59
+ ? {
60
+ 'Content-Type': 'application/x-www-form-urlencoded',
61
+ ...opts.headers,
62
+ }
63
+ : {
64
+ 'Content-Type': 'application/json',
65
+ ...opts.headers,
66
+ };
67
+ const bodyContent = opts.isFormData
68
+ ? new URLSearchParams(body).toString()
69
+ : JSON.stringify(body);
70
+ return this.request({
71
+ path: endpoint,
72
+ method: 'POST',
73
+ // @ts-ignore
74
+ headers,
75
+ timeout: opts.timeout || this.defaultTimeout,
76
+ params: bodyContent,
77
+ });
78
+ }
79
+ patch(endpoint, query, body, opts = {}) {
80
+ const headers = opts.isFormData
81
+ ? {
82
+ 'Content-Type': 'application/x-www-form-urlencoded',
83
+ ...opts.headers,
84
+ }
85
+ : {
86
+ 'Content-Type': 'application/json',
87
+ ...opts.headers,
88
+ };
89
+ const bodyContent = opts.isFormData
90
+ ? new URLSearchParams(body).toString()
91
+ : JSON.stringify(body);
92
+ return this.request({
93
+ path: endpoint,
94
+ method: 'PATCH',
95
+ // @ts-ignore
96
+ headers,
97
+ timeout: opts.timeout || this.defaultTimeout,
98
+ params: bodyContent,
99
+ });
100
+ }
101
+ put(endpoint, query, body, opts = {}) {
102
+ const headers = {
103
+ 'Content-Type': 'application/json',
104
+ ...opts.headers,
105
+ };
106
+ const bodyContent = JSON.stringify(body);
107
+ return this.request({
108
+ path: endpoint,
109
+ method: 'PUT',
110
+ // @ts-ignore
111
+ headers,
112
+ timeout: opts.timeout || this.defaultTimeout,
113
+ params: bodyContent,
114
+ });
115
+ }
116
+ delete(endpoint, query, body, opts = {}) {
117
+ return this.request({
118
+ path: endpoint,
119
+ method: 'DELETE',
120
+ // @ts-ignore
121
+ headers: opts.headers,
122
+ timeout: opts.timeout || this.defaultTimeout,
123
+ params: query,
124
+ });
125
+ }
126
+ }
package/index.d.ts ADDED
@@ -0,0 +1,117 @@
1
+ export declare class NotFoundError extends Error {
2
+ }
3
+ export declare class UnauthorizedError extends Error {
4
+ }
5
+ export declare class InternalServerError extends Error {
6
+ }
7
+ export interface APIClientOptions {
8
+ restEndpoint: string;
9
+ }
10
+ export interface APIClientRequestHeaders {
11
+ accept?: string | string[] | undefined;
12
+ 'accept-charset'?: string | string[] | undefined;
13
+ 'accept-encoding'?: string | string[] | undefined;
14
+ 'accept-language'?: string | string[] | undefined;
15
+ 'accept-ranges'?: string | undefined;
16
+ 'access-control-allow-credentials'?: string | undefined;
17
+ 'access-control-allow-headers'?: string | undefined;
18
+ 'access-control-allow-methods'?: string | undefined;
19
+ 'access-control-allow-origin'?: string | undefined;
20
+ 'access-control-expose-headers'?: string | undefined;
21
+ 'access-control-max-age'?: string | undefined;
22
+ 'access-control-request-headers'?: string | undefined;
23
+ 'access-control-request-method'?: string | undefined;
24
+ age?: string | undefined;
25
+ allow?: string | undefined;
26
+ authorization?: string | undefined;
27
+ 'cache-control'?: string | undefined;
28
+ 'cdn-cache-control'?: string | undefined;
29
+ connection?: string | string[] | undefined;
30
+ 'content-disposition'?: string | undefined;
31
+ 'content-encoding'?: string | undefined;
32
+ 'content-language'?: string | undefined;
33
+ 'content-length'?: string | number | undefined;
34
+ 'content-location'?: string | undefined;
35
+ 'content-range'?: string | undefined;
36
+ 'content-security-policy'?: string | undefined;
37
+ 'content-security-policy-report-only'?: string | undefined;
38
+ cookie?: string | string[] | undefined;
39
+ dav?: string | string[] | undefined;
40
+ dnt?: string | undefined;
41
+ date?: string | undefined;
42
+ etag?: string | undefined;
43
+ expect?: string | undefined;
44
+ expires?: string | undefined;
45
+ forwarded?: string | undefined;
46
+ from?: string | undefined;
47
+ host?: string | undefined;
48
+ 'if-match'?: string | undefined;
49
+ 'if-modified-since'?: string | undefined;
50
+ 'if-none-match'?: string | undefined;
51
+ 'if-range'?: string | undefined;
52
+ 'if-unmodified-since'?: string | undefined;
53
+ 'last-modified'?: string | undefined;
54
+ link?: string | string[] | undefined;
55
+ location?: string | undefined;
56
+ 'max-forwards'?: string | undefined;
57
+ origin?: string | undefined;
58
+ prgama?: string | string[] | undefined;
59
+ 'proxy-authenticate'?: string | string[] | undefined;
60
+ 'proxy-authorization'?: string | undefined;
61
+ 'public-key-pins'?: string | undefined;
62
+ 'public-key-pins-report-only'?: string | undefined;
63
+ range?: string | undefined;
64
+ referer?: string | undefined;
65
+ 'referrer-policy'?: string | undefined;
66
+ refresh?: string | undefined;
67
+ 'retry-after'?: string | undefined;
68
+ 'sec-websocket-accept'?: string | undefined;
69
+ 'sec-websocket-extensions'?: string | string[] | undefined;
70
+ 'sec-websocket-key'?: string | undefined;
71
+ 'sec-websocket-protocol'?: string | string[] | undefined;
72
+ 'sec-websocket-version'?: string | undefined;
73
+ server?: string | undefined;
74
+ 'set-cookie'?: string | string[] | undefined;
75
+ 'strict-transport-security'?: string | undefined;
76
+ te?: string | undefined;
77
+ trailer?: string | undefined;
78
+ 'transfer-encoding'?: string | undefined;
79
+ 'user-agent'?: string | undefined;
80
+ upgrade?: string | undefined;
81
+ 'upgrade-insecure-requests'?: string | undefined;
82
+ vary?: string | undefined;
83
+ via?: string | string[] | undefined;
84
+ warning?: string | undefined;
85
+ 'www-authenticate'?: string | string[] | undefined;
86
+ 'x-content-type-options'?: string | undefined;
87
+ 'x-dns-prefetch-control'?: string | undefined;
88
+ 'x-frame-options'?: string | undefined;
89
+ 'x-xss-protection'?: string | undefined;
90
+ }
91
+ export type APIClientRequestOpts = {
92
+ headers?: APIClientRequestHeaders;
93
+ timeout?: number;
94
+ isFormData?: boolean;
95
+ };
96
+ export declare class APIClient {
97
+ private baseUrl;
98
+ private defaultTimeout;
99
+ constructor(options: APIClientOptions);
100
+ private buildFullPath;
101
+ private request;
102
+ get<Resp = unknown>(endpoint: string, query?: {
103
+ [key: string]: any;
104
+ }, body?: void, opts?: APIClientRequestOpts): Promise<Resp>;
105
+ post<Resp = unknown, Params = any>(endpoint: string, query?: {
106
+ [key: string]: any;
107
+ }, body?: Params, opts?: APIClientRequestOpts): Promise<Resp>;
108
+ patch<Resp = unknown, Params = any>(endpoint: string, query?: {
109
+ [key: string]: any;
110
+ }, body?: Params, opts?: APIClientRequestOpts): Promise<Resp>;
111
+ put<Resp = unknown, Params = any>(endpoint: string, query?: {
112
+ [key: string]: any;
113
+ }, body?: Params, opts?: APIClientRequestOpts): Promise<Resp>;
114
+ delete<Resp = unknown>(endpoint: string, query?: {
115
+ [key: string]: any;
116
+ }, body?: void, opts?: APIClientRequestOpts): Promise<Resp>;
117
+ }
package/index.js ADDED
@@ -0,0 +1,133 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.APIClient = exports.InternalServerError = exports.UnauthorizedError = exports.NotFoundError = void 0;
4
+ const http_errors_1 = require("@constructive-io/http-errors");
5
+ const url_1 = require("url");
6
+ class NotFoundError extends Error {
7
+ }
8
+ exports.NotFoundError = NotFoundError;
9
+ class UnauthorizedError extends Error {
10
+ }
11
+ exports.UnauthorizedError = UnauthorizedError;
12
+ class InternalServerError extends Error {
13
+ }
14
+ exports.InternalServerError = InternalServerError;
15
+ class APIClient {
16
+ baseUrl;
17
+ defaultTimeout = 10000; // 10 seconds
18
+ constructor(options) {
19
+ this.baseUrl = options.restEndpoint;
20
+ }
21
+ buildFullPath(endpoint, query) {
22
+ const url = new URL(endpoint, this.baseUrl);
23
+ if (query) {
24
+ Object.keys(query).forEach(key => url.searchParams.append(key, query[key]));
25
+ }
26
+ return url.toString();
27
+ }
28
+ async request(options) {
29
+ const { path, headers, method, params, timeout } = options;
30
+ const url = this.buildFullPath(path, method === 'GET' ? params : undefined);
31
+ const controller = new AbortController();
32
+ const id = setTimeout(() => controller.abort(), timeout || this.defaultTimeout);
33
+ const fetchOptions = {
34
+ method,
35
+ headers,
36
+ signal: controller.signal,
37
+ body: method !== 'GET' && method !== 'DELETE' ? JSON.stringify(params) : null,
38
+ };
39
+ try {
40
+ const response = await fetch(url, fetchOptions);
41
+ clearTimeout(id);
42
+ if (!response.ok) {
43
+ // Use the factory function to create an error based on the status code
44
+ throw (0, http_errors_1.createHTTPError)(response.status);
45
+ }
46
+ return response.json();
47
+ }
48
+ catch (error) {
49
+ clearTimeout(id);
50
+ throw error;
51
+ }
52
+ }
53
+ get(endpoint, query, body, opts = {}) {
54
+ return this.request({
55
+ path: endpoint,
56
+ method: 'GET',
57
+ // @ts-ignore
58
+ headers: opts.headers,
59
+ timeout: opts.timeout || this.defaultTimeout,
60
+ params: query,
61
+ });
62
+ }
63
+ post(endpoint, query, body, opts = {}) {
64
+ const headers = opts.isFormData
65
+ ? {
66
+ 'Content-Type': 'application/x-www-form-urlencoded',
67
+ ...opts.headers,
68
+ }
69
+ : {
70
+ 'Content-Type': 'application/json',
71
+ ...opts.headers,
72
+ };
73
+ const bodyContent = opts.isFormData
74
+ ? new url_1.URLSearchParams(body).toString()
75
+ : JSON.stringify(body);
76
+ return this.request({
77
+ path: endpoint,
78
+ method: 'POST',
79
+ // @ts-ignore
80
+ headers,
81
+ timeout: opts.timeout || this.defaultTimeout,
82
+ params: bodyContent,
83
+ });
84
+ }
85
+ patch(endpoint, query, body, opts = {}) {
86
+ const headers = opts.isFormData
87
+ ? {
88
+ 'Content-Type': 'application/x-www-form-urlencoded',
89
+ ...opts.headers,
90
+ }
91
+ : {
92
+ 'Content-Type': 'application/json',
93
+ ...opts.headers,
94
+ };
95
+ const bodyContent = opts.isFormData
96
+ ? new url_1.URLSearchParams(body).toString()
97
+ : JSON.stringify(body);
98
+ return this.request({
99
+ path: endpoint,
100
+ method: 'PATCH',
101
+ // @ts-ignore
102
+ headers,
103
+ timeout: opts.timeout || this.defaultTimeout,
104
+ params: bodyContent,
105
+ });
106
+ }
107
+ put(endpoint, query, body, opts = {}) {
108
+ const headers = {
109
+ 'Content-Type': 'application/json',
110
+ ...opts.headers,
111
+ };
112
+ const bodyContent = JSON.stringify(body);
113
+ return this.request({
114
+ path: endpoint,
115
+ method: 'PUT',
116
+ // @ts-ignore
117
+ headers,
118
+ timeout: opts.timeout || this.defaultTimeout,
119
+ params: bodyContent,
120
+ });
121
+ }
122
+ delete(endpoint, query, body, opts = {}) {
123
+ return this.request({
124
+ path: endpoint,
125
+ method: 'DELETE',
126
+ // @ts-ignore
127
+ headers: opts.headers,
128
+ timeout: opts.timeout || this.defaultTimeout,
129
+ params: query,
130
+ });
131
+ }
132
+ }
133
+ exports.APIClient = APIClient;
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@constructive-io/fetch-api-client",
3
+ "version": "0.7.12",
4
+ "author": "Constructive <developers@constructive.io>",
5
+ "description": "Universal Fetch-based HTTP client for Node.js and browsers",
6
+ "main": "index.js",
7
+ "module": "esm/index.js",
8
+ "types": "index.d.ts",
9
+ "homepage": "https://github.com/constructive-io/dev-utils",
10
+ "license": "MIT",
11
+ "publishConfig": {
12
+ "access": "public",
13
+ "directory": "dist"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "https://github.com/constructive-io/dev-utils"
18
+ },
19
+ "bugs": {
20
+ "url": "https://github.com/constructive-io/dev-utils/issues"
21
+ },
22
+ "scripts": {
23
+ "copy": "makage assets",
24
+ "clean": "makage clean",
25
+ "prepublishOnly": "npm run build",
26
+ "build": "makage build",
27
+ "lint": "eslint . --fix",
28
+ "test": "jest",
29
+ "test:watch": "jest --watch"
30
+ },
31
+ "keywords": [],
32
+ "dependencies": {
33
+ "@constructive-io/http-errors": "0.2.12",
34
+ "isomorphic-fetch": "^3.0.0"
35
+ },
36
+ "devDependencies": {
37
+ "@types/isomorphic-fetch": "^0.0.39",
38
+ "makage": "0.1.8"
39
+ },
40
+ "gitHead": "c5a1d1d1440805103acfb584c4c97c78eeaa50e9"
41
+ }