Browse Source

Use `@sindresorhus/is` for type checking (#422)

fix-progress-browserify
Brandon Smith 7 years ago
committed by Sindre Sorhus
parent
commit
9495256aa0
  1. 55
      index.js
  2. 3
      package.json
  3. 3
      test/http.js
  4. 3
      test/progress.js
  5. 5
      test/stream.js

55
index.js

@ -10,7 +10,7 @@ const querystring = require('querystring');
const CacheableRequest = require('cacheable-request'); const CacheableRequest = require('cacheable-request');
const duplexer3 = require('duplexer3'); const duplexer3 = require('duplexer3');
const intoStream = require('into-stream'); const intoStream = require('into-stream');
const isStream = require('is-stream'); const is = require('@sindresorhus/is');
const getStream = require('get-stream'); const getStream = require('get-stream');
const timedOut = require('timed-out'); const timedOut = require('timed-out');
const urlParseLax = require('url-parse-lax'); const urlParseLax = require('url-parse-lax');
@ -20,7 +20,6 @@ const decompressResponse = require('decompress-response');
const mimicResponse = require('mimic-response'); const mimicResponse = require('mimic-response');
const isRetryAllowed = require('is-retry-allowed'); const isRetryAllowed = require('is-retry-allowed');
const isURL = require('isurl'); const isURL = require('isurl');
const isPlainObj = require('is-plain-obj');
const PCancelable = require('p-cancelable'); const PCancelable = require('p-cancelable');
const pTimeout = require('p-timeout'); const pTimeout = require('p-timeout');
const pify = require('pify'); const pify = require('pify');
@ -30,7 +29,7 @@ const pkg = require('./package.json');
const getMethodRedirectCodes = new Set([300, 301, 302, 303, 304, 305, 307, 308]); const getMethodRedirectCodes = new Set([300, 301, 302, 303, 304, 305, 307, 308]);
const allMethodRedirectCodes = new Set([300, 303, 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 getBodySize = opts => {
const body = opts.body; const body = opts.body;
@ -43,7 +42,7 @@ const getBodySize = opts => {
return 0; return 0;
} }
if (typeof body === 'string') { if (is.string(body)) {
return Buffer.byteLength(body); return Buffer.byteLength(body);
} }
@ -55,7 +54,7 @@ const getBodySize = opts => {
return pify(fs.stat)(body.path).then(stat => stat.size); 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; return body._buffer.length;
} }
@ -68,7 +67,7 @@ function requestAsEventEmitter(opts) {
const ee = new EventEmitter(); const ee = new EventEmitter();
const requestUrl = opts.href || urlLib.resolve(urlLib.format(opts), opts.path); const requestUrl = opts.href || urlLib.resolve(urlLib.format(opts), opts.path);
const redirects = []; const redirects = [];
const agents = typeof opts.agent === 'object' ? opts.agent : null; const agents = is.object(opts.agent) ? opts.agent : null;
let retryCount = 0; let retryCount = 0;
let redirectUrl; let redirectUrl;
let uploadBodySize; let uploadBodySize;
@ -179,7 +178,7 @@ function requestAsEventEmitter(opts) {
progressStream.redirectUrls = redirects; progressStream.redirectUrls = redirects;
const response = opts.decompress === true && const response = opts.decompress === true &&
typeof decompressResponse === 'function' && is.function(decompressResponse) &&
opts.method !== 'HEAD' ? decompressResponse(progressStream) : progressStream; opts.method !== 'HEAD' ? decompressResponse(progressStream) : progressStream;
if (!opts.decompress && ['gzip', 'deflate'].indexOf(res.headers['content-encoding']) !== -1) { if (!opts.decompress && ['gzip', 'deflate'].indexOf(res.headers['content-encoding']) !== -1) {
@ -305,7 +304,7 @@ function asPromise(opts) {
req.abort(); req.abort();
}); });
if (isStream(opts.body)) { if (is.nodeStream(opts.body)) {
opts.body.pipe(req); opts.body.pipe(req);
opts.body = undefined; opts.body = undefined;
return; return;
@ -315,7 +314,7 @@ function asPromise(opts) {
}); });
ee.on('response', res => { 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 stream
.catch(err => reject(new got.ReadError(err, opts))) .catch(err => reject(new got.ReadError(err, opts)))
@ -394,7 +393,7 @@ function asStream(opts) {
ee.on('request', req => { ee.on('request', req => {
proxy.emit('request', req); proxy.emit('request', req);
if (isStream(opts.body)) { if (is.nodeStream(opts.body)) {
opts.body.pipe(req); opts.body.pipe(req);
return; return;
} }
@ -436,9 +435,9 @@ function asStream(opts) {
} }
function normalizeArguments(url, opts) { function normalizeArguments(url, opts) {
if (typeof url !== 'string' && typeof url !== 'object') { if (!is.string(url) && !is.object(url)) {
throw new TypeError(`Parameter \`url\` must be a string or object, not ${typeof url}`); throw new TypeError(`Parameter \`url\` must be a string or object, not ${is(url)}`);
} else if (typeof url === 'string') { } else if (is.string(url)) {
url = url.replace(/^unix:/, 'http://$&'); url = url.replace(/^unix:/, 'http://$&');
url = urlParseLax(url); url = urlParseLax(url);
if (url.auth) { if (url.auth) {
@ -465,7 +464,7 @@ function normalizeArguments(url, opts) {
const headers = lowercaseKeys(opts.headers); const headers = lowercaseKeys(opts.headers);
for (const key of Object.keys(headers)) { for (const key of Object.keys(headers)) {
if (headers[key] === null || headers[key] === undefined) { if (is.nullOrUndefined(headers[key])) {
delete headers[key]; delete headers[key];
} }
} }
@ -478,7 +477,7 @@ function normalizeArguments(url, opts) {
const query = opts.query; const query = opts.query;
if (query) { if (query) {
if (typeof query !== 'string') { if (!is.string(query)) {
opts.query = querystring.stringify(query); opts.query = querystring.stringify(query);
} }
@ -486,18 +485,20 @@ function normalizeArguments(url, opts) {
delete 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'; opts.headers.accept = 'application/json';
} }
const body = opts.body; const body = opts.body;
if (body !== null && body !== undefined) { if (is.nullOrUndefined(body)) {
opts.method = (opts.method || 'GET').toUpperCase();
} else {
const headers = opts.headers; 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'); 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) { 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'); throw new TypeError('The `body` option must be a plain Object or Array when the `form` or `json` option is used');
} }
@ -513,21 +514,19 @@ function normalizeArguments(url, opts) {
opts.body = JSON.stringify(body); opts.body = JSON.stringify(body);
} }
if (headers['content-length'] === undefined && headers['transfer-encoding'] === undefined && !isStream(body)) { if (is.undefined(headers['content-length']) && is.undefined(headers['transfer-encoding']) && !is.nodeStream(body)) {
const length = typeof opts.body === 'string' ? Buffer.byteLength(opts.body) : opts.body.length; const length = is.string(opts.body) ? Buffer.byteLength(opts.body) : opts.body.length;
headers['content-length'] = length; headers['content-length'] = length;
} }
// Convert buffer to stream to receive upload progress events // Convert buffer to stream to receive upload progress events
// see https://github.com/sindresorhus/got/pull/322 // see https://github.com/sindresorhus/got/pull/322
if (Buffer.isBuffer(body)) { if (is.buffer(body)) {
opts.body = intoStream(body); opts.body = intoStream(body);
opts.body._buffer = body; opts.body._buffer = body;
} }
opts.method = (opts.method || 'POST').toUpperCase(); opts.method = (opts.method || 'POST').toUpperCase();
} else {
opts.method = (opts.method || 'GET').toUpperCase();
} }
if (opts.hostname === 'unix') { if (opts.hostname === 'unix') {
@ -540,7 +539,7 @@ function normalizeArguments(url, opts) {
} }
} }
if (typeof opts.retries !== 'function') { if (!is.function(opts.retries)) {
const retries = opts.retries; const retries = opts.retries;
opts.retries = (iter, err) => { opts.retries = (iter, err) => {
@ -554,12 +553,12 @@ function normalizeArguments(url, opts) {
}; };
} }
if (opts.followRedirect === undefined) { if (is.undefined(opts.followRedirect)) {
opts.followRedirect = true; opts.followRedirect = true;
} }
if (opts.timeout) { if (opts.timeout) {
if (typeof opts.timeout === 'number') { if (is.number(opts.timeout)) {
opts.gotTimeout = {request: opts.timeout}; opts.gotTimeout = {request: opts.timeout};
} else { } else {
opts.gotTimeout = opts.timeout; opts.gotTimeout = opts.timeout;
@ -600,7 +599,7 @@ class StdError extends Error {
Error.captureStackTrace(this, this.constructor); Error.captureStackTrace(this, this.constructor);
this.name = 'StdError'; this.name = 'StdError';
if (error.code !== undefined) { if (!is.undefined(error.code)) {
this.code = error.code; this.code = error.code;
} }

3
package.json

@ -50,14 +50,13 @@
"electron" "electron"
], ],
"dependencies": { "dependencies": {
"@sindresorhus/is": "^0.6.0",
"cacheable-request": "^2.1.1", "cacheable-request": "^2.1.1",
"decompress-response": "^3.3.0", "decompress-response": "^3.3.0",
"duplexer3": "^0.1.4", "duplexer3": "^0.1.4",
"get-stream": "^3.0.0", "get-stream": "^3.0.0",
"into-stream": "^3.1.0", "into-stream": "^3.1.0",
"is-plain-obj": "^1.1.0",
"is-retry-allowed": "^1.1.0", "is-retry-allowed": "^1.1.0",
"is-stream": "^1.1.0",
"isurl": "^1.0.0-alpha5", "isurl": "^1.0.0-alpha5",
"lowercase-keys": "^1.0.0", "lowercase-keys": "^1.0.0",
"mimic-response": "^1.0.0", "mimic-response": "^1.0.0",

3
test/http.js

@ -1,3 +1,4 @@
import is from '@sindresorhus/is';
import test from 'ava'; import test from 'ava';
import got from '..'; import got from '..';
import {createServer} from './helpers/server'; import {createServer} from './helpers/server';
@ -66,7 +67,7 @@ test('invalid protocol throws', async t => {
test('buffer on encoding === null', async t => { test('buffer on encoding === null', async t => {
const data = (await got(s.url, {encoding: null})).body; const data = (await got(s.url, {encoding: null})).body;
t.truthy(Buffer.isBuffer(data)); t.true(is.buffer(data));
}); });
test('query option', async t => { test('query option', async t => {

3
test/progress.js

@ -5,6 +5,7 @@ import getStream from 'get-stream';
import FormData from 'form-data'; import FormData from 'form-data';
import tempfile from 'tempfile'; import tempfile from 'tempfile';
import pify from 'pify'; import pify from 'pify';
import is from '@sindresorhus/is';
import test from 'ava'; import test from 'ava';
import got from '..'; import got from '..';
import {createServer} from './helpers/server'; import {createServer} from './helpers/server';
@ -12,7 +13,7 @@ import {createServer} from './helpers/server';
const checkEvents = (t, events, bodySize = null) => { const checkEvents = (t, events, bodySize = null) => {
t.true(events.length >= 2); t.true(events.length >= 2);
const hasBodySize = typeof bodySize === 'number'; const hasBodySize = is.number(bodySize);
let lastEvent = events.shift(); let lastEvent = events.shift();
if (!hasBodySize) { if (!hasBodySize) {

5
test/stream.js

@ -2,6 +2,7 @@ import test from 'ava';
import intoStream from 'into-stream'; import intoStream from 'into-stream';
import getStream from 'get-stream'; import getStream from 'get-stream';
import pEvent from 'p-event'; import pEvent from 'p-event';
import is from '@sindresorhus/is';
import got from '..'; import got from '..';
import {createServer} from './helpers/server'; import {createServer} from './helpers/server';
@ -96,8 +97,8 @@ test('redirect response contains old url', async t => {
test('check for pipe method', t => { test('check for pipe method', t => {
const stream = got.stream(`${s.url}/`); const stream = got.stream(`${s.url}/`);
t.is(typeof stream.pipe, 'function'); t.true(is.function(stream.pipe));
t.is(typeof stream.on('error', () => {}).pipe, 'function'); t.true(is.function(stream.on('error', () => {}).pipe));
}); });
test('piping works', async t => { test('piping works', async t => {

Loading…
Cancel
Save