Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow extend() to append to prefixUrl #586

Closed
mfulton26 opened this issue May 14, 2024 · 5 comments · Fixed by #611
Closed

Allow extend() to append to prefixUrl #586

mfulton26 opened this issue May 14, 2024 · 5 comments · Fixed by #611

Comments

@mfulton26
Copy link
Contributor

I'd like a way to use extend() and append to the existing prefixUrl:

const api = ky.create({ prefixUrl: "https://www.example.com/api" });
const sales = api.extend({ path: "sales/v1" });
await sales.post("offers", { json: {} }); // POSTs to https://www.example.com/api/sales/v1/offers

Today if I use prefixUrl in an extend() call then it overwrites the "base" prefixUrl and I don't see any way to access the configured prefixUrl from the "base" KyInstance. Is this already possible and I've overlooked it?

@sindresorhus
Copy link
Owner

I think something like this would be useful. It should probably be called appendPath to make it clear what it does. I would like to see feedback more people first though.

@DCKT
Copy link

DCKT commented May 21, 2024

+1 ! This functionality can be useful when an API has multiples levels.
I also think this should be under a new function to avoid breaking change and explicit behavior.

@mfulton26
Copy link
Contributor Author

kyInstance.appendPath() could be nice (explicit, simple, no changes to extend())

@sholladay
Copy link
Collaborator

I propose a more generic feature to solve this. When using .extend(), pass a function and Ky will provide you the existing options, which you can then modify as you see fit and return. The return value is spread into the existing options, just as though you had passed it directly to .extend() without using a function.

const api = ky.create({ prefixUrl: "https://www.example.com/api" });
const sales = api.extend((options => ({ prefixUrl: options.prefixUrl + "/sales/v1" }));
await sales.post("offers", { json: {} }); // POSTs to https://www.example.com/api/sales/v1/offers

@sholladay sholladay changed the title extend: append to prefixUrl Allow extend() to append to prefixUrl Jun 25, 2024
@sindresorhus
Copy link
Owner

@sholladay 👍

mfulton26 added a commit to mfulton26/ky that referenced this issue Jul 16, 2024
callback function receives parent's default options to allow extended instance to refer to modify parent options

Closes sindresorhus#586
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants