From a4facf311d886e29217527ea4ee1c0990af04af3 Mon Sep 17 00:00:00 2001 From: Sindre Sorhus Date: Thu, 16 Nov 2017 15:02:40 +0700 Subject: [PATCH] Readme and error message tweaks --- index.js | 14 ++++---- readme.md | 83 ++++++++++++++++++++++++----------------------- test/arguments.js | 2 +- test/cache.js | 2 +- test/error.js | 2 +- test/redirects.js | 2 +- test/stream.js | 4 +-- 7 files changed, 55 insertions(+), 54 deletions(-) diff --git a/index.js b/index.js index 6775dd5..c474d26 100644 --- a/index.js +++ b/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)) { diff --git a/readme.md b/readme.md index 7e070a4..c6a9988 100644 --- a/readme.md +++ b/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); //=> ' ...' - }) - .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(); +})(); ``` - ## Cache diff --git a/test/arguments.js b/test/arguments.js index cd3cb8f..1038ac3 100644 --- a/test/arguments.js +++ b/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 => { diff --git a/test/cache.js b/test/cache.js index 04a8423..7148f21 100644 --- a/test/cache.js +++ b/test/cache.js @@ -1,5 +1,5 @@ import test from 'ava'; -import got from '../'; +import got from '..'; import {createServer} from './helpers/server'; let s; diff --git a/test/error.js b/test/error.js index ae05acc..1fe3f1d 100644 --- a/test/error.js +++ b/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 => { diff --git a/test/redirects.js b/test/redirects.js index 12776e4..e68539b 100644 --- a/test/redirects.js +++ b/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 => { diff --git a/test/stream.js b/test/stream.js index 19b9015..16a6779 100644 --- a/test/stream.js +++ b/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);