Skip to content

Commit

Permalink
Minor tweaks
Browse files Browse the repository at this point in the history
  • Loading branch information
sindresorhus committed Jun 20, 2019
1 parent 2ea817c commit 3fdabce
Show file tree
Hide file tree
Showing 8 changed files with 36 additions and 30 deletions.
4 changes: 3 additions & 1 deletion source/as-promise.ts
Expand Up @@ -127,7 +127,9 @@ export default function asPromise(options: NormalizedOptions): CancelableRequest
'redirect',
'uploadProgress',
'downloadProgress'
].forEach(event => emitter.on(event, (...args: unknown[]) => proxy.emit(event, ...args)));
].forEach(event => emitter.on(event, (...args: unknown[]) => {
proxy.emit(event, ...args);
}));
}) as CancelableRequest<ResponeReturn>;

promise.on = (name, fn) => {
Expand Down
4 changes: 3 additions & 1 deletion source/as-stream.ts
Expand Up @@ -96,7 +96,9 @@ export default function asStream(options: NormalizedOptions): ProxyStream {
'redirect',
'uploadProgress',
'downloadProgress'
].forEach(event => emitter.on(event, (...args) => proxy.emit(event, ...args)));
].forEach(event => emitter.on(event, (...args) => {
proxy.emit(event, ...args);
}));

const pipe = proxy.pipe.bind(proxy);
const unpipe = proxy.unpipe.bind(proxy);
Expand Down
2 changes: 1 addition & 1 deletion source/errors.ts
Expand Up @@ -10,7 +10,7 @@ export class GotError extends Error {

readonly options!: NormalizedOptions;

constructor(message: string, error: (Error & { code?: string }) | { code?: string }, options: NormalizedOptions) {
constructor(message: string, error: (Error & {code?: string}) | {code?: string}, options: NormalizedOptions) {
super(message);
Error.captureStackTrace(this, this.constructor);
this.name = 'GotError';
Expand Down
6 changes: 3 additions & 3 deletions source/merge.ts
Expand Up @@ -42,10 +42,10 @@ export default function merge<Target extends Record<string, unknown>, Source ext
return target as Target & Source;
}

export function mergeOptions<T extends Options>(...sources: T[]): T & { hooks: Partial<Hooks> } {
const mergedOptions = merge({} as T & { hooks: Partial<Hooks> }, ...sources.map(source => source || {}));
export function mergeOptions<T extends Options>(...sources: T[]): T & {hooks: Partial<Hooks>} {
const mergedOptions = merge({} as T & {hooks: Partial<Hooks>}, ...sources.map(source => source || {}));

const hooks = knownHookEvents.reduce((acc, current) => ({...acc, [current]: []}), {}) as Record<HookEvent, HookType[]>;
const hooks = knownHookEvents.reduce((accumulator, current) => ({...accumulator, [current]: []}), {}) as Record<HookEvent, HookType[]>;

for (const source of sources) {
// We need to check `source` to allow calling `.extend()` with no arguments.
Expand Down
37 changes: 19 additions & 18 deletions source/normalize-arguments.ts
Expand Up @@ -26,7 +26,7 @@ import {HTTPError, ParseError, MaxRedirectsError, GotError} from './errors';

const retryAfterStatusCodes: ReadonlySet<StatusCode> = new Set([413, 429, 503]);

let shownDeprecation = false;
let hasShownDeprecation = false;

// `preNormalize` handles static options (e.g. headers).
// For example, when you create a custom instance and make a request
Expand Down Expand Up @@ -122,13 +122,13 @@ export const preNormalizeArguments = (options: Options, defaults?: Options): Nor
};

export const normalizeArguments = (url: URLOrOptions, options: NormalizedOptions, defaults?: Defaults): NormalizedOptions => {
let urlArg: URLArgument;
let urlArgument: URLArgument;
if (is.plainObject(url)) {
options = {...url, ...options};
urlArg = options.url || '';
urlArgument = options.url || '';
delete options.url;
} else {
urlArg = url;
urlArgument = url;
}

if (defaults) {
Expand All @@ -137,34 +137,34 @@ export const normalizeArguments = (url: URLOrOptions, options: NormalizedOptions
options = merge({}, preNormalizeArguments(options));
}

if (!is.string(urlArg) && !is.object(urlArg)) {
throw new TypeError(`Parameter \`url\` must be a string or object, not ${is(urlArg)}`);
if (!is.string(urlArgument) && !is.object(urlArgument)) {
throw new TypeError(`Parameter \`url\` must be a string or object, not ${is(urlArgument)}`);
}

let urlObj: https.RequestOptions | URLOptions;
if (is.string(urlArg)) {
if (is.string(urlArgument)) {
if (options.baseUrl) {
if (urlArg.startsWith('/')) {
urlArg = urlArg.slice(1);
if (urlArgument.startsWith('/')) {
urlArgument = urlArgument.slice(1);
}
} else {
urlArg = urlArg.replace(/^unix:/, 'http://$&');
urlArgument = urlArgument.replace(/^unix:/, 'http://$&');
}

urlObj = urlArg || options.baseUrl ? urlToOptions(new URL(urlArg, options.baseUrl)) : {};
} else if (is.urlInstance(urlArg)) {
urlObj = urlToOptions(urlArg);
urlObj = urlArgument || options.baseUrl ? urlToOptions(new URL(urlArgument, options.baseUrl)) : {};
} else if (is.urlInstance(urlArgument)) {
urlObj = urlToOptions(urlArgument);
} else {
urlObj = urlArg;
urlObj = urlArgument;
}

// Override both null/undefined with default protocol
options = merge<NormalizedOptions, Partial<URL | URLOptions | NormalizedOptions | Options>>({path: ''} as NormalizedOptions, urlObj, {protocol: urlObj.protocol || 'https:'}, options);

for (const hook of options.hooks.init) {
const called = hook(options);
const isCalled = hook(options);

if (is.promise(called)) {
if (is.promise(isCalled)) {
throw new TypeError('The `init` hook must be a synchronous function');
}
}
Expand All @@ -180,10 +180,11 @@ export const normalizeArguments = (url: URLOrOptions, options: NormalizedOptions
let {searchParams} = options;
delete options.searchParams;

// TODO: Remove this before Got v11
if (options.query) {
if (!shownDeprecation) {
if (!hasShownDeprecation) {
console.warn('`options.query` is deprecated. We support it solely for compatibility - it will be removed in Got 11. Use `options.searchParams` instead.');
shownDeprecation = true;
hasShownDeprecation = true;
}

searchParams = options.query;
Expand Down
4 changes: 3 additions & 1 deletion source/types/mimic-response.d.ts
Expand Up @@ -2,5 +2,7 @@ declare module 'mimic-response' {
import {IncomingMessage} from 'http';
import {Transform as TransformStream} from 'stream';

export default function(input: IncomingMessage, output: TransformStream): void;
declare function mimicResponse(input: IncomingMessage, output: TransformStream): void;

export = mimicResponse;
}
3 changes: 1 addition & 2 deletions source/utils/get-body-size.ts
Expand Up @@ -22,8 +22,7 @@ export default async (options: Options): Promise<number | undefined> => {
}

if (isFormData(body)) {
// TS thinks this returns Promise<void> when it actually returns a number
return promisify(body.getLength.bind(body))() as unknown as number;
return promisify(body.getLength.bind(body))();
}

if (body instanceof ReadStream) {
Expand Down
6 changes: 3 additions & 3 deletions test/retry.ts
Expand Up @@ -102,7 +102,6 @@ test('custom retries', withServer, async (t, server, got) => {
]
}
}));
// @ts-ignore
t.is(error.response.statusCode, 500);
t.true(tried);
});
Expand All @@ -123,7 +122,9 @@ test('custom error codes', withServer, async (t, server, got) => {
const error = new Error('Snap!');
// @ts-ignore
error.code = errorCode;
setTimeout(() => emitter.emit('error', error));
setTimeout(() => {
emitter.emit('error', error);
});

return emitter;
},
Expand All @@ -141,7 +142,6 @@ test('custom error codes', withServer, async (t, server, got) => {
}
}));

// @ts-ignore
t.is(error.code, errorCode);
});

Expand Down

0 comments on commit 3fdabce

Please sign in to comment.