@slango/ristretto 1.0.52 → 1.0.54

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.
@@ -1,65 +0,0 @@
1
- import {
2
- Middleware,
3
- MiddlewareNext,
4
- PostResponseMiddlewareContext,
5
- PreRequestMiddlewareContext,
6
- } from './index.js';
7
-
8
- export type PostResponseMiddleWare = Middleware<PostResponseMiddlewareContext>;
9
- export type PreRequestMiddleWare = Middleware<PreRequestMiddlewareContext>;
10
-
11
- const preRequestMiddlewares: PreRequestMiddleWare[] = [];
12
- const postResponseMiddlewares: PostResponseMiddleWare[] = [];
13
-
14
- export const addPreRequestMiddleware = (middleware: PreRequestMiddleWare) => {
15
- preRequestMiddlewares.push(middleware);
16
- };
17
-
18
- export const addPostResponseMiddleware = (middleware: PostResponseMiddleWare) => {
19
- postResponseMiddlewares.push(middleware);
20
- };
21
-
22
- export const removePreRequestMiddleware = (middleware: PreRequestMiddleWare) => {
23
- const index = preRequestMiddlewares.findIndex((m) => m === middleware);
24
- if (index !== -1) preRequestMiddlewares.splice(index, 1);
25
- };
26
-
27
- export const removePostResponseMiddleware = (middleware: PostResponseMiddleWare) => {
28
- const index = postResponseMiddlewares.findIndex((m) => m === middleware);
29
- if (index !== -1) postResponseMiddlewares.splice(index, 1);
30
- };
31
-
32
- export const clearPreRequestMiddlewares = () => {
33
- preRequestMiddlewares.length = 0;
34
- };
35
-
36
- export const clearPostResponseMiddlewares = () => {
37
- postResponseMiddlewares.length = 0;
38
- };
39
-
40
- const runMiddlewares = <Context>(middlewares: Middleware<Context>[]) => {
41
- return async (context: Context): Promise<void> => {
42
- let index = 0;
43
-
44
- const next: MiddlewareNext = async (error?: Error) => {
45
- if (error) {
46
- throw error;
47
- }
48
-
49
- if (index < middlewares.length) {
50
- const currentMiddleware = middlewares[index];
51
- index++;
52
- try {
53
- await currentMiddleware(context, next);
54
- } catch (err) {
55
- await next(err as Error);
56
- }
57
- }
58
- };
59
-
60
- await next();
61
- };
62
- };
63
-
64
- export const runPreRequest = runMiddlewares(preRequestMiddlewares);
65
- export const runPostResponse = runMiddlewares(postResponseMiddlewares);
@@ -1,9 +0,0 @@
1
- export class HttpError extends Error {
2
- public readonly status: number;
3
-
4
- constructor(status: number, message: string) {
5
- super(message);
6
- this.name = 'HttpError';
7
- this.status = status;
8
- }
9
- }
@@ -1,50 +0,0 @@
1
- import { afterEach, describe, expect, it, vi } from 'vitest';
2
-
3
- import { abortableRequest } from './abortableRequest.js';
4
- import { HttpMethod } from './httpMethod.js';
5
- import { request, RequestOptions } from './request.js';
6
-
7
- vi.mock('./request', () => ({
8
- request: vi.fn(),
9
- }));
10
-
11
- const requestMock = vi.mocked(request);
12
-
13
- afterEach(() => {
14
- vi.clearAllMocks();
15
- });
16
-
17
- describe('abortableRequest', () => {
18
- it('should create a request with the given method and options', async () => {
19
- const method = HttpMethod.GET;
20
- const options: RequestOptions = {
21
- headers: { 'Content-Type': 'application/json' },
22
- url: '/api/test',
23
- };
24
- const mockResponse = Promise.resolve('response');
25
- requestMock.mockReturnValue(mockResponse);
26
-
27
- const result = abortableRequest(method, options);
28
-
29
- expect(request).toHaveBeenCalledWith(method, {
30
- ...options,
31
- signal: expect.any(AbortSignal) as AbortSignal,
32
- });
33
- await expect(result).resolves.toBe('response');
34
- });
35
-
36
- it('should abort the request when abort is called', async () => {
37
- const method = HttpMethod.POST;
38
- const options: RequestOptions = { url: '/api/test' };
39
-
40
- const mockedResponse = new Promise((_, reject) => {
41
- setTimeout(() => reject(new DOMException('Aborted', 'AbortError')));
42
- });
43
- requestMock.mockReturnValueOnce(mockedResponse);
44
-
45
- const abortable = abortableRequest(method, options);
46
- abortable.abort();
47
-
48
- await expect(abortable).rejects.toThrowError('Aborted');
49
- });
50
- });
@@ -1,22 +0,0 @@
1
- import { HttpMethod } from './httpMethod.js';
2
- import { request, RequestOptions } from './request.js';
3
-
4
- export interface AbortablePromise<Response> extends Promise<Response> {
5
- abort: () => void;
6
- }
7
-
8
- export const abortableRequest = <Response>(
9
- method: HttpMethod,
10
- options: RequestOptions,
11
- ): AbortablePromise<Response> => {
12
- const controller = new AbortController();
13
- const signal = controller.signal;
14
-
15
- const r = request(method, {
16
- signal,
17
- ...options,
18
- }) as AbortablePromise<Response>;
19
- r.abort = () => controller.abort();
20
-
21
- return r;
22
- };
@@ -1,58 +0,0 @@
1
- import { afterEach, describe, expect, it, vi } from 'vitest';
2
-
3
- import { get, post, put } from '../index.js';
4
- import { withBearerToken } from './auth.js';
5
- import { request } from './request.js';
6
-
7
- vi.mock('./request.js', () => ({
8
- request: vi.fn(),
9
- }));
10
-
11
- const requestMock = vi.mocked(request);
12
-
13
- const getRequest = get('/api/data/get');
14
- const postRequest = post('/api/data/post');
15
- const putRequest = put('/api/data/put');
16
-
17
- afterEach(() => {
18
- vi.clearAllMocks();
19
- });
20
-
21
- describe('withBearerToken', () => {
22
- it('should add the Authorization header with the provided bearer token', async () => {
23
- const bearerToken = 'test-token';
24
- await withBearerToken(bearerToken)(getRequest)();
25
- const requestHeaders = requestMock.mock.calls[0][1].headers!;
26
-
27
- expect(requestHeaders).toEqual({
28
- Authorization: `Bearer ${bearerToken}`,
29
- });
30
- });
31
-
32
- it('should merge the Authorization header with existing headers', async () => {
33
- const bearerToken = 'test-token';
34
- await withBearerToken(bearerToken)(postRequest)({
35
- headers: { 'X-Test': 'Value' },
36
- });
37
- const requestHeaders = requestMock.mock.calls[0][1].headers!;
38
-
39
- expect(requestHeaders).toEqual({
40
- Authorization: `Bearer ${bearerToken}`,
41
- 'X-Test': 'Value',
42
- });
43
- });
44
-
45
- it('should override any existing Authorization header with the provided bearer token', async () => {
46
- const bearerToken = 'new-token';
47
- await withBearerToken(bearerToken)(putRequest)({
48
- headers: {
49
- Authorization: `Bearer Test Test`,
50
- },
51
- });
52
- const requestHeaders = requestMock.mock.calls[0][1].headers!;
53
-
54
- expect(requestHeaders).toEqual({
55
- Authorization: `Bearer ${bearerToken}`,
56
- });
57
- });
58
- });
package/src/utils/auth.ts DELETED
@@ -1,16 +0,0 @@
1
- import { AbortablePromise } from './abortableRequest.js';
2
- import { Request, RequestOptionsWithoutUrl } from './request.js';
3
-
4
- export const withBearerToken =
5
- (bearerToken: string) =>
6
- <Response, PromiseType extends AbortablePromise<Response> | Promise<Response>>(
7
- req: Request<Response, PromiseType>,
8
- ) =>
9
- (options: Omit<RequestOptionsWithoutUrl, 'body'> = {}) =>
10
- req({
11
- ...options,
12
- headers: {
13
- ...options.headers,
14
- Authorization: `Bearer ${bearerToken}`,
15
- },
16
- });
@@ -1,17 +0,0 @@
1
- type AbsoluteURLString = `${Lowercase<'http' | 'https'>}://${string}`;
2
-
3
- export type BaseURL = AbsoluteURLString | URL;
4
-
5
- export const getDefaultBaseUrl = (): string => {
6
- const baseUrl =
7
- typeof window === 'undefined' ? process.env.BASE_URL || '' : window.location.origin;
8
-
9
- if (!baseUrl) {
10
- throw new Error('BASE_URL is not defined');
11
- }
12
-
13
- return baseUrl;
14
- };
15
-
16
- // Helper to preset a base URL on requests.
17
- export { withBaseUrl } from './withBaseUrl.js';
@@ -1,123 +0,0 @@
1
- import { afterEach, describe, expect, it, vi } from 'vitest';
2
-
3
- import { patch, post, put } from '../index.js';
4
- import { JsonObjectWithFile, withFormDataBody, withJsonBody } from './body.js';
5
- import { HttpMethod } from './httpMethod.js';
6
- import { request } from './request.js';
7
-
8
- vi.mock('./request.js', () => ({
9
- request: vi.fn(),
10
- }));
11
-
12
- const requestMock = vi.mocked(request);
13
-
14
- const postRequest = post('/api/data/post');
15
- const putRequest = put('/api/data/put');
16
- const patchRequest = patch('/api/data/patch');
17
-
18
- afterEach(() => {
19
- vi.clearAllMocks();
20
- });
21
-
22
- const formDataToObject = (formData: FormData) => {
23
- const obj: JsonObjectWithFile = {};
24
- for (const [key, value] of formData.entries()) {
25
- if (obj[key]) {
26
- obj[key] = Array.isArray(obj[key]) ? [...obj[key], value] : [obj[key], value];
27
- } else {
28
- obj[key] = value;
29
- }
30
- }
31
- return obj;
32
- };
33
-
34
- describe('withJsonBody', () => {
35
- it('should set JSON body and content-type header', async () => {
36
- const jsonBody = { key: 'value' };
37
- await withJsonBody(jsonBody)(postRequest)();
38
- const requestBody = requestMock.mock.calls[0][1].body as string;
39
-
40
- expect(requestBody).toBe(JSON.stringify(jsonBody));
41
- });
42
-
43
- it('should merge existing headers', async () => {
44
- const jsonBody = { key: 'value' };
45
- await withJsonBody(jsonBody)(putRequest)({ headers: { Authorization: 'Bearer token' } });
46
-
47
- expect(requestMock).toHaveBeenCalledWith(HttpMethod.PUT, {
48
- body: JSON.stringify(jsonBody),
49
- headers: {
50
- Authorization: 'Bearer token',
51
- 'content-type': 'application/json',
52
- },
53
- url: '/api/data/put',
54
- });
55
- });
56
- });
57
-
58
- describe('withFormDataBody', () => {
59
- it('should set FormData body with simple key-value pairs', async () => {
60
- const body = { key: 'value' };
61
- await withFormDataBody(body)(patchRequest)();
62
- const requestBody = requestMock.mock.calls[0][1].body as FormData;
63
-
64
- const formData = new FormData();
65
- formData.append('key', 'value');
66
-
67
- expect(formDataToObject(requestBody)).toEqual(formDataToObject(formData));
68
- });
69
-
70
- it('should handle nested objects in FormData', async () => {
71
- const body = { user: { age: 25, name: 'Alice' } };
72
- await withFormDataBody(body)(postRequest)();
73
- const requestBody = requestMock.mock.calls[0][1].body as FormData;
74
-
75
- const formData = new FormData();
76
- formData.append('user[name]', 'Alice');
77
- formData.append('user[age]', '25');
78
-
79
- expect(formDataToObject(requestBody)).toEqual(formDataToObject(formData));
80
- });
81
-
82
- it('should handle arrays in FormData', async () => {
83
- const body = { tags: ['tag1', 'tag2'] };
84
- await withFormDataBody(body)(putRequest)();
85
- const requestBody = requestMock.mock.calls[0][1].body as FormData;
86
-
87
- const formData = new FormData();
88
- formData.append('tags[0]', 'tag1');
89
- formData.append('tags[1]', 'tag2');
90
-
91
- expect(formDataToObject(requestBody)).toEqual(formDataToObject(formData));
92
- });
93
-
94
- it('should handle File and Blob objects in FormData', async () => {
95
- const file = new File(['file contents'], 'test.txt');
96
- const body = { file };
97
- await withFormDataBody(body)(patchRequest)();
98
- const requestBody = requestMock.mock.calls[0][1].body as FormData;
99
-
100
- const formData = new FormData();
101
- formData.append('file', file);
102
-
103
- expect(formDataToObject(requestBody)).toEqual(formDataToObject(formData));
104
- });
105
-
106
- it('should merge existing headers', async () => {
107
- const jsonBody = { key: 'value' };
108
- await withFormDataBody(jsonBody)(putRequest)({ headers: { Authorization: 'Bearer token' } });
109
- const requestBody = requestMock.mock.calls[0][1].body as FormData;
110
-
111
- const formData = new FormData();
112
- formData.append('key', 'value');
113
-
114
- expect(requestMock).toHaveBeenCalledWith(HttpMethod.PUT, {
115
- body: expect.any(FormData) as FormData,
116
- headers: {
117
- Authorization: 'Bearer token',
118
- },
119
- url: '/api/data/put',
120
- });
121
- expect(formDataToObject(requestBody)).toEqual(formDataToObject(formData));
122
- });
123
- });
package/src/utils/body.ts DELETED
@@ -1,74 +0,0 @@
1
- import { JsonPrimitive as BaseJsonPrimitive, JsonObject, JsonValue } from 'type-fest';
2
-
3
- import { AbortablePromise } from './abortableRequest.js';
4
- import { Request, RequestOptionsWithoutUrl } from './request.js';
5
-
6
- // undefined is not allowed in JsonObjectWithFile (because it is not allowed in Json)
7
- export type JsonObjectWithFile = {
8
- [Key in string]: JsonValueWithFile;
9
- } & {
10
- [Key in string]?: JsonValueWithFile;
11
- };
12
- type JsonArrayWithFile = JsonValueWithFile[] | readonly JsonValueWithFile[];
13
- type JsonPrimitiveWithFile = BaseJsonPrimitive | Blob | File;
14
- type JsonValueWithFile = JsonArrayWithFile | JsonObjectWithFile | JsonPrimitiveWithFile;
15
-
16
- const isJsonObject = (value: unknown): value is JsonObject =>
17
- typeof value === 'object' && !Array.isArray(value);
18
-
19
- const jsonToFormData = (
20
- json: JsonObjectWithFile,
21
- formData = new FormData(),
22
- parentKey = '',
23
- ): FormData => {
24
- const appendValue = (key: string, value: unknown) => {
25
- if (value instanceof File || value instanceof Blob) {
26
- formData.append(key, value);
27
- } else if (isJsonObject(value)) {
28
- // Recursive call for nested objects
29
- jsonToFormData(value, formData, key);
30
- } else {
31
- formData.append(key, value as Blob | string);
32
- }
33
- };
34
-
35
- Object.entries(json).forEach(([key, value]) => {
36
- const fullKey = parentKey ? `${parentKey}[${key}]` : key;
37
-
38
- if (Array.isArray(value)) {
39
- value.forEach((item, index) => appendValue(`${fullKey}[${index}]`, item));
40
- } else {
41
- appendValue(fullKey, value);
42
- }
43
- });
44
-
45
- return formData;
46
- };
47
-
48
- export type Body = BodyInit | JsonValueWithFile;
49
-
50
- export const withJsonBody =
51
- <Body extends JsonValue>(fixedBody: Body) =>
52
- <Response, PromiseType extends AbortablePromise<Response> | Promise<Response>>(
53
- req: Request<Response, PromiseType>,
54
- ) =>
55
- (options: Omit<RequestOptionsWithoutUrl, 'body'> = {}) =>
56
- req({
57
- ...options,
58
- body: JSON.stringify(fixedBody),
59
- headers: {
60
- ...options.headers,
61
- 'content-type': 'application/json',
62
- },
63
- });
64
-
65
- export const withFormDataBody =
66
- <Body extends JsonObjectWithFile>(fixedBody: Body) =>
67
- <Response, PromiseType extends AbortablePromise<Response> | Promise<Response>>(
68
- req: Request<Response, PromiseType>,
69
- ) =>
70
- (options: Omit<RequestOptionsWithoutUrl, 'body'> = {}) =>
71
- req({
72
- ...options,
73
- body: jsonToFormData(fixedBody),
74
- });
@@ -1,11 +0,0 @@
1
- export enum HttpMethod {
2
- CONNECT = 'CONNECT',
3
- DELETE = 'DELETE',
4
- GET = 'GET',
5
- HEAD = 'HEAD',
6
- OPTIONS = 'OPTIONS',
7
- PATCH = 'PATCH',
8
- POST = 'POST',
9
- PUT = 'PUT',
10
- TRACE = 'TRACE',
11
- }
@@ -1,75 +0,0 @@
1
- import { afterEach, describe, expect, it, vi } from 'vitest';
2
-
3
- import { get, patch, post, put } from '../index.js';
4
- import { HttpMethod } from './httpMethod.js';
5
- import { QueryParams, withQueryParams } from './queryParams.js';
6
- import { request } from './request.js';
7
-
8
- vi.mock('./request.js', () => ({
9
- request: vi.fn(),
10
- }));
11
-
12
- const requestMock = vi.mocked(request);
13
-
14
- const getRequest = get('/api/data/get');
15
- const postRequest = post('/api/data/post');
16
- const putRequest = put('/api/data/put');
17
- const patchRequest = patch('/api/data/patch');
18
-
19
- const compareSearchParams = (reference: URLSearchParams, value: URLSearchParams) => {
20
- const referenceArray = Array.from(reference.entries());
21
- const valueArray = Array.from(value.entries());
22
- expect(referenceArray.length).toEqual(valueArray.length);
23
- expect(valueArray).toEqual(expect.arrayContaining(referenceArray));
24
- };
25
-
26
- afterEach(() => {
27
- vi.clearAllMocks();
28
- });
29
-
30
- describe('withQueryParams', () => {
31
- it('should add single query parameters to the request URL', async () => {
32
- const query: QueryParams = { baz: 42, foo: 'bar' };
33
- await withQueryParams(query)(getRequest)();
34
- const requestSearchParams = requestMock.mock.calls[0][1].searchParams!;
35
-
36
- compareSearchParams(requestSearchParams, new URLSearchParams('foo=bar&baz=42'));
37
- });
38
-
39
- it('should handle array values in query parameters', async () => {
40
- const query: QueryParams = { foo: ['bar', 'baz'] };
41
- await withQueryParams(query)(postRequest)();
42
- const requestSearchParams = requestMock.mock.calls[0][1].searchParams!;
43
-
44
- compareSearchParams(requestSearchParams, new URLSearchParams('foo=bar&foo=baz'));
45
- });
46
-
47
- it('should ignore null and undefined values in query parameters', async () => {
48
- const query: QueryParams = { baz: null, foo: 'bar', qux: undefined };
49
- await withQueryParams(query)(putRequest)();
50
- const requestSearchParams = requestMock.mock.calls[0][1].searchParams!;
51
-
52
- compareSearchParams(requestSearchParams, new URLSearchParams('foo=bar'));
53
- });
54
-
55
- it('should handle boolean values in query parameters', async () => {
56
- const query: QueryParams = { bar: false, foo: true };
57
- await withQueryParams(query)(patchRequest)();
58
- const requestSearchParams = requestMock.mock.calls[0][1].searchParams!;
59
-
60
- compareSearchParams(requestSearchParams, new URLSearchParams('foo=true&bar=false'));
61
- });
62
-
63
- it('should merge query parameters with existing options', async () => {
64
- const query: QueryParams = { foo: 'bar' };
65
- await withQueryParams(query)(getRequest)({ headers: { Authorization: 'Bearer token' } });
66
- const requestSearchParams = requestMock.mock.calls[0][1].searchParams!;
67
-
68
- compareSearchParams(requestSearchParams, new URLSearchParams('foo=bar'));
69
- expect(requestMock).toHaveBeenCalledWith(HttpMethod.GET, {
70
- headers: { Authorization: 'Bearer token' },
71
- searchParams: expect.any(URLSearchParams) as URLSearchParams,
72
- url: '/api/data/get',
73
- });
74
- });
75
- });
@@ -1,31 +0,0 @@
1
- import { AbortablePromise } from './abortableRequest.js';
2
- import { Request } from './request.js';
3
-
4
- export type QueryParams = Record<string, QueryParamValue | QueryParamValue[]>;
5
- type QueryParamValue = boolean | null | number | string | undefined;
6
-
7
- export const queryParamsToURLSearchParams = (query: QueryParams): URLSearchParams => {
8
- const params = new URLSearchParams();
9
-
10
- Object.entries(query).forEach(([key, value]) => {
11
- if (Array.isArray(value)) {
12
- value.forEach((v) => params.append(key, String(v)));
13
- } else if (value !== null && value !== undefined) {
14
- params.append(key, String(value));
15
- }
16
- });
17
-
18
- return params;
19
- };
20
-
21
- export const withQueryParams =
22
- <Query extends QueryParams>(query: Query) =>
23
- <Response, PromiseType extends AbortablePromise<Response> | Promise<Response>>(
24
- req: Request<Response, PromiseType>,
25
- ): Request<Response, PromiseType> =>
26
- (options = {}) => {
27
- return req({
28
- ...options,
29
- searchParams: queryParamsToURLSearchParams(query),
30
- });
31
- };