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
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,17 @@ final class AlgoliaWaitException implements AlgoliaException {
}
}

/// Represents a successful API response with no content (HTTP 204).
///
/// Returned by custom request methods when the server responds with
/// 204 No Content, as Dart's type system requires a non-null return value.
final class AlgoliaNoResponse {
const AlgoliaNoResponse();

@override
String toString() => 'AlgoliaNoResponse{}';
}

/// Exception thrown when all hosts for the Algolia API are unreachable.
///
/// Contains a list of the errors associated with each unreachable host.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ final class RetryStrategy {
);

/// Run an request and get a response.
Future<Map<String, dynamic>> execute({
Future<Map<String, dynamic>?> execute({
required ApiRequest request,
RequestOptions? options,
}) async {
Expand All @@ -66,7 +66,7 @@ final class RetryStrategy {
final response = await requester.perform(httpRequest);
host.reset();
requester.setConnectTimeout(requesterConnectTimeout);
return response.body ?? const {};
return response.statusCode == 204 ? null : response.body;
} on AlgoliaTimeoutException catch (e) {
host.timedOut();
errors.add(e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,8 @@ private <T> T execute(@Nonnull HttpRequest httpRequest, RequestOptions requestOp
}

// Return null if there's no content or the return type isn't provided.
if (returnType == null || response.body() == null || response.body().contentLength() == 0) {
return null; // No need to deserialize, either no content or no type provided
if (returnType == null || response.body() == null || response.body().contentLength() == 0 || response.code() == 204) {
return null;
}

// Returns the raw response when using `*WithHTTPInfo` methods.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,11 @@ export function serializeHeaders(
}

export function deserializeSuccess<TObject>(response: Response): TObject {
// Handle 204 No Content and other empty responses
if (response.status === 204 || response.content.length === 0) {
return undefined as unknown as TObject;
}

try {
return JSON.parse(response.content);
} catch (e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,8 @@ public class KtorRequester(
requestBuilder.setTimeout(requestOptions, callType, host)
try {
val response = httpClient.request(requestBuilder)
val body = response.body<T>(returnType)
@Suppress("UNCHECKED_CAST")
val body: T = if (response.status.value == 204 || response.contentLength() == 0L) null as T else response.body<T>(returnType)
mutex.withLock { host.reset() }
return body
} catch (exception: Throwable) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -284,15 +284,19 @@ private function handleResponse(
throw new AlgoliaException($statusCode.': '.$response->getReasonPhrase(), $statusCode);
}

try {
$deserializeStart = microtime(true);
$responseArray = Helpers::json_decode($body, true);
$deserializeDurationMs = round((microtime(true) - $deserializeStart) * 1000);
$this->log(LogLevel::DEBUG, 'Response body deserialized in '.$deserializeDurationMs.'ms');
} catch (\InvalidArgumentException $e) {
$this->log(LogLevel::ERROR, 'Failed to deserialize response: '.$e->getMessage());

throw $e;
if (204 === $statusCode || $body === '') {
$responseArray = null;
} else {
try {
$deserializeStart = microtime(true);
$responseArray = Helpers::json_decode($body, true);
$deserializeDurationMs = round((microtime(true) - $deserializeStart) * 1000);
$this->log(LogLevel::DEBUG, 'Response body deserialized in '.$deserializeDurationMs.'ms');
} catch (\InvalidArgumentException $e) {
$this->log(LogLevel::ERROR, 'Failed to deserialize response: '.$e->getMessage());

throw $e;
}
}

if (404 === $statusCode) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def deserialize(klass: Any = None, data: Any = None) -> Any:

:return: object.
"""
if data is None:
if data is None or data == "":
return None

if hasattr(klass, "__origin__") and klass.__origin__ is list:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -161,8 +161,8 @@ private[algoliasearch] class HttpRequester private (
// Handle unsuccessful responses.
if (!response.isSuccessful)
throw AlgoliaApiException(message = response.message, httpErrorCode = response.code)
// Deserialize and return the response.
jsonSerializer.deserialize[T](response.body.byteStream)
if (response.code == 204) null.asInstanceOf[T]
else jsonSerializer.deserialize[T](response.body.byteStream)
} catch {
case exception: IOException => throw AlgoliaClientException(cause = exception)
case exception: AlgoliaApiException =>
Expand Down
2 changes: 2 additions & 0 deletions scripts/cts/testServer/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { chunkWrapperServer } from './chunkWrapper.ts';
import { errorServer, errorServerRetriedOnce, errorServerRetriedTwice, neverCalledServer } from './error.ts';
import { gzipServer } from './gzip.ts';
import { gzipResponseServer } from './gzipResponse.ts';
import { noContentServer } from './noContent.ts';
import { pushMockServer, pushMockServerRetriedOnce } from './pushMock.ts';
import { replaceAllObjectsServer } from './replaceAllObjects.ts';
import { replaceAllObjectsServerFailed } from './replaceAllObjectsFailed.ts';
Expand Down Expand Up @@ -49,6 +50,7 @@ export async function startTestServer(suites: Record<CTSType, boolean>): Promise
pushMockServer(),
pushMockServerRetriedOnce(),
replaceAllObjectsWithTransformationServer(),
noContentServer(),
);
}
if (suites.benchmark) {
Expand Down
15 changes: 15 additions & 0 deletions scripts/cts/testServer/noContent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import type { Server } from 'http';

import type express from 'express';

import { setupServer } from './index.ts';

function addRoutes(app: express.Express): void {
app.all('/1/test/no-content', (_req, res) => {
res.status(204).end();
});
}

export function noContentServer(): Promise<Server> {
return setupServer('noContent', 6692, addRoutes);
}
3 changes: 3 additions & 0 deletions templates/dart/api.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,9 @@ final class {{classname}} implements ApiClient {
) + {{/vendorExtensions.x-timeouts}}requestOptions,
);
{{#returnType}}
{{#vendorExtensions.x-is-custom-request}}
if (response == null) return AlgoliaNoResponse();
{{/vendorExtensions.x-is-custom-request}}
return deserialize<{{{.}}}, {{{returnBaseType}}}>(response, '{{{.}}}', growable: true,);
{{/returnType}}
}
Expand Down
5 changes: 5 additions & 0 deletions templates/dart/tests/client/method.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,12 @@ try {
expectBody(res, """{{{match.value}}}""");
{{/match.isPrimitive}}
{{#match.isPrimitive}}
{{#match.isNull}}
expect(res, isA<AlgoliaNoResponse>());
{{/match.isNull}}
{{^match.isNull}}
expect(res, {{#match}}{{> tests/param_value}}{{/match}});
{{/match.isNull}}
{{/match.isPrimitive}}
{{/testResponse}}
} on InterceptionException catch (_) {
Expand Down
7 changes: 6 additions & 1 deletion templates/swift/tests/client/tests.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,12 @@
{{/match.isPrimitive}}
{{/isHelper}}
{{^isHelper}}
XTCJSONEquals(received: response, expected: "{{#lambda.escapeQuotes}}{{{match.value}}}{{/lambda.escapeQuotes}}")
{{#match.isNull}}
XCTAssertTrue(response.value is Void)
{{/match.isNull}}
{{^match.isNull}}
XTCJSONEquals(received: response, expected: "{{#lambda.escapeQuotes}}{{{match.value}}}{{/lambda.escapeQuotes}}")
{{/match.isNull}}
{{/isHelper}}
{{/testResponse}}
{{#shouldScope}}
Expand Down
32 changes: 32 additions & 0 deletions tests/CTS/client/common/noContent.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
[
{
"testName": "handles 204 No Content responses correctly",
"autoCreateClient": false,
"steps": [
{
"type": "createClient",
"parameters": {
"appId": "test-app-id",
"apiKey": "test-api-key",
"region": "us",
"customHosts": [
{
"port": 6692
}
]
}
},
{
"type": "method",
"method": "customDelete",
"parameters": {
"path": "1/test/no-content"
},
"expected": {
"type": "response",
"match": null
}
}
]
}
]
Loading