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 mimicResponse = require('mimic-response');
const isRetryAllowed = require('is-retry-allowed');
const Buffer = require('safe-buffer').Buffer;
const isURL = require('isurl');
const isPlainObj = require('is-plain-obj');
const PCancelable = require('p-cancelable');
const pTimeout = require('p-timeout');
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 allMethodRedirectCodes = new Set([300, 303, 307, 308]);
@ -380,12 +380,12 @@ function asStream(opts) {
}
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) {
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 = urlParseLax(url);
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)) {
url = urlToOptions(url);
@ -494,12 +494,12 @@ function normalizeArguments(url, opts) {
if (body !== null && body !== undefined) {
const headers = opts.headers;
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);
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)) {

83
readme.md

@ -41,30 +41,36 @@ $ npm install got
## Usage
```js
const fs = require('fs');
const got = require('got');
got('sindresorhus.com')
.then(response => {
(async () => {
try {
const response = await got('sindresorhus.com');
console.log(response.body);
//=> '<!doctype html> ...'
})
.catch(error => {
} catch (error) {
console.log(error.response.body);
//=> 'Internal server error ...'
});
}
})();
```
###### Streams
```js
const fs = require('fs');
const got = require('got');
// Streams
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'));
```
### 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])
@ -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.
```js
got('sindresorhus.com')
.on('downloadProgress', progress => {
// Report download progress
})
.on('uploadProgress', progress => {
// Report upload progress
})
.then(response => {
// Done
});
(async () => {
const response = await got('sindresorhus.com')
.on('downloadProgress', progress => {
// Report download progress
})
.on('uploadProgress', progress => {
// Report upload progress
});
console.log(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.
```js
const request = got(url, options);
(async () => {
const request = got(url, options);
request.catch(err => {
if (request.canceled) {
// Handle cancelation
}
// Handle other errors
});
request.cancel();
```
// In another part of the code
if (something) {
request.cancel();
}
Or
```js
const request = got(url, options);
try {
await request;
} catch (error) {
if (request.canceled) { // Or `error instanceof got.CancelError`
// Handle cancelation
}
request.catch(err => {
if (err instanceof got.CancelError) {
// Handle cancelation
// Handle other errors
}
// Handle other errors
});
request.cancel();
})();
```
<a name="cache-adapters"></a>
## 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 => {
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 => {

2
test/cache.js

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

2
test/error.js

@ -53,7 +53,7 @@ test('dns message', async t => {
test('options.body error message', async t => {
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 => {

2
test/redirects.js

@ -152,7 +152,7 @@ test('relative redirect works', async t => {
test('throws on endless redirect', async t => {
const err = await t.throws(got(`${http.url}/endless`));
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 => {

4
test/stream.js

@ -35,7 +35,7 @@ test.before('setup', async () => {
test('option.json can not be used', t => {
t.throws(() => {
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 => {
@ -58,7 +58,7 @@ test.cb('returns writeable stream', t => {
test.cb('throws on write to stream with body specified', t => {
t.throws(() => {
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
setTimeout(t.end, 10);

Loading…
Cancel
Save