sindresorhus / ky

🌳 Tiny & elegant JavaScript HTTP client based on the browser Fetch API
MIT License
11.83k stars 341 forks source link

Allow extend() to append to prefixUrl #586

Open mfulton26 opened 1 month ago

mfulton26 commented 1 month ago

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 commented 1 month ago

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 commented 1 month ago

+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 commented 1 month ago

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

sholladay commented 3 weeks ago

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
sindresorhus commented 1 week ago

@sholladay 👍