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

test: test case for issue #1120 #1121

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
23 changes: 11 additions & 12 deletions source/as-promise.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,17 @@ import {normalizeArguments, mergeOptions} from './normalize-arguments';
import requestAsEventEmitter, {proxyEvents} from './request-as-event-emitter';
import {CancelableRequest, GeneralError, NormalizedOptions, Response} from './types';

const parseBody = (body: Buffer, responseType: NormalizedOptions['responseType'], encoding: NormalizedOptions['encoding']): unknown => {
const parseBody = (kludge: {body: Buffer}, responseType: NormalizedOptions['responseType'], encoding: NormalizedOptions['encoding']): unknown => {
PopGoesTheWza marked this conversation as resolved.
Show resolved Hide resolved
if (responseType === 'json') {
return body.length === 0 ? '' : JSON.parse(body.toString());
return kludge.body.length === 0 ? '' : JSON.parse(kludge.body.toString());
}

if (responseType === 'buffer') {
return Buffer.from(body);
return Buffer.from(kludge.body);
}

if (responseType === 'text') {
return body.toString(encoding);
return kludge.body.toString(encoding);
}

throw new TypeError(`Unknown body type '${responseType as string}'`);
Expand All @@ -35,9 +35,8 @@ export function createRejection(error: Error): CancelableRequest<never> {
return promise;
}

export default function asPromise<T>(options: NormalizedOptions): CancelableRequest<T> {
export default function asPromise<T>(options: NormalizedOptions, kludge = {body: Buffer.from('')}): CancelableRequest<T> {
const proxy = new EventEmitter();
let body: Buffer;

const promise = new PCancelable<Response | Response['body']>((resolve, reject, onCancel) => {
const emitter = requestAsEventEmitter(options);
Expand All @@ -61,7 +60,7 @@ export default function asPromise<T>(options: NormalizedOptions): CancelableRequ

// Download body
try {
body = await getStream.buffer(response, {encoding: 'binary'});
kludge.body = await getStream.buffer(response, {encoding: 'binary'});
} catch (error) {
emitError(new ReadError(error, options));
return;
Expand All @@ -81,10 +80,10 @@ export default function asPromise<T>(options: NormalizedOptions): CancelableRequ

// Parse body
try {
response.body = parseBody(body, options.responseType, options.encoding);
response.body = parseBody(kludge, options.responseType, options.encoding);
} catch (error) {
// Fall back to `utf8`
response.body = body.toString();
response.body = kludge.body.toString();

if (isOk()) {
const parseError = new ParseError(error, response, options);
Expand Down Expand Up @@ -116,7 +115,7 @@ export default function asPromise<T>(options: NormalizedOptions): CancelableRequ
await hook(typedOptions);
}

const promise = asPromise(typedOptions);
const promise = asPromise(typedOptions, kludge);

onCancel(() => {
promise.catch(() => {});
Expand Down Expand Up @@ -160,15 +159,15 @@ export default function asPromise<T>(options: NormalizedOptions): CancelableRequ

const shortcut = <T>(responseType: NormalizedOptions['responseType']): CancelableRequest<T> => {
// eslint-disable-next-line promise/prefer-await-to-then
const newPromise = promise.then(() => parseBody(body, responseType, options.encoding));
const newPromise = promise.then(() => parseBody(kludge, responseType, options.encoding));

Object.defineProperties(newPromise, Object.getOwnPropertyDescriptors(promise));

return newPromise as CancelableRequest<T>;
};

promise.json = () => {
if (is.undefined(body) && is.undefined(options.headers.accept)) {
if (is.undefined(kludge.body) && is.undefined(options.headers.accept)) {
options.headers.accept = 'application/json';
}

Expand Down
93 changes: 93 additions & 0 deletions test/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,99 @@ test('afterResponse allows to retry', withServer, async (t, server, got) => {
t.is(statusCode, 200);
});

test.failing('afterResponse with retry has correct `.text()`', withServer, async (t, server, got) => {
server.get('/', (request, response) => {
if (request.headers.token === 'unicorn') {
response.end('hello world');
} else {
response.statusCode = 401;
response.end('hello nasty');
}
});

const body = await got({
hooks: {
afterResponse: [
(response, retryWithMergedOptions) => {
if (response.statusCode === 401) {
return retryWithMergedOptions({
headers: {
token: 'unicorn'
}
});
}

return response;
}
]
}
}).text();

t.is(body, 'hello world');
});

test.failing('afterResponse with retry has correct `.json()`', withServer, async (t, server, got) => {
server.get('/', (request, response) => {
if (request.headers.token === 'unicorn') {
response.end(JSON.stringify({hello: 'world'}));
} else {
response.statusCode = 401;
response.end(JSON.stringify({hello: 'nasty'}));
}
});

const body = await got({
hooks: {
afterResponse: [
(response, retryWithMergedOptions) => {
if (response.statusCode === 401) {
return retryWithMergedOptions({
headers: {
token: 'unicorn'
}
});
}

return response;
}
]
}
}).json() as any;

t.is(body.hello, 'world');
});

test.failing('afterResponse with retry has correct `.buffer()`', withServer, async (t, server, got) => {
server.get('/', (request, response) => {
if (request.headers.token === 'unicorn') {
response.end('hello world');
} else {
response.statusCode = 401;
response.end('hello nasty');
}
});

const body = await got({
hooks: {
afterResponse: [
(response, retryWithMergedOptions) => {
if (response.statusCode === 401) {
return retryWithMergedOptions({
headers: {
token: 'unicorn'
}
});
}

return response;
}
]
}
}).buffer();

t.is(body.toString(), 'hello world');
});

test('cancelling the request after retrying in a afterResponse hook', withServer, async (t, server, got) => {
let requests = 0;
server.get('/', (_request, response) => {
Expand Down