ky icon indicating copy to clipboard operation
ky copied to clipboard

Allow extend() to append to prefixUrl

Open mfulton26 opened this issue 1 year ago • 4 comments

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?

mfulton26 avatar May 14 '24 13:05 mfulton26

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.

sindresorhus avatar May 14 '24 21:05 sindresorhus

+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.

DCKT avatar May 21 '24 09:05 DCKT

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

mfulton26 avatar May 21 '24 12:05 mfulton26

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 avatar Jun 13 '24 02:06 sholladay

@sholladay 👍

sindresorhus avatar Jun 30 '24 13:06 sindresorhus