0
0
mirror of https://github.com/PostHog/posthog.git synced 2024-11-22 08:40:03 +01:00
posthog/.storybook/ApiSelector/withApi.js
Marius Andra 528f7d0dda
Storybook API connection toolbar (#5871)
* basic api selector toolbar

* api history
2021-09-11 00:34:15 +02:00

36 lines
1.1 KiB
JavaScript

import React, { useEffect } from 'react'
import { GLOBAL_KEY } from './constants'
export const withApi = (Story, context) => {
const connection = context.globals[GLOBAL_KEY]
const { apiKey, apiHost } = connection || {}
useEffect(() => {
const oldFetch = window.fetch
window.fetch = (url, ...args) => {
console.log('Intercepted Fetch', args)
if (url.startsWith('/api/')) {
if (!apiHost) {
return Promise.resolve(new Error('Request Failed!'))
} else {
let [opts, ...otherArgs] = args
opts = {
...opts,
headers: {
...opts.headers,
Authorization: `Bearer ${apiKey}`,
},
}
return oldFetch(`${apiHost}${url}`, opts || {}, ...otherArgs)
}
}
return oldFetch(url, ...args)
}
return () => {
window.fetch = oldFetch
}
}, [connection])
return <Story {...context} />
}