Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: added support for handling empty responses with nullable types #181

Merged
merged 6 commits into from
Jul 9, 2024
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
23 changes: 18 additions & 5 deletions packages/core/src/http/requestBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -499,16 +499,15 @@ export class DefaultRequestBuilder<BaseUrlParamType, AuthParams>
return { ...request, headers };
});
const result = await this.call(requestOptions);
if (result.body === '') {
throw new Error(
'Could not parse body as JSON. The response body is empty.'
);
}
if (typeof result.body !== 'string') {
throw new Error(
'Could not parse body as JSON. The response body is not a string.'
);
}
if (result.body.trim() === '') {
// Try mapping the missing body as null
return this.tryMappingAsNull<T>(schema, result);
}
let parsed: unknown;
try {
parsed = JSON.parse(result.body);
Expand All @@ -521,6 +520,20 @@ export class DefaultRequestBuilder<BaseUrlParamType, AuthParams>
}
return { ...result, result: mappingResult.result };
}

private tryMappingAsNull<T>(
schema: Schema<T, any>,
result: ApiResponse<void>
) {
const nullMappingResult = validateAndMap(null, schema);
if (nullMappingResult.errors) {
throw new Error(
'Could not parse body as JSON. The response body is empty.'
);
}
return { ...result, result: nullMappingResult.result };
}

public async callAsXml<T>(
rootName: string,
schema: Schema<T, any>,
Expand Down
118 changes: 113 additions & 5 deletions packages/core/test/http/requestBuilder.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {
HttpClientInterface,
RequestBuilder,
createRequestBuilderFactory,
skipEncode,
} from '../../src/http/requestBuilder';
Expand All @@ -24,6 +25,7 @@ import { FileWrapper } from '../../src/fileWrapper';
import fs from 'fs';
import path from 'path';
import { bossSchema } from '../../../schema/test/bossSchema';
import { boolean, nullable, optional } from '@apimatic/schema/src';

describe('test default request builder behavior with succesful responses', () => {
const authParams = {
Expand All @@ -39,6 +41,16 @@ describe('test default request builder behavior with succesful responses', () =>
httpStatusCodesToRetry: [408, 413, 429, 500, 502, 503, 504, 521, 522, 524],
httpMethodsToRetry: ['GET', 'PUT'] as HttpMethod[],
};
const noContentResponse: HttpResponse = {
statusCode: 204,
body: '',
headers: {},
};
const whitespacedResponse: HttpResponse = {
statusCode: 204,
body: ' ',
headers: {},
};
const basicAuth = mockBasicAuthenticationInterface(authParams);
const defaultRequestBuilder = createRequestBuilderFactory<string, boolean>(
mockHttpClientAdapter(),
Expand Down Expand Up @@ -419,8 +431,7 @@ describe('test default request builder behavior with succesful responses', () =>
reqBuilder.validateResponse(false);
await reqBuilder.callAsJson(employeeSchema);
} catch (error) {
const expectedResult =
"Could not parse body as JSON.\n\nExpected 'r' instead of 'e'";
const expectedResult = `Could not parse body as JSON.\n\nExpected 'r' instead of 'e'`;
expect(error.message).toEqual(expectedResult);
}
});
Expand Down Expand Up @@ -473,6 +484,98 @@ describe('test default request builder behavior with succesful responses', () =>
expect(error.message).toEqual(`Response status code was not ok: 400.`);
}
});
it('should test request builder with 400 response code', async () => {
try {
const reqBuilder = defaultRequestBuilder(
'GET',
'/test/requestBuilder/errorResponse'
);
reqBuilder.baseUrl('default');
await reqBuilder.callAsText();
} catch (error) {
expect(error.message).toEqual(`Response status code was not ok: 400.`);
}
});
it('should test response with no content textual types', async () => {
const reqBuilder = customRequestBuilder(noContentResponse);
const { result } = await reqBuilder.callAsText();
expect(result).toEqual('');
});
it('should test response with whitespace content textual types', async () => {
const reqBuilder = customRequestBuilder(whitespacedResponse);
const { result } = await reqBuilder.callAsText();
expect(result).toEqual(' ');
});
it('should test response with no content string cases', async () => {
const reqBuilder = customRequestBuilder(noContentResponse);
const nullableString = await reqBuilder.callAsJson(nullable(string()));
expect(nullableString.result).toEqual(null);

const optionalString = await reqBuilder.callAsJson(optional(string()));
expect(optionalString.result).toEqual(undefined);
});
it('should test response with whitespace content string cases', async () => {
const reqBuilder = customRequestBuilder(whitespacedResponse);
const nullableString = await reqBuilder.callAsJson(nullable(string()));
expect(nullableString.result).toEqual(null);

const optionalString = await reqBuilder.callAsJson(optional(string()));
expect(optionalString.result).toEqual(undefined);
});
it('should test response with no content boolean cases', async () => {
const reqBuilder = customRequestBuilder(noContentResponse);
const nullableString = await reqBuilder.callAsJson(nullable(boolean()));
expect(nullableString.result).toEqual(null);

const optionalString = await reqBuilder.callAsJson(optional(boolean()));
expect(optionalString.result).toEqual(undefined);
});
it('should test response with whitespace content boolean cases', async () => {
const reqBuilder = customRequestBuilder(whitespacedResponse);
const nullableString = await reqBuilder.callAsJson(nullable(boolean()));
expect(nullableString.result).toEqual(null);

const optionalString = await reqBuilder.callAsJson(optional(boolean()));
expect(optionalString.result).toEqual(undefined);
});
it('should test response with no content object cases', async () => {
const reqBuilder = customRequestBuilder(noContentResponse);
const nullableString = await reqBuilder.callAsJson(
nullable(employeeSchema)
);
expect(nullableString.result).toEqual(null);

const optionalString = await reqBuilder.callAsJson(
optional(employeeSchema)
);
expect(optionalString.result).toEqual(undefined);
});
it('should test response with whitespace content object cases', async () => {
const reqBuilder = customRequestBuilder(whitespacedResponse);
const nullableString = await reqBuilder.callAsJson(
nullable(employeeSchema)
);
expect(nullableString.result).toEqual(null);

const optionalString = await reqBuilder.callAsJson(
optional(employeeSchema)
);
expect(optionalString.result).toEqual(undefined);
});

function customRequestBuilder(
response: HttpResponse
): RequestBuilder<string, boolean> {
const reqBuilder = createRequestBuilderFactory<string, boolean>(
mockHttpClientAdapter(response),
(server) => mockBaseURIProvider(server),
ApiError,
basicAuth,
retryConfig
)('GET', '/test/requestBuilder');
reqBuilder.baseUrl('default');
return reqBuilder;
}

function mockBasicAuthenticationInterface({
username,
Expand All @@ -497,16 +600,21 @@ describe('test default request builder behavior with succesful responses', () =>
};
}

function mockHttpClientAdapter(): HttpClientInterface {
function mockHttpClientAdapter(
customResponse?: HttpResponse
): HttpClientInterface {
return async (request, requestOptions) => {
if (typeof customResponse !== 'undefined') {
return customResponse;
}
const iserrorResponse = request.url.startsWith(
'http://apimatic.hopto.org:3000/test/requestBuilder/errorResponse'
);

if (iserrorResponse) {
return await mockErrorResponse(request, requestOptions);
return mockErrorResponse(request, requestOptions);
}
return await mockResponse(request, requestOptions);
return mockResponse(request, requestOptions);
};
}

Expand Down
Loading