Skip to content

Commit 8a5ab6f

Browse files
authored
feat(javascript): add WithHTTPInfo methods (#6682)
1 parent 372ab5f commit 8a5ab6f

17 files changed

Lines changed: 442 additions & 57 deletions

File tree

‎clients/algoliasearch-client-javascript/package.json‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
"files": [
2828
{
2929
"path": "packages/algoliasearch/dist/algoliasearch.umd.js",
30-
"maxSize": "17KB"
30+
"maxSize": "21KB"
3131
},
3232
{
3333
"path": "packages/algoliasearch/dist/lite/builds/browser.umd.js",
@@ -43,11 +43,11 @@
4343
},
4444
{
4545
"path": "packages/client-analytics/dist/builds/browser.umd.js",
46-
"maxSize": "6KB"
46+
"maxSize": "7KB"
4747
},
4848
{
4949
"path": "packages/composition/dist/builds/browser.umd.js",
50-
"maxSize": "6KB"
50+
"maxSize": "7KB"
5151
},
5252
{
5353
"path": "packages/client-insights/dist/builds/browser.umd.js",
@@ -63,11 +63,11 @@
6363
},
6464
{
6565
"path": "packages/client-search/dist/builds/browser.umd.js",
66-
"maxSize": "9KB"
66+
"maxSize": "10KB"
6767
},
6868
{
6969
"path": "packages/ingestion/dist/builds/browser.umd.js",
70-
"maxSize": "8KB"
70+
"maxSize": "10KB"
7171
},
7272
{
7373
"path": "packages/monitoring/dist/builds/browser.umd.js",

‎clients/algoliasearch-client-javascript/packages/algoliasearch/__tests__/algoliasearch.common.test.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,7 @@ describe('api', () => {
122122
},
123123
request: expect.any(Function),
124124
requestStream: expect.any(Function),
125+
requestWithHttpInfo: expect.any(Function),
125126
requester: {
126127
send: expect.any(Function),
127128
sendStream: expect.any(Function),
@@ -146,6 +147,20 @@ describe('api', () => {
146147
});
147148
});
148149

150+
describe('withHTTPInfo methods', () => {
151+
test('exposes a `searchWithHTTPInfo` variant returning the full HTTP response information', async () => {
152+
const response = await client.searchWithHTTPInfo({ requests: [{ indexName: 'theIndexName' }] });
153+
const req = response.data as unknown as EchoResponse;
154+
155+
expect(response.status).toEqual(200);
156+
expect(response.headers).toEqual(expect.objectContaining({ 'content-type': 'text/plain' }));
157+
expect(JSON.parse(response.content)).toEqual(req);
158+
expect(req.path).toEqual('/1/indexes/*/queries');
159+
expect(req.method).toEqual('POST');
160+
expect(req.data).toEqual({ requests: [{ indexName: 'theIndexName' }] });
161+
});
162+
});
163+
149164
describe('bridge methods', () => {
150165
test('throws when missing transformationOptions.region', () => {
151166
//@ts-expect-error
Lines changed: 179 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,179 @@
1+
import { describe, expect, test } from 'vitest';
2+
import { createMemoryCache, createNullCache } from '../../cache';
3+
import { createNullLogger } from '../../logger';
4+
import { ApiError, DetailedApiError, createTransporter } from '../../transporter';
5+
import type { AlgoliaAgent, Requester, TransporterWithHttpInfo } from '../../types';
6+
7+
describe('transporter requestWithHttpInfo', () => {
8+
const algoliaAgent: AlgoliaAgent = {
9+
value: 'test',
10+
add: () => algoliaAgent,
11+
};
12+
13+
function createTestTransporter(requester: Requester): TransporterWithHttpInfo {
14+
return createTransporter({
15+
hosts: [{ url: 'localhost', accept: 'readWrite', protocol: 'https' }],
16+
hostsCache: createNullCache(),
17+
baseHeaders: {},
18+
baseQueryParameters: {},
19+
algoliaAgent,
20+
logger: createNullLogger(),
21+
timeouts: {
22+
connect: 1000,
23+
read: 2000,
24+
write: 3000,
25+
},
26+
requester,
27+
requestsCache: createMemoryCache(),
28+
responsesCache: createMemoryCache(),
29+
});
30+
}
31+
32+
test('resolves with the status, headers, content and the same deserialized data as `request`', async () => {
33+
const transporter = createTestTransporter({
34+
send: async () => ({
35+
status: 200,
36+
content: JSON.stringify({ value: 42 }),
37+
headers: { 'x-served-by': 'test-host' },
38+
isTimedOut: false,
39+
}),
40+
});
41+
42+
const response = await transporter.requestWithHttpInfo<{ value: number }>({
43+
method: 'GET',
44+
path: '/test',
45+
queryParameters: {},
46+
headers: {},
47+
});
48+
49+
expect(response).toEqual({
50+
status: 200,
51+
headers: { 'x-served-by': 'test-host' },
52+
content: JSON.stringify({ value: 42 }),
53+
data: { value: 42 },
54+
});
55+
56+
const data = await transporter.request<{ value: number }>({
57+
method: 'GET',
58+
path: '/test',
59+
queryParameters: {},
60+
headers: {},
61+
});
62+
63+
expect(response.data).toEqual(data);
64+
});
65+
66+
test('leaves `headers` undefined when the requester does not capture them', async () => {
67+
const transporter = createTestTransporter({
68+
send: async () => ({
69+
status: 200,
70+
content: JSON.stringify({ value: 42 }),
71+
isTimedOut: false,
72+
}),
73+
});
74+
75+
const response = await transporter.requestWithHttpInfo<{ value: number }>({
76+
method: 'GET',
77+
path: '/test',
78+
queryParameters: {},
79+
headers: {},
80+
});
81+
82+
expect(response.headers).toBeUndefined();
83+
});
84+
85+
test('resolves with `undefined` data on 204 empty responses', async () => {
86+
const transporter = createTestTransporter({
87+
send: async () => ({
88+
status: 204,
89+
content: '',
90+
headers: {},
91+
isTimedOut: false,
92+
}),
93+
});
94+
95+
const response = await transporter.requestWithHttpInfo<undefined>({
96+
method: 'DELETE',
97+
path: '/test',
98+
queryParameters: {},
99+
headers: {},
100+
});
101+
102+
expect(response.status).toBe(204);
103+
expect(response.content).toBe('');
104+
expect(response.data).toBeUndefined();
105+
});
106+
107+
test('throws the same errors as `request` on non-2xx responses', async () => {
108+
const transporter = createTestTransporter({
109+
send: async () => ({
110+
status: 403,
111+
content: JSON.stringify({ message: 'Invalid API key', status: 403 }),
112+
isTimedOut: false,
113+
}),
114+
});
115+
116+
const request = {
117+
method: 'GET',
118+
path: '/test',
119+
queryParameters: {},
120+
headers: {},
121+
} as const;
122+
123+
await expect(transporter.requestWithHttpInfo(request)).rejects.toThrow(new ApiError('Invalid API key', 403, []));
124+
await expect(transporter.request(request)).rejects.toThrow(new ApiError('Invalid API key', 403, []));
125+
});
126+
127+
test('throws detailed errors when the response contains one', async () => {
128+
const transporter = createTestTransporter({
129+
send: async () => ({
130+
status: 400,
131+
content: JSON.stringify({ message: 'Invalid request', status: 400, error: { code: 'invalid_request' } }),
132+
isTimedOut: false,
133+
}),
134+
});
135+
136+
await expect(
137+
transporter.requestWithHttpInfo({
138+
method: 'GET',
139+
path: '/test',
140+
queryParameters: {},
141+
headers: {},
142+
}),
143+
).rejects.toBeInstanceOf(DetailedApiError);
144+
});
145+
146+
test('bypasses the requests and responses caches, even for cacheable requests', async () => {
147+
let requestCount = 0;
148+
const transporter = createTestTransporter({
149+
send: async () => {
150+
requestCount++;
151+
return {
152+
status: 200,
153+
content: JSON.stringify({ value: requestCount }),
154+
isTimedOut: false,
155+
};
156+
},
157+
});
158+
159+
const request = {
160+
method: 'GET',
161+
path: '/test',
162+
queryParameters: {},
163+
headers: {},
164+
cacheable: true,
165+
} as const;
166+
167+
const firstResponse = await transporter.requestWithHttpInfo<{ value: number }>(request);
168+
const secondResponse = await transporter.requestWithHttpInfo<{ value: number }>(request);
169+
170+
// Each call hits the network, nothing is read from nor written to the caches
171+
expect(firstResponse.data).toEqual({ value: 1 });
172+
expect(secondResponse.data).toEqual({ value: 2 });
173+
expect(requestCount).toBe(2);
174+
175+
// The plain `request` does not see cache entries created by `requestWithHttpInfo` either
176+
const cachedData = await transporter.request<{ value: number }>(request);
177+
expect(cachedData).toEqual({ value: 3 });
178+
});
179+
});

‎clients/algoliasearch-client-javascript/packages/client-common/src/transporter/createTransporter.ts‎

Lines changed: 39 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,28 @@
11
import type { ServerSentEvent } from '../sse';
22
import { iterSSEEvents } from '../sse';
33
import type {
4+
AlgoliaHttpResponse,
45
EndRequest,
56
Host,
67
QueryParameters,
78
Request,
89
RequestOptions,
910
Response,
1011
StackFrame,
11-
Transporter,
1212
TransporterOptions,
13+
TransporterWithHttpInfo,
1314
} from '../types';
1415
import { COMPRESSION_THRESHOLD } from './compress';
1516
import { createStatefulHost } from './createStatefulHost';
1617
import { RetryError } from './errors';
17-
import { deserializeFailure, deserializeSuccess, serializeData, serializeHeaders, serializeUrl } from './helpers';
18+
import {
19+
deserializeFailure,
20+
deserializeSuccess,
21+
deserializeSuccessWithHttpInfo,
22+
serializeData,
23+
serializeHeaders,
24+
serializeUrl,
25+
} from './helpers';
1826
import { isRetryable, isSuccess } from './responses';
1927
import { stackFrameWithoutCredentials, stackTraceWithoutCredentials } from './stackTrace';
2028

@@ -36,7 +44,7 @@ export function createTransporter({
3644
responsesCache,
3745
compress,
3846
compression,
39-
}: TransporterOptions): Transporter {
47+
}: TransporterOptions): TransporterWithHttpInfo {
4048
async function createRetryableOptions(compatibleHosts: Host[]): Promise<RetryableOptions> {
4149
const statefulHosts = await Promise.all(
4250
compatibleHosts.map((compatibleHost) => {
@@ -74,11 +82,11 @@ export function createTransporter({
7482
};
7583
}
7684

77-
async function retryableRequest<TResponse>(
85+
async function retryableRequest(
7886
request: Request,
7987
requestOptions: RequestOptions,
8088
isRead: boolean,
81-
): Promise<TResponse> {
89+
): Promise<Response> {
8290
const stackTrace: StackFrame[] = [];
8391

8492
/**
@@ -143,7 +151,7 @@ export function createTransporter({
143151
const retry = async (
144152
retryableHosts: Host[],
145153
getTimeout: (timeoutsCount: number, timeout: number) => number,
146-
): Promise<TResponse> => {
154+
): Promise<Response> => {
147155
/**
148156
* We iterate on each host, until there is no host left.
149157
*/
@@ -208,7 +216,7 @@ export function createTransporter({
208216
}
209217

210218
if (isSuccess(response)) {
211-
return deserializeSuccess(response);
219+
return response;
212220
}
213221

214222
pushToStackTrace(response);
@@ -238,7 +246,9 @@ export function createTransporter({
238246
* the retryable request. At this point, we may *not* perform the actual
239247
* request. But we want to have the function factory ready.
240248
*/
241-
return retryableRequest<TResponse>(request, requestOptions, isRead);
249+
return retryableRequest(request, requestOptions, isRead).then((response) =>
250+
deserializeSuccess<TResponse>(response),
251+
);
242252
};
243253

244254
/**
@@ -313,6 +323,26 @@ export function createTransporter({
313323
);
314324
}
315325

326+
function createRequestWithHttpInfo<TData>(
327+
request: Request,
328+
requestOptions: RequestOptions = {},
329+
): Promise<AlgoliaHttpResponse<TData>> {
330+
/**
331+
* A read request is either a `GET` request, or a request that we make
332+
* via the `read` transporter (e.g. `search`).
333+
*/
334+
const isRead = request.useReadTransporter || request.method === 'GET';
335+
336+
/**
337+
* The HTTP info variant always hits the network: both the requests and
338+
* the responses caches are bypassed, even for `cacheable` requests, so
339+
* that the returned status code and headers reflect an actual API call.
340+
*/
341+
return retryableRequest(request, requestOptions, isRead).then((response) =>
342+
deserializeSuccessWithHttpInfo<TData>(response),
343+
);
344+
}
345+
316346
async function* requestStream(
317347
request: Request,
318348
requestOptions: RequestOptions = {},
@@ -391,6 +421,7 @@ export function createTransporter({
391421
baseQueryParameters,
392422
hosts,
393423
request: createRequest,
424+
requestWithHttpInfo: createRequestWithHttpInfo,
394425
requestStream,
395426
requestsCache,
396427
responsesCache,

‎clients/algoliasearch-client-javascript/packages/client-common/src/transporter/helpers.ts‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,13 @@
1-
import type { Headers, Host, QueryParameters, Request, RequestOptions, Response, StackFrame } from '../types';
1+
import type {
2+
AlgoliaHttpResponse,
3+
Headers,
4+
Host,
5+
QueryParameters,
6+
Request,
7+
RequestOptions,
8+
Response,
9+
StackFrame,
10+
} from '../types';
211
import { ApiError, DeserializationError, DetailedApiError } from './errors';
312

413
export function shuffle<TData>(array: TData[]): TData[] {
@@ -87,6 +96,15 @@ export function deserializeSuccess<TObject>(response: Response): TObject {
8796
}
8897
}
8998

99+
export function deserializeSuccessWithHttpInfo<TData>(response: Response): AlgoliaHttpResponse<TData> {
100+
return {
101+
status: response.status,
102+
headers: response.headers,
103+
content: response.content,
104+
data: deserializeSuccess<TData>(response),
105+
};
106+
}
107+
90108
export function deserializeFailure({ content, status }: Response, stackFrame: StackFrame[]): Error {
91109
try {
92110
const parsed = JSON.parse(content);

0 commit comments

Comments
 (0)