Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

1.3 KB
Raw Blame
import { INTERNAL_SERVICE_CALL_HEADER_NAME } from '~/common/api/middleware/internal-api-auth'
import { logger } from '~/common/utils/logger'
import { FetchOptions, FetchResponse, internalFetch } from '~/common/utils/request'
import { tryCatch } from '~/common/utils/try-catch'

export class InternalFetchService {
    constructor(
        private internalApiBaseUrl: string,
        private internalApiSecret: string
    ) {}

    async fetch({
        urlPath,
        fetchParams,
    }: {
        urlPath: `/${string}`
        fetchParams: FetchOptions
    }): Promise<{ fetchError: Error | null; fetchResponse: FetchResponse | null }> {
        logger.debug('Making internal fetch request', { urlPath })

        const internalUrl = `${this.internalApiBaseUrl || 'http://localhost:8000'}${urlPath}`
        const internalFetchParams = {
            ...fetchParams,
            headers: {
                'Content-Type': 'application/json',
                ...fetchParams.headers,
                ...(this.internalApiSecret
                    ? { [INTERNAL_SERVICE_CALL_HEADER_NAME.toLowerCase()]: this.internalApiSecret }
                    : {}),
            },
        }

        const [fetchError, fetchResponse] = await tryCatch(
            async () => await internalFetch(internalUrl, internalFetchParams)
        )
        return { fetchError, fetchResponse }
    }
}