Giter Site home page Giter Site logo

sindresorhus / ky Goto Github PK

View Code? Open in Web Editor NEW
11.5K 53.0 333.0 1003 KB

๐ŸŒณ Tiny & elegant JavaScript HTTP client based on the browser Fetch API

License: MIT License

TypeScript 100.00%
fetch whatwg-fetch http-client http-request request npm-package tiny json rest js

ky's Introduction

Ky is a tiny and elegant HTTP client based on the browser Fetch API

Coverage Status

Ky targets modern browsers, Node.js, and Deno.

It's just a tiny file with no dependencies.

Benefits over plain fetch

  • Simpler API
  • Method shortcuts (ky.post())
  • Treats non-2xx status codes as errors (after redirects)
  • Retries failed requests
  • JSON option
  • Timeout support
  • URL prefix option
  • Instances with custom defaults
  • Hooks

Install

npm install ky
Download
CDN

Usage

import ky from 'ky';

const json = await ky.post('https://example.com', {json: {foo: true}}).json();

console.log(json);
//=> `{data: '๐Ÿฆ„'}`

With plain fetch, it would be:

class HTTPError extends Error {}

const response = await fetch('https://example.com', {
	method: 'POST',
	body: JSON.stringify({foo: true}),
	headers: {
		'content-type': 'application/json'
	}
});

if (!response.ok) {
	throw new HTTPError(`Fetch error: ${response.statusText}`);
}

const json = await response.json();

console.log(json);
//=> `{data: '๐Ÿฆ„'}`

If you are using Deno, import Ky from a URL. For example, using a CDN:

import ky from 'https://esm.sh/ky';

API

ky(input, options?)

The input and options are the same as fetch, with some exceptions:

  • The credentials option is same-origin by default, which is the default in the spec too, but not all browsers have caught up yet.
  • Adds some more options. See below.

Returns a Response object with Body methods added for convenience. So you can, for example, call ky.get(input).json() directly without having to await the Response first. When called like that, an appropriate Accept header will be set depending on the body method used. Unlike the Body methods of window.Fetch; these will throw an HTTPError if the response status is not in the range of 200...299. Also, .json() will return an empty string if body is empty or the response status is 204 instead of throwing a parse error due to an empty body.

ky.get(input, options?)

ky.post(input, options?)

ky.put(input, options?)

ky.patch(input, options?)

ky.head(input, options?)

ky.delete(input, options?)

Sets options.method to the method name and makes a request.

When using a Request instance as input, any URL altering options (such as prefixUrl) will be ignored.

options

Type: object

method

Type: string
Default: 'get'

HTTP method used to make the request.

Internally, the standard methods (GET, POST, PUT, PATCH, HEAD and DELETE) are uppercased in order to avoid server errors due to case sensitivity.

json

Type: object and any other value accepted by JSON.stringify()

Shortcut for sending JSON. Use this instead of the body option. Accepts any plain object or value, which will be JSON.stringify()'d and sent in the body with the correct header set.

searchParams

Type: string | object<string, string | number | boolean> | Array<Array<string | number | boolean>> | URLSearchParams
Default: ''

Search parameters to include in the request URL. Setting this will override all existing search parameters in the input URL.

Accepts any value supported by URLSearchParams().

prefixUrl

Type: string | URL

A prefix to prepend to the input URL when making the request. It can be any valid URL, either relative or absolute. A trailing slash / is optional and will be added automatically, if needed, when it is joined with input. Only takes effect when input is a string. The input argument cannot start with a slash / when using this option.

Useful when used with ky.extend() to create niche-specific Ky-instances.

import ky from 'ky';

// On https://example.com

const response = await ky('unicorn', {prefixUrl: '/api'});
//=> 'https://example.com/api/unicorn'

const response2 = await ky('unicorn', {prefixUrl: 'https://cats.com'});
//=> 'https://cats.com/unicorn'

Notes:

  • After prefixUrl and input are joined, the result is resolved against the base URL of the page (if any).
  • Leading slashes in input are disallowed when using this option to enforce consistency and avoid confusion about how the input URL is handled, given that input will not follow the normal URL resolution rules when prefixUrl is being used, which changes the meaning of a leading slash.
retry

Type: object | number
Default:

  • limit: 2
  • methods: get put head delete options trace
  • statusCodes: 408 413 429 500 502 503 504
  • maxRetryAfter: undefined
  • backoffLimit: undefined
  • delay: attemptCount => 0.3 * (2 ** (attemptCount - 1)) * 1000

An object representing limit, methods, statusCodes and maxRetryAfter fields for maximum retry count, allowed methods, allowed status codes and maximum Retry-After time.

If retry is a number, it will be used as limit and other defaults will remain in place.

If maxRetryAfter is set to undefined, it will use options.timeout. If Retry-After header is greater than maxRetryAfter, it will cancel the request.

The backoffLimit option is the upper limit of the delay per retry in milliseconds. To clamp the delay, set backoffLimit to 1000, for example. By default, the delay is calculated with 0.3 * (2 ** (attemptCount - 1)) * 1000. The delay increases exponentially.

The delay option can be used to change how the delay between retries is calculated. The function receives one parameter, the attempt count, starting at 1.

Retries are not triggered following a timeout.

import ky from 'ky';

const json = await ky('https://example.com', {
	retry: {
		limit: 10,
		methods: ['get'],
		statusCodes: [413],
		backoffLimit: 3000
	}
}).json();
timeout

Type: number | false
Default: 10000

Timeout in milliseconds for getting a response, including any retries. Can not be greater than 2147483647. If set to false, there will be no timeout.

hooks

Type: object<string, Function[]>
Default: {beforeRequest: [], beforeRetry: [], afterResponse: []}

Hooks allow modifications during the request lifecycle. Hook functions may be async and are run serially.

hooks.beforeRequest

Type: Function[]
Default: []

This hook enables you to modify the request right before it is sent. Ky will make no further changes to the request after this. The hook function receives request and options as arguments. You could, for example, modify the request.headers here.

The hook can return a Request to replace the outgoing request, or return a Response to completely avoid making an HTTP request. This can be used to mock a request, check an internal cache, etc. An important consideration when returning a request or response from this hook is that any remaining beforeRequest hooks will be skipped, so you may want to only return them from the last hook.

import ky from 'ky';

const api = ky.extend({
	hooks: {
		beforeRequest: [
			request => {
				request.headers.set('X-Requested-With', 'ky');
			}
		]
	}
});

const response = await api.get('https://example.com/api/users');
hooks.beforeRetry

Type: Function[]
Default: []

This hook enables you to modify the request right before retry. Ky will make no further changes to the request after this. The hook function receives an object with the normalized request and options, an error instance, and the retry count. You could, for example, modify request.headers here.

If the request received a response, the error will be of type HTTPError and the Response object will be available at error.response. Be aware that some types of errors, such as network errors, inherently mean that a response was not received. In that case, the error will not be an instance of HTTPError.

You can prevent Ky from retrying the request by throwing an error. Ky will not handle it in any way and the error will be propagated to the request initiator. The rest of the beforeRetry hooks will not be called in this case. Alternatively, you can return the ky.stop symbol to do the same thing but without propagating an error (this has some limitations, see ky.stop docs for details).

import ky from 'ky';

const response = await ky('https://example.com', {
	hooks: {
		beforeRetry: [
			async ({request, options, error, retryCount}) => {
				const token = await ky('https://example.com/refresh-token');
				request.headers.set('Authorization', `token ${token}`);
			}
		]
	}
});
hooks.beforeError

Type: Function[]
Default: []

This hook enables you to modify the HTTPError right before it is thrown. The hook function receives a HTTPError as an argument and should return an instance of HTTPError.

import ky from 'ky';

await ky('https://example.com', {
	hooks: {
		beforeError: [
			error => {
				const {response} = error;
				if (response && response.body) {
					error.name = 'GitHubError';
					error.message = `${response.body.message} (${response.status})`;
				}

				return error;
			}
		]
	}
});
hooks.afterResponse

Type: Function[]
Default: []

This hook enables you to read and optionally modify the response. The hook function receives normalized request, options, and a clone of the response as arguments. The return value of the hook function will be used by Ky as the response object if it's an instance of Response.

import ky from 'ky';

const response = await ky('https://example.com', {
	hooks: {
		afterResponse: [
			(_request, _options, response) => {
				// You could do something with the response, for example, logging.
				log(response);

				// Or return a `Response` instance to overwrite the response.
				return new Response('A different response', {status: 200});
			},

			// Or retry with a fresh token on a 403 error
			async (request, options, response) => {
				if (response.status === 403) {
					// Get a fresh token
					const token = await ky('https://example.com/token').text();

					// Retry with the token
					request.headers.set('Authorization', `token ${token}`);

					return ky(request);
				}
			}
		]
	}
});
throwHttpErrors

Type: boolean
Default: true

Throw an HTTPError when, after following redirects, the response has a non-2xx status code. To also throw for redirects instead of following them, set the redirect option to 'manual'.

Setting this to false may be useful if you are checking for resource availability and are expecting error responses.

Note: If false, error responses are considered successful and the request will not be retried.

onDownloadProgress

Type: Function

Download progress event handler.

The function receives a progress and chunk argument:

  • The progress object contains the following elements: percent, transferredBytes and totalBytes. If it's not possible to retrieve the body size, totalBytes will be 0.
  • The chunk argument is an instance of Uint8Array. It's empty for the first call.
import ky from 'ky';

const response = await ky('https://example.com', {
	onDownloadProgress: (progress, chunk) => {
		// Example output:
		// `0% - 0 of 1271 bytes`
		// `100% - 1271 of 1271 bytes`
		console.log(`${progress.percent * 100}% - ${progress.transferredBytes} of ${progress.totalBytes} bytes`);
	}
});
parseJson

Type: Function
Default: JSON.parse()

User-defined JSON-parsing function.

Use-cases:

  1. Parse JSON via the bourne package to protect from prototype pollution.
  2. Parse JSON with reviver option of JSON.parse().
import ky from 'ky';
import bourne from '@hapijs/bourne';

const json = await ky('https://example.com', {
	parseJson: text => bourne(text)
}).json();
fetch

Type: Function
Default: fetch

User-defined fetch function. Has to be fully compatible with the Fetch API standard.

Use-cases:

  1. Use custom fetch implementations like isomorphic-unfetch.
  2. Use the fetch wrapper function provided by some frameworks that use server-side rendering (SSR).
import ky from 'ky';
import fetch from 'isomorphic-unfetch';

const json = await ky('https://example.com', {fetch}).json();

ky.extend(defaultOptions)

Create a new ky instance with some defaults overridden with your own.

In contrast to ky.create(), ky.extend() inherits defaults from its parent.

You can pass headers as a Headers instance or a plain object.

You can remove a header with .extend() by passing the header with an undefined value. Passing undefined as a string removes the header only if it comes from a Headers instance.

import ky from 'ky';

const url = 'https://sindresorhus.com';

const original = ky.create({
	headers: {
		rainbow: 'rainbow',
		unicorn: 'unicorn'
	}
});

const extended = original.extend({
	headers: {
		rainbow: undefined
	}
});

const response = await extended(url).json();

console.log('rainbow' in response);
//=> false

console.log('unicorn' in response);
//=> true

ky.create(defaultOptions)

Create a new Ky instance with complete new defaults.

import ky from 'ky';

// On https://my-site.com

const api = ky.create({prefixUrl: 'https://example.com/api'});

const response = await api.get('users/123');
//=> 'https://example.com/api/users/123'

const response = await api.get('/status', {prefixUrl: ''});
//=> 'https://my-site.com/status'

defaultOptions

Type: object

ky.stop

A Symbol that can be returned by a beforeRetry hook to stop the retry. This will also short circuit the remaining beforeRetry hooks.

Note: Returning this symbol makes Ky abort and return with an undefined response. Be sure to check for a response before accessing any properties on it or use optional chaining. It is also incompatible with body methods, such as .json() or .text(), because there is no response to parse. In general, we recommend throwing an error instead of returning this symbol, as that will cause Ky to abort and then throw, which avoids these limitations.

A valid use-case for ky.stop is to prevent retries when making requests for side effects, where the returned data is not important. For example, logging client activity to the server.

import ky from 'ky';

const options = {
	hooks: {
		beforeRetry: [
			async ({request, options, error, retryCount}) => {
				const shouldStopRetry = await ky('https://example.com/api');
				if (shouldStopRetry) {
					return ky.stop;
				}
			}
		]
	}
};

// Note that response will be `undefined` in case `ky.stop` is returned.
const response = await ky.post('https://example.com', options);

// Using `.text()` or other body methods is not supported.
const text = await ky('https://example.com', options).text();

HTTPError

Exposed for instanceof checks. The error has a response property with the Response object, request property with the Request object, and options property with normalized options (either passed to ky when creating an instance with ky.create() or directly when performing the request).

If you need to read the actual response when an HTTPError has occurred, call the respective parser method on the response object. For example:

try {
	await ky('https://example.com').json();
} catch (error) {
	if (error.name === 'HTTPError') {
		const errorJson = await error.response.json();
	}
}

TimeoutError

The error thrown when the request times out. It has a request property with the Request object.

Tips

Sending form data

Sending form data in Ky is identical to fetch. Just pass a FormData instance to the body option. The Content-Type header will be automatically set to multipart/form-data.

import ky from 'ky';

// `multipart/form-data`
const formData = new FormData();
formData.append('food', 'fries');
formData.append('drink', 'icetea');

const response = await ky.post(url, {body: formData});

If you want to send the data in application/x-www-form-urlencoded format, you will need to encode the data with URLSearchParams.

import ky from 'ky';

// `application/x-www-form-urlencoded`
const searchParams = new URLSearchParams();
searchParams.set('food', 'fries');
searchParams.set('drink', 'icetea');

const response = await ky.post(url, {body: searchParams});

Setting a custom Content-Type

Ky automatically sets an appropriate Content-Type header for each request based on the data in the request body. However, some APIs require custom, non-standard content types, such as application/x-amz-json-1.1. Using the headers option, you can manually override the content type.

import ky from 'ky';

const json = await ky.post('https://example.com', {
	headers: {
		'content-type': 'application/json'
	},
	json: {
		foo: true
	},
}).json();

console.log(json);
//=> `{data: '๐Ÿฆ„'}`

Cancellation

Fetch (and hence Ky) has built-in support for request cancellation through the AbortController API. Read more.

Example:

import ky from 'ky';

const controller = new AbortController();
const {signal} = controller;

setTimeout(() => {
	controller.abort();
}, 5000);

try {
	console.log(await ky(url, {signal}).text());
} catch (error) {
	if (error.name === 'AbortError') {
		console.log('Fetch aborted');
	} else {
		console.error('Fetch error:', error);
	}
}

FAQ

How do I use this in Node.js?

Node.js 18 and later supports fetch natively, so you can just use this package directly.

How do I use this with a web app (React, Vue.js, etc.) that uses server-side rendering (SSR)?

Same as above.

How do I test a browser library that uses this?

Either use a test runner that can run in the browser, like Mocha, or use AVA with ky-universal. Read more.

How do I use this without a bundler like Webpack?

Make sure your code is running as a JavaScript module (ESM), for example by using a <script type="module"> tag in your HTML document. Then Ky can be imported directly by that module without a bundler or other tools.

<script type="module">
import ky from 'https://unpkg.com/ky/distribution/index.js';

const json = await ky('https://jsonplaceholder.typicode.com/todos/1').json();

console.log(json.title);
//=> 'delectus aut autem
</script>

How is it different from got

See my answer here. Got is maintained by the same people as Ky.

How is it different from axios?

See my answer here.

How is it different from r2?

See my answer in #10.

What does ky mean?

It's just a random short npm package name I managed to get. It does, however, have a meaning in Japanese:

A form of text-able slang, KY is an abbreviation for ็ฉบๆฐ—่ชญใ‚ใชใ„ (kuuki yomenai), which literally translates into โ€œcannot read the air.โ€ It's a phrase applied to someone who misses the implied meaning.

Browser support

The latest version of Chrome, Firefox, and Safari.

Node.js support

Node.js 18 and later.

Related

  • got - Simplified HTTP requests for Node.js
  • ky-hooks-change-case - Ky hooks to modify cases on requests and responses of objects

Maintainers

ky's People

Contributors

alecmev avatar byscripts avatar cristobal avatar darkenergy96 avatar davidrunger avatar elijahsmith avatar hasparus avatar himynameisdave avatar ialexi-bl avatar joaovieira avatar jonasgeiler avatar kdelmonte avatar killynathan avatar lambdalisue avatar lemonadern avatar mgcrea avatar piitaya avatar poppinlp avatar promer94 avatar rangermeier avatar rclarey avatar richienb avatar ruyadorno avatar selrond avatar shivamjoker avatar sholladay avatar sindresorhus avatar szmarczak avatar ulken avatar whitecrownclown avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ky's Issues

Unhandled Rejection (Error): `input` must not begin with a slash when using `prefixUrl`

Hi,

I receive this exception when trying to call an API resource at https://example.com/foo/id

My ky instance is created as follow:

import ky from 'ky';

const config = {
    prefixUrl: process.env.API_ENTRYPOINT,
    headers: {
        'accept': 'application/ld+json'
    }
};

export default ky.extend(config);

I read the discussion related to the #11 and especially the one you wrote #11 (comment)

Sorry to be rude, but I disagree with the choice you made.
From my point of view, the only acceptable format should be await ky('/unicorn', {prefixUrl: 'https://cats.com'});.

It is not a matter of taste, just a choice guided by the RFC3986:
As per the section 3.3:

If a URI contains an authority component, then the path component
must either be empty or begin with a slash ("/") character.

For the url https://cats.com/unicorn we have the following parts:

  • The scheme: https
  • The : separator
  • The authority //cats.com (no userinfo, no port and host=cats.com)
  • The path to the resource: /unicorn

Except if the path is empty, a path must start with a slash.

Can you please reconsider the choice you made in #11 and modify this library according to that RFC?

Include a UMD build

I'm having to transpile the module before usage and I'm not sure if that's intentional.

This is the line which caused me pain.

ky/index.js

Line 192 in eb4b341

export default createInstance();

Feel free to close this is if the use of export is intentional, I couldn't really tell from the docs.

Add simple query/search parameters option?

I've added a very simple wrapper around fetch myself and added the ability to passing in a qs object, which adds some parameters to the url:

const uri = new URL(url)
if (qs) {
	Object.keys(qs).forEach((key) => uri.searchParams.append(key, qs[key]))
}

it's a nicer api then just adding these to the url by hand.
I could make a PR if interested.

Maybe some dist resources?

For some out of the box reasons for this lib. Maybe there could be some dist resources like iife, umd or whatever? Since the target env is browser and the native esm support for browser is not that popular. :)

More comprehensive `retry` option

Issuehunt badges

In addition to accepting a number, it should accept an object with the ability to specify which methods and status codes to retry on. Same as Got: https://github.com/sindresorhus/got#retry


IssueHunt Summary

whitecrownclown whitecrownclown has been rewarded.

Backers (Total: $60.00)

Submitted pull Requests


Tips


IssueHunt has been backed by the following sponsors. Become a sponsor

`Promise.race()` breaks debugging

I generally develop frontend having "Pause on exceptions" functionality of chrome dev tools enabled. Here Ky doesn't work so good and forced me to disable that feature.
What happens is that determining if the fetch request goes well or it goes in timeout, Ky puts the actual request in race against a promise that on timeout (delay) throws an error. It's a nice looking piece of code and works fine, but when the fetch resolves correctly (in time) the other promise continues on its way and launches an uncontrolled exception that is caught by "Pause on exceptions".

A solution can be removing the throw statement form the timeout promise and chaining the result of the promises race with another function that checks which promise won (fetch or timeout), if the latter then throw the error.

alternative syntax

Hi, could you have a look at this alternative syntax for the constructor ? It gets rid of delete this._options.timeout; and delete this._options.json; . Does it look cleaner for you ?

constructor(input, {timeout = 10000, json, ...otherOptions}) {
		this._input = input;
		this._retryCount = 0;

		this._options = {
			method: 'get',
			credentials: 'same-origin', // TODO: This can be removed when the spec change is implemented in all browsers. Context: https://www.chromestatus.com/feature/4539473312350208
			retry: 3,
			...otherOptions
		};

		this._timeout = timeout;

		const headers = new window.Headers(this._options.headers || {});

		if (json) {
			headers.set('content-type', 'application/json');
			this._options.body = JSON.stringify(json);
		}

Both hooks.afterResponse and beforeRequest could be defined optional

Hooks implementation is really a superb and extremly powerfull solution, but I would suggest some small changes to the typescript definition:

  1. Both hooks.afterResponse and beforeRequest could be optional
  2. BeforeRequestHook sould be BeforeRequestHook = (options: Options) => void;

Question: Is XHR Supported

From looking at the tags in the package.json file, I noticed it says XHR, but when looking at the actual repository's docs, it uses the browser fetch API. Does this mean this library does not support XHR?

Why Ky?

Why yet another library? Why not contribute to existing ones instead of splitting the ecosystem, making it harder for beginners to choose one lib?

Here is a very similar yet much older lib you could have contributed too https://github.com/elbywan/wretch

Searching for ky

I have just spent 15 minutes, because I forgot ky name. Using keywords like fetch, library, tiny etc. I failed to find this library in google, npm and github. In the end I kept scrolling in my liked tweets until I found it.

afterResponse hooks not fired if await ky directly

As discussed in Pr #93:
afterResponse hooks are not executed for the following code:

const response = await ky.get('https://example.com', {
    hooks: {
        afterResponse: [
             response => {
                 // This won't get called
             }
         ]
     }
});

const data = await response.json();

I know this is not how ky is supposed to be used, but it's easy to fall into this and see that everything is working, except the hooks.

Request continues after timeout

Something like:

const timeout = (promise, ms) => Promise.race([
	promise,
	(async () => {
		await delay(ms);
+       promise.abort();
		throw new TimeoutError();
	})()
]);

Hooks

Something like:

ky(input, {..., hooks: {
	beforeRequest: [
		...
	]
}})

No ES5 package

This library doesn't work with popular tools like create-react-app or next.js. The reason is that it has no precompiled ES5 bundles. This is considered a bad practice as when someone is using it he has to compile it to ES5 himself to support older browsers. Also, ky won't work on older browsers when just put into the page as a script.

I don't think it's a good idea to force users to compile every dependency to make sure it's ES5-ready. It would massively affect build times.

Default retry is different to readme

Hello,

Just a simple typo in the readme most likely, I would submit a PR but I'm not sure which is actually the most correct behaviour, a default retry of 2 like in the readme or 3 like the actual default.

Cheers

Error not thrown without the json method

Hi,

I was just trying to catch errors in the front-end of my react/redux app when I spotted a really odd behavior.

  • When doing a DELETE request on my API without ".json()" appended to my response, http errors are not thrown, even with throwHttpErrors forced true in the options.
try {
    await api.delete(`roles/${id}`);
    dispatch(actions.deleteRole(id));
  } catch (error) {
    dispatch({
      type: types.DELETE_ROLE_ERROR,
      payload: {
        error,
      },
    });
  }
  • When doing the same DELETE request with ".json()" appended to the response, errors are thrown but the request is fired twice so the second one always returns a 404.
try {
    await api.delete(`roles/${id}`).json();
    dispatch(actions.deleteRole(id));
  } catch (error) {
    dispatch({
      type: types.DELETE_ROLE_ERROR,
      payload: {
        error,
      },
    });
  }

Any idea why this would happen?

Add JSON convenience methods

To simplify json calls, which is probably the major use-case of this library it might be nice to provide some wrapper methods which simplify the api calls even further for the common get, put, patch, delete http verbs.

Eg.

const json = await ky.getJson('https://some-api.com');
const json = await ky.postJson('https://some-api.com', {foo: true});

These would obviously just be some syntatic sugar around the existing json examples, but imo it would make the api even nicer to use.

Maybe some assertions for `defaults` type in `extend`?

The defaults param will be used to deepMerge with other options and the deepMerge method will flat items for array argument.
Everything goes on normal and users may not know what happen if they pass in an array until they look into code. But there is something changed for options for Ky constructor actually.
Maybe there could be some assertions for the defaults param type as it should be an object? :)

naming

I know this was probably on purpose, or at least less important than the reasons pointed on the readme. however I have a really hard time dissociating this from the homonymous product ๐Ÿค”.

of course this could be a plus on describing the lib โ€” like "less friction on your client HTTP requests" โ€” and it's always nice to have a short npm name.

on future releases we may mirror it to another name if it's commonly agreed between maintainers here.. (hey, bhr for browser http request is still available ๐Ÿ˜…)

Adding a prettier config

Hello,

What's your opinion on having a prettier config? It'd much easier for contributors to write according to your style.

Trouble with Cypress

Env

"ky": "^0.5.1",
"cypress": "^3.1.2",

Problem

Cypress doesn't support fetch api call.

Chromium give following error:

GET https://raw.githubusercontent.com/parlr/lsf-data/master/ net::ERR_ABORTED 400 (Bad Request)

After trying to force fetch polyfill by adding below code in support/index.js

Cypress.on('window:before:load', win => {
  win.fetch = null;
});

I got this error:

Uncaught (in promise) ReferenceError: err is not defined
    at _callee$ (actions.js:36)
    at tryCatch (runtime.js:62)
    at Generator.invoke [as _invoke] (runtime.js:296)
    at Generator.prototype.(:8080/__/anonymous function) [as throw] (webpack:///./node_modules/regenerator-runtime/runtime.js?:114:21)
    at asyncGeneratorStep (actions.js:5)
    at _throw (actions.js:7)

TypeScript typings

Sindre, what's your current position on bundling Typescript typings to the repository? Somewhere I got the impression that you like Typescript and find typings useful. Do you intend to add them yourself? Will you allow someone to help with them? (but what about maintenance if you will change the API?)

Will you accept PR with initial typings?

Use es6 modules

Is it possible to leverage the es6 module export syntax instead of the current commonjs style?

Since this is a client side adaptation of fetch, one pro would be possible use of the file without a node bundler, and allow direct inclusion via `<script type="module">"

Example:

<script type="module">
        import ky, { extend, HTTPError, TimeoutError } from './index.js';

        document.addEventListener('DOMContentLoaded', () => {
            console.log({ ky });
            console.log({ extend });
            console.log({ HTTPError });
            console.log({ TimeoutError });
            alert('hi');
        });

    </script>

My current implementation needs some help to get working:

export default createInstance();
export let extend = defaults => createInstance(defaults);
export { HTTPError, TimeoutError };

That above fails a few tests. Example: k.extend is not defined anymore. We can instead directly add extend as a method.

Set the `accept` header when shortcut methods are called

Issuehunt badges

Mentioned it in sindresorhus/got#695 (comment)

One thing that got does, which I think it awesome, and which we don't have in ky, is setting the accept header when .json() is called.

@sholladay What's the benefit of sending this header? It works already without.

selrond earned $20.00 by resolving this issue!

React native reference error in 0.5.1

I have been using this library on version 0.4.1 for some time and that works in react-native when running on the simulator with a debugger attached. Running on device results in Reference Error: self is not defined. This should be fixed in issue #53 (With commit f107e7b) which is available from version 0.5.0. After upgrading ky to 0.5.0 or 0.5.1 Running on a simulator with a debugger attached or a device results in Reference Error: document is not defined.

I import ky and export an instance as follows:

import ky from "ky";
export const api = ky.extend({prefixUrl: BASE_URL});

The error shown in the console is as follows:

Possible Unhandled Promise Rejection (id: 0):
ReferenceError: document is not defined
ReferenceError: document is not defined
    at new Ky (blob:file:///58581b4b-dc99-4126-b9a9-cb3f918e33f0:111478:76)
    at Function.ky.(anonymous function) [as post] (blob:file:///58581b4b-dc99-4126-b9a9-cb3f918e33f0:111772:16)
    at _callee3$ (blob:file:///58581b4b-dc99-4126-b9a9-cb3f918e33f0:115504:24)
    at tryCatch (blob:file:///58581b4b-dc99-4126-b9a9-cb3f918e33f0:2081:19)
    at Generator.invoke [as _invoke] (blob:file:///58581b4b-dc99-4126-b9a9-cb3f918e33f0:2256:24)
    at Generator.prototype.(anonymous function) [as next] (blob:file:///58581b4b-dc99-4126-b9a9-cb3f918e33f0:2124:23)
    at tryCatch (blob:file:///58581b4b-dc99-4126-b9a9-cb3f918e33f0:2081:19)
    at invoke (blob:file:///58581b4b-dc99-4126-b9a9-cb3f918e33f0:2157:22)
    at blob:file:///58581b4b-dc99-4126-b9a9-cb3f918e33f0:2167:15
    at tryCallOne (blob:file:///58581b4b-dc99-4126-b9a9-cb3f918e33f0:6115:14)

TypeScript - Don't allow `body` option for GET and HEAD requests

Would be nice to not allow the body option when using ky.get() and ky.head().

We could use a custom Omit type for this:

type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>

Would also be nice to handle ky(โ€ฆ, {method: 'get', body: โ€ฆ}), but not sure whether that is possible?

It would also be nice to disallow the body option when the json option is used.

More info: http://artsy.github.io/blog/2018/11/21/conditional-types-in-typescript/

Universal app

I know we should use Got for node js, but I'm building an universal app that will be rendered on both server/client side, so how should we handle that ?

Ability to provide custom fetch

I am loving the simplicity of this module. What I also love is Next.js. However, those two unfortunately doesn't play well with each other.

Trying to call ky inside Next's getInitialProps throws that self is not defined, because during first request Next.js calls getInitialProps on the server.

One possible solution would be to accept a user's fetch (e.g. https://www.npmjs.com/package/isomorphic-unfetch).

I understand that this adds a complexity, but if you are willing to accept it, I can send a PR.

Object spread operator is breaking in local dev

โ” Issue

Ky is breaking due to the use of Object Spread Operator.

๐Ÿ”ฆ Context

I've tested it with Create-React-App. CRA supports the Object Spread Operator, however if it's used within a module, Babel does not transpile it. Interestingly enough, Ky works fine when I add into a box at Codesandbox.io.

๐Ÿ’ป Error Sample

./node_modules/ky/index.js
Module parse failed: Unexpected token (21:19)
You may need an appropriate loader to handle this file type.
| 				}
| 
| 				returnValue = {...returnValue, [key]: value};
| 			}
| 		}

๐ŸŒ Your Environment

Create react app @ latest
Node @ v10.6.0

TypeError relative URL after upgrading to 0.5.0

I've got this code:

  fetchHomeCards = async () => {
    this.setState({ loading: true });
    const response = await ky("/api/cards/");
    if (response.ok) {
...

it used to work just fine in 0.4.1, but busted now.

In Firefox I get TypeError: /api/cards/ is not a valid URL. on this line:

var url = new _globalThis.URL(this._options.prefixUrl + this._input);

In Chrome I get a lot more helpful error:

index.js:181 Uncaught (in promise) TypeError: Failed to construct 'URL': Invalid URL
    at new Ky (index.js:181)
    at ky (index.js:518)
    at CardsContainer._callee$ (State.js:15)
    at tryCatch (runtime.js:62)
    at Generator.invoke [as _invoke] (runtime.js:288)
    at Generator.prototype.(:3000/anonymous function) [as next] (http://localhost:3000/static/js/1.chunk.js:941:21)
    at asyncGeneratorStep (asyncToGenerator.js:3)
    at _next (asyncToGenerator.js:25)
    at asyncToGenerator.js:32
    at new Promise (<anonymous>)
    at CardsContainer.fetchHomeCards (asyncToGenerator.js:21)
    at Home._callee$ (Home.js:9)
    at tryCatch (runtime.js:62)
    at Generator.invoke [as _invoke] (runtime.js:288)
    at Generator.prototype.(:3000/anonymous function) [as next] (http://localhost:3000/static/js/1.chunk.js:941:21)
    at asyncGeneratorStep (asyncToGenerator.js:3)
    at _next (asyncToGenerator.js:25)
    at asyncToGenerator.js:32
    at new Promise (<anonymous>)
    at Home.<anonymous> (asyncToGenerator.js:21)
    at Home.componentDidMount (Home.js:12)
    at commitLifeCycles (react-dom.development.js:15986)
    at commitAllLifeCycles (react-dom.development.js:17388)
    at HTMLUnknownElement.callCallback (react-dom.development.js:147)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:196)
    at invokeGuardedCallback (react-dom.development.js:250)
    at commitRoot (react-dom.development.js:17549)
    at completeRoot (react-dom.development.js:19002)
    at performWorkOnRoot (react-dom.development.js:18924)
    at performWork (react-dom.development.js:18826)
    at performSyncWork (react-dom.development.js:18799)
    at requestWork (react-dom.development.js:18676)
    at scheduleWork (react-dom.development.js:18480)
    at scheduleRootUpdate (react-dom.development.js:19186)
    at updateContainerAtExpirationTime (react-dom.development.js:19212)
    at updateContainer (react-dom.development.js:19280)
    at ReactRoot.push../node_modules/react-dom/cjs/react-dom.development.js.ReactRoot.render (react-dom.development.js:19559)
    at react-dom.development.js:19713
    at unbatchedUpdates (react-dom.development.js:19064)
    at legacyRenderSubtreeIntoContainer (react-dom.development.js:19709)
    at Object.render (react-dom.development.js:19776)
    at Module../src/index.js (index.js:8)
    at __webpack_require__ (bootstrap:782)
    at fn (bootstrap:150)
    at Object.0 (serviceWorker.js:131)
    at __webpack_require__ (bootstrap:782)
    at checkDeferredModules (bootstrap:45)
    at Array.webpackJsonpCallback [as push] (bootstrap:32)
    at main.chunk.js:1

Adding an delete alias for better named imports

I ran into this problem when using rollup specifically, but the issue occurs anytime someone attempts to perform a named import. ie.

import { post, get, delete } from 'ky'

The problem here is that delete is a restricted keyword and causes issues when imported and called. One suggestion is to rename it during the import like:

import { post, get, delete as del } from 'ky'

But this doesnt really solve the problem that the export is still confusing.

As a suggestion, i think adding 'del', which would just be an alias for delete would remove this problem:

import { del } from 'ky'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.