Browse Source

Readme and error message tweaks

update-cacheable-request
Sindre Sorhus 7 years ago
parent
commit
a4facf311d
  1. 14
      index.js
  2. 83
      readme.md
  3. 2
      test/arguments.js
  4. 2
      test/cache.js
  5. 2
      test/error.js
  6. 2
      test/redirects.js
  7. 4
      test/stream.js

14
index.js

@ -19,13 +19,13 @@ const lowercaseKeys = require('lowercase-keys');
const decompressResponse = require('decompress-response'); 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 Buffer = require('safe-buffer').Buffer;
const isURL = require('isurl'); const isURL = require('isurl');
const isPlainObj = require('is-plain-obj'); 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');
const pkg = require('./package'); const Buffer = require('safe-buffer').Buffer;
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]);
@ -380,12 +380,12 @@ function asStream(opts) {
} }
if (opts.json) { if (opts.json) {
throw new Error('got can not be used as stream when options.json is used'); throw new Error('Got can not be used as a stream when the `json` option is used');
} }
if (opts.body) { if (opts.body) {
proxy.write = () => { proxy.write = () => {
throw new Error('got\'s stream is not writable when options.body is used'); throw new Error('Got\'s stream is not writable when the `body` option is used');
}; };
} }
@ -442,7 +442,7 @@ function normalizeArguments(url, opts) {
url = url.replace(/^unix:/, 'http://$&'); url = url.replace(/^unix:/, 'http://$&');
url = urlParseLax(url); url = urlParseLax(url);
if (url.auth) { if (url.auth) {
throw new Error('Basic authentication must be done with auth option'); throw new Error('Basic authentication must be done with the `auth` option');
} }
} else if (isURL.lenient(url)) { } else if (isURL.lenient(url)) {
url = urlToOptions(url); url = urlToOptions(url);
@ -494,12 +494,12 @@ function normalizeArguments(url, opts) {
if (body !== null && body !== undefined) { if (body !== null && body !== undefined) {
const headers = opts.headers; const headers = opts.headers;
if (!isStream(body) && typeof body !== 'string' && !Buffer.isBuffer(body) && !(opts.form || opts.json)) { if (!isStream(body) && typeof body !== 'string' && !Buffer.isBuffer(body) && !(opts.form || opts.json)) {
throw new TypeError('options.body must be a ReadableStream, 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 = isPlainObj(body) || Array.isArray(body);
if ((opts.form || opts.json) && !canBodyBeStringified) { if ((opts.form || opts.json) && !canBodyBeStringified) {
throw new TypeError('options.body must be a plain Object or Array when options.form or options.json is used'); throw new TypeError('The `body` option must be a plain Object or Array when the `form` or `json` option is used');
} }
if (isFormData(body)) { if (isFormData(body)) {

83
readme.md

@ -41,30 +41,36 @@ $ npm install got
## Usage ## Usage
```js ```js
const fs = require('fs');
const got = require('got'); const got = require('got');
got('sindresorhus.com') (async () => {
.then(response => { try {
const response = await got('sindresorhus.com');
console.log(response.body); console.log(response.body);
//=> '<!doctype html> ...' //=> '<!doctype html> ...'
}) } catch (error) {
.catch(error => {
console.log(error.response.body); console.log(error.response.body);
//=> 'Internal server error ...' //=> 'Internal server error ...'
}); }
})();
```
###### Streams
```js
const fs = require('fs');
const got = require('got');
// Streams
got.stream('sindresorhus.com').pipe(fs.createWriteStream('index.html')); got.stream('sindresorhus.com').pipe(fs.createWriteStream('index.html'));
// For POST, PUT and PATCH methods got.stream returns a WritableStream // For POST, PUT, and PATCH methods `got.stream` returns a `stream.Writable`
fs.createReadStream('index.html').pipe(got.stream.post('sindresorhus.com')); fs.createReadStream('index.html').pipe(got.stream.post('sindresorhus.com'));
``` ```
### API ### API
It's a `GET` request by default, but can be changed in `options`. It's a `GET` request by default, but can be changed by using different methods or in the `options`.
#### got(url, [options]) #### got(url, [options])
@ -235,16 +241,17 @@ If it's not possible to retrieve the body size (can happen when streaming), `tot
**Note**: Progress events can also be used with promises. **Note**: Progress events can also be used with promises.
```js ```js
got('sindresorhus.com') (async () => {
.on('downloadProgress', progress => { const response = await got('sindresorhus.com')
// Report download progress .on('downloadProgress', progress => {
}) // Report download progress
.on('uploadProgress', progress => { })
// Report upload progress .on('uploadProgress', progress => {
}) // Report upload progress
.then(response => { });
// Done
}); console.log(response);
})();
``` ```
##### .on('error', error, body, response) ##### .on('error', error, body, response)
@ -305,36 +312,30 @@ When the request is aborted with `.cancel()`.
The promise returned by Got has a [`.cancel()`](https://github.com/sindresorhus/p-cancelable) method which, when called, aborts the request. The promise returned by Got has a [`.cancel()`](https://github.com/sindresorhus/p-cancelable) method which, when called, aborts the request.
```js ```js
const request = got(url, options); (async () => {
const request = got(url, options);
request.catch(err => {
if (request.canceled) {
// Handle cancelation
}
// Handle other errors // In another part of the code
}); if (something) {
request.cancel();
request.cancel(); }
```
Or
```js try {
const request = got(url, options); await request;
} catch (error) {
if (request.canceled) { // Or `error instanceof got.CancelError`
// Handle cancelation
}
request.catch(err => { // Handle other errors
if (err instanceof got.CancelError) {
// Handle cancelation
} }
})();
// Handle other errors
});
request.cancel();
``` ```
<a name="cache-adapters"></a> <a name="cache-adapters"></a>
## Cache ## Cache

2
test/arguments.js

@ -55,7 +55,7 @@ test('overrides querystring from opts', async t => {
test('should throw with auth in url string', async t => { test('should throw with auth in url string', async t => {
const err = await t.throws(got('https://test:45d3ps453@account.myservice.com/api/token')); const err = await t.throws(got('https://test:45d3ps453@account.myservice.com/api/token'));
t.regex(err.message, /Basic authentication must be done with auth option/); t.regex(err.message, /Basic authentication must be done with the `auth` option/);
}); });
test('does not throw with auth in url object', async t => { test('does not throw with auth in url object', async t => {

2
test/cache.js

@ -1,5 +1,5 @@
import test from 'ava'; import test from 'ava';
import got from '../'; import got from '..';
import {createServer} from './helpers/server'; import {createServer} from './helpers/server';
let s; let s;

2
test/error.js

@ -53,7 +53,7 @@ test('dns message', async t => {
test('options.body error message', async t => { test('options.body error message', async t => {
const err = await t.throws(got(s.url, {body: () => {}})); const err = await t.throws(got(s.url, {body: () => {}}));
t.regex(err.message, /options\.body must be a ReadableStream, string, Buffer or plain Object/); t.regex(err.message, /The `body` option must be a stream\.Readable, string, Buffer or plain Object/);
}); });
test('default status message', async t => { test('default status message', async t => {

2
test/redirects.js

@ -152,7 +152,7 @@ test('relative redirect works', async t => {
test('throws on endless redirect', async t => { test('throws on endless redirect', async t => {
const err = await t.throws(got(`${http.url}/endless`)); const err = await t.throws(got(`${http.url}/endless`));
t.is(err.message, 'Redirected 10 times. Aborting.'); t.is(err.message, 'Redirected 10 times. Aborting.');
t.deepEqual(err.redirectUrls, Array(10).fill(`${http.url}/endless`)); t.deepEqual(err.redirectUrls, new Array(10).fill(`${http.url}/endless`));
}); });
test('query in options are not breaking redirects', async t => { test('query in options are not breaking redirects', async t => {

4
test/stream.js

@ -35,7 +35,7 @@ test.before('setup', async () => {
test('option.json can not be used', t => { test('option.json can not be used', t => {
t.throws(() => { t.throws(() => {
got.stream(s.url, {json: true}); got.stream(s.url, {json: true});
}, 'got can not be used as stream when options.json is used'); }, 'Got can not be used as a stream when the `json` option is used');
}); });
test.cb('returns readable stream', t => { test.cb('returns readable stream', t => {
@ -58,7 +58,7 @@ test.cb('returns writeable stream', t => {
test.cb('throws on write to stream with body specified', t => { test.cb('throws on write to stream with body specified', t => {
t.throws(() => { t.throws(() => {
got.stream(s.url, {body: 'wow'}).write('wow'); got.stream(s.url, {body: 'wow'}).write('wow');
}, 'got\'s stream is not writable when options.body is used'); }, 'Got\'s stream is not writable when the `body` option is used');
// Wait for request to end // Wait for request to end
setTimeout(t.end, 10); setTimeout(t.end, 10);

Loading…
Cancel
Save