Skip to content

Commit

Permalink
Use @sindresorhus/is for type checking (#422)
Browse files Browse the repository at this point in the history
  • Loading branch information
brandon93s authored and sindresorhus committed Nov 20, 2017
1 parent 570ff68 commit 9495256
Show file tree
Hide file tree
Showing 5 changed files with 35 additions and 34 deletions.
55 changes: 27 additions & 28 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const querystring = require('querystring');
const CacheableRequest = require('cacheable-request');
const duplexer3 = require('duplexer3');
const intoStream = require('into-stream');
const isStream = require('is-stream');
const is = require('@sindresorhus/is');
const getStream = require('get-stream');
const timedOut = require('timed-out');
const urlParseLax = require('url-parse-lax');
Expand All @@ -20,7 +20,6 @@ const decompressResponse = require('decompress-response');
const mimicResponse = require('mimic-response');
const isRetryAllowed = require('is-retry-allowed');
const isURL = require('isurl');
const isPlainObj = require('is-plain-obj');
const PCancelable = require('p-cancelable');
const pTimeout = require('p-timeout');
const pify = require('pify');
Expand All @@ -30,7 +29,7 @@ const pkg = require('./package.json');
const getMethodRedirectCodes = new Set([300, 301, 302, 303, 304, 305, 307, 308]);
const allMethodRedirectCodes = new Set([300, 303, 307, 308]);

const isFormData = body => isStream(body) && typeof body.getBoundary === 'function';
const isFormData = body => is.nodeStream(body) && is.function(body.getBoundary);

const getBodySize = opts => {
const body = opts.body;
Expand All @@ -43,7 +42,7 @@ const getBodySize = opts => {
return 0;
}

if (typeof body === 'string') {
if (is.string(body)) {
return Buffer.byteLength(body);
}

Expand All @@ -55,7 +54,7 @@ const getBodySize = opts => {
return pify(fs.stat)(body.path).then(stat => stat.size);
}

if (isStream(body) && Buffer.isBuffer(body._buffer)) {
if (is.nodeStream(body) && is.buffer(body._buffer)) {
return body._buffer.length;
}

Expand All @@ -68,7 +67,7 @@ function requestAsEventEmitter(opts) {
const ee = new EventEmitter();
const requestUrl = opts.href || urlLib.resolve(urlLib.format(opts), opts.path);
const redirects = [];
const agents = typeof opts.agent === 'object' ? opts.agent : null;
const agents = is.object(opts.agent) ? opts.agent : null;
let retryCount = 0;
let redirectUrl;
let uploadBodySize;
Expand Down Expand Up @@ -179,7 +178,7 @@ function requestAsEventEmitter(opts) {
progressStream.redirectUrls = redirects;

const response = opts.decompress === true &&
typeof decompressResponse === 'function' &&
is.function(decompressResponse) &&
opts.method !== 'HEAD' ? decompressResponse(progressStream) : progressStream;

if (!opts.decompress && ['gzip', 'deflate'].indexOf(res.headers['content-encoding']) !== -1) {
Expand Down Expand Up @@ -305,7 +304,7 @@ function asPromise(opts) {
req.abort();
});

if (isStream(opts.body)) {
if (is.nodeStream(opts.body)) {
opts.body.pipe(req);
opts.body = undefined;
return;
Expand All @@ -315,7 +314,7 @@ function asPromise(opts) {
});

ee.on('response', res => {
const stream = opts.encoding === null ? getStream.buffer(res) : getStream(res, opts);
const stream = is.null(opts.encoding) ? getStream.buffer(res) : getStream(res, opts);

stream
.catch(err => reject(new got.ReadError(err, opts)))
Expand Down Expand Up @@ -394,7 +393,7 @@ function asStream(opts) {
ee.on('request', req => {
proxy.emit('request', req);

if (isStream(opts.body)) {
if (is.nodeStream(opts.body)) {
opts.body.pipe(req);
return;
}
Expand Down Expand Up @@ -436,9 +435,9 @@ function asStream(opts) {
}

function normalizeArguments(url, opts) {
if (typeof url !== 'string' && typeof url !== 'object') {
throw new TypeError(`Parameter \`url\` must be a string or object, not ${typeof url}`);
} else if (typeof url === 'string') {
if (!is.string(url) && !is.object(url)) {
throw new TypeError(`Parameter \`url\` must be a string or object, not ${is(url)}`);
} else if (is.string(url)) {
url = url.replace(/^unix:/, 'http://$&');
url = urlParseLax(url);
if (url.auth) {
Expand All @@ -465,7 +464,7 @@ function normalizeArguments(url, opts) {

const headers = lowercaseKeys(opts.headers);
for (const key of Object.keys(headers)) {
if (headers[key] === null || headers[key] === undefined) {
if (is.nullOrUndefined(headers[key])) {
delete headers[key];
}
}
Expand All @@ -478,26 +477,28 @@ function normalizeArguments(url, opts) {
const query = opts.query;

if (query) {
if (typeof query !== 'string') {
if (!is.string(query)) {
opts.query = querystring.stringify(query);
}

opts.path = `${opts.path.split('?')[0]}?${opts.query}`;
delete opts.query;
}

if (opts.json && opts.headers.accept === undefined) {
if (opts.json && is.undefined(opts.headers.accept)) {
opts.headers.accept = 'application/json';
}

const body = opts.body;
if (body !== null && body !== undefined) {
if (is.nullOrUndefined(body)) {
opts.method = (opts.method || 'GET').toUpperCase();
} else {
const headers = opts.headers;
if (!isStream(body) && typeof body !== 'string' && !Buffer.isBuffer(body) && !(opts.form || opts.json)) {
if (!is.nodeStream(body) && !is.string(body) && !is.buffer(body) && !(opts.form || opts.json)) {
throw new TypeError('The `body` option must be a stream.Readable, string, Buffer or plain Object');
}

const canBodyBeStringified = isPlainObj(body) || Array.isArray(body);
const canBodyBeStringified = is.plainObject(body) || is.array(body);
if ((opts.form || opts.json) && !canBodyBeStringified) {
throw new TypeError('The `body` option must be a plain Object or Array when the `form` or `json` option is used');
}
Expand All @@ -513,21 +514,19 @@ function normalizeArguments(url, opts) {
opts.body = JSON.stringify(body);
}

if (headers['content-length'] === undefined && headers['transfer-encoding'] === undefined && !isStream(body)) {
const length = typeof opts.body === 'string' ? Buffer.byteLength(opts.body) : opts.body.length;
if (is.undefined(headers['content-length']) && is.undefined(headers['transfer-encoding']) && !is.nodeStream(body)) {
const length = is.string(opts.body) ? Buffer.byteLength(opts.body) : opts.body.length;
headers['content-length'] = length;
}

// Convert buffer to stream to receive upload progress events
// see https://github.com/sindresorhus/got/pull/322
if (Buffer.isBuffer(body)) {
if (is.buffer(body)) {
opts.body = intoStream(body);
opts.body._buffer = body;
}

opts.method = (opts.method || 'POST').toUpperCase();
} else {
opts.method = (opts.method || 'GET').toUpperCase();
}

if (opts.hostname === 'unix') {
Expand All @@ -540,7 +539,7 @@ function normalizeArguments(url, opts) {
}
}

if (typeof opts.retries !== 'function') {
if (!is.function(opts.retries)) {
const retries = opts.retries;

opts.retries = (iter, err) => {
Expand All @@ -554,12 +553,12 @@ function normalizeArguments(url, opts) {
};
}

if (opts.followRedirect === undefined) {
if (is.undefined(opts.followRedirect)) {
opts.followRedirect = true;
}

if (opts.timeout) {
if (typeof opts.timeout === 'number') {
if (is.number(opts.timeout)) {
opts.gotTimeout = {request: opts.timeout};
} else {
opts.gotTimeout = opts.timeout;
Expand Down Expand Up @@ -600,7 +599,7 @@ class StdError extends Error {
Error.captureStackTrace(this, this.constructor);
this.name = 'StdError';

if (error.code !== undefined) {
if (!is.undefined(error.code)) {
this.code = error.code;
}

Expand Down
3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,14 +50,13 @@
"electron"
],
"dependencies": {
"@sindresorhus/is": "^0.6.0",
"cacheable-request": "^2.1.1",
"decompress-response": "^3.3.0",
"duplexer3": "^0.1.4",
"get-stream": "^3.0.0",
"into-stream": "^3.1.0",
"is-plain-obj": "^1.1.0",
"is-retry-allowed": "^1.1.0",
"is-stream": "^1.1.0",
"isurl": "^1.0.0-alpha5",
"lowercase-keys": "^1.0.0",
"mimic-response": "^1.0.0",
Expand Down
3 changes: 2 additions & 1 deletion test/http.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import is from '@sindresorhus/is';
import test from 'ava';
import got from '..';
import {createServer} from './helpers/server';
Expand Down Expand Up @@ -66,7 +67,7 @@ test('invalid protocol throws', async t => {

test('buffer on encoding === null', async t => {
const data = (await got(s.url, {encoding: null})).body;
t.truthy(Buffer.isBuffer(data));
t.true(is.buffer(data));
});

test('query option', async t => {
Expand Down
3 changes: 2 additions & 1 deletion test/progress.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@ import getStream from 'get-stream';
import FormData from 'form-data';
import tempfile from 'tempfile';
import pify from 'pify';
import is from '@sindresorhus/is';
import test from 'ava';
import got from '..';
import {createServer} from './helpers/server';

const checkEvents = (t, events, bodySize = null) => {
t.true(events.length >= 2);

const hasBodySize = typeof bodySize === 'number';
const hasBodySize = is.number(bodySize);
let lastEvent = events.shift();

if (!hasBodySize) {
Expand Down
5 changes: 3 additions & 2 deletions test/stream.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import test from 'ava';
import intoStream from 'into-stream';
import getStream from 'get-stream';
import pEvent from 'p-event';
import is from '@sindresorhus/is';
import got from '..';
import {createServer} from './helpers/server';

Expand Down Expand Up @@ -96,8 +97,8 @@ test('redirect response contains old url', async t => {

test('check for pipe method', t => {
const stream = got.stream(`${s.url}/`);
t.is(typeof stream.pipe, 'function');
t.is(typeof stream.on('error', () => {}).pipe, 'function');
t.true(is.function(stream.pipe));
t.true(is.function(stream.on('error', () => {}).pipe));
});

test('piping works', async t => {
Expand Down

0 comments on commit 9495256

Please sign in to comment.