Extending ky instance with additional arguments for hooks without affecting other instances (typescript)
#564
-
|
I'm looking to create a import ky from 'ky'
import { getStringCookie, removeCookie } from '../cookie-service'
type MyOptions = {
withAuth?: boolean
unauthorizedCheck?: boolean
}
declare module 'ky' {
interface Options extends MyOptions {}
interface NormalizedOptions extends MyOptions {}
}
const api = ky.create({
hooks: {
beforeRequest: [
(request, options) => {
if (options.withAuth) {
request.headers.set(
'Authorization',
`Bearer ${getStringCookie('auth')}`,
)
}
},
],
afterResponse: [
(_request, options, response) => {
if (options.unauthorizedCheck && response.status === 401) {
removeCookie('auth')
window.location.href = '/'
throw new Error('Unauthorized')
}
return response
},
],
},
})
export default apiHowever, this would affect all other Is there a way to avoid this while achieving the same functionality? Specifically, I'd like to have autocompletion and type checking when calling any Any guidance would be greatly appreciated. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
you cant add custom options to type CustomOptions = {
withAuth?: boolean;
unauthorizedCheck?: boolean;
};
function createApi(customOptions: CustomOptions = {}) {
return ky.extend({
hooks: {
beforeRequest: [
request => {
if (customOptions.withAuth) {
request.headers.set('Authorization', getToken());
}
}
],
afterResponse: [
async (request, options, response) => {
if (customOptions.unauthorizedCheck && response.status === 401) {
// handle unauthorized
}
}
]
}
});
}
// usage
const api = createApi({withAuth: true, unauthorizedCheck: true});
await api.get('https://example.com/api/users');this keeps your custom options separate from Ky's built-in options and gives you full type safety without global modifications. alternatively, use closures to store state per-instance if you need dynamic behavior. |
Beta Was this translation helpful? Give feedback.
you cant add custom options to
Optionswithout affecting all instances globally. instead, create a wrapper function with your custom options: