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.

4.5 KB
Raw Blame
import { MakeLogicType, actions, kea, key, listeners, path, props, reducers } from 'kea'
import { loaders } from 'kea-loaders'

import { ApiConfig } from 'lib/api'

import { externalDataSourcesCredentialAccountsCreate } from 'products/warehouse_sources/frontend/generated/api'
import type { IntegrationAccountApi } from 'products/warehouse_sources/frontend/generated/api.schemas'

const CREDENTIALS_DEBOUNCE_MS = 500

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface credentialAccountsLogicValues {
    accounts: IntegrationAccountApi[]
    accountsError: string | null
    accountsLoaded: boolean
    accountsLoading: boolean
    credentials: Record<string, string>
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface credentialAccountsLogicActions {
    loadCredentialAccounts: () => any
    loadCredentialAccountsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadCredentialAccountsSuccess: (
        accounts: IntegrationAccountApi[],
        payload?: any
    ) => {
        accounts: IntegrationAccountApi[]
        payload?: any
    }
    setCredentials: (credentials: Record<string, string>) => {
        credentials: Record<string, string>
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface credentialAccountsLogicProps {
    sourceType: string
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface credentialAccountsLogicMeta {
    key: string
}

export type credentialAccountsLogicType = MakeLogicType<
    credentialAccountsLogicValues,
    credentialAccountsLogicActions,
    credentialAccountsLogicProps,
    credentialAccountsLogicMeta
>

/**
 * Accounts listed from credentials still sitting in the connect form, for a source that has no
 * OAuth integration to read them from. The OAuth twin is `integrationAccountsLogic`.
 *
 * Keyed on source type alone: the credentials change as the user types, and keying on them would
 * mount a fresh logic per keystroke.
 */
export const credentialAccountsLogic = kea<credentialAccountsLogicType>([
    props({} as { sourceType: string }),
    key((props) => props.sourceType),
    path((key) => ['lib', 'integrations', 'credentialAccountsLogic', key]),

    actions({
        setCredentials: (credentials: Record<string, string>) => ({ credentials }),
    }),

    loaders(({ props, values }) => ({
        accounts: [
            [] as IntegrationAccountApi[],
            {
                loadCredentialAccounts: async () => {
                    const response = await externalDataSourcesCredentialAccountsCreate(
                        String(ApiConfig.getCurrentProjectId()),
                        {
                            source_type: props.sourceType,
                            credentials: values.credentials,
                        }
                    )
                    return response.accounts
                },
            },
        ],
    })),

    reducers({
        credentials: [{} as Record<string, string>, { setCredentials: (_, { credentials }) => credentials }],
        // Distinguishes "not fetched yet" from "fetched and genuinely empty", so the picker doesn't
        // flash an empty state before the first response.
        accountsLoaded: [
            false,
            {
                loadCredentialAccountsSuccess: () => true,
                loadCredentialAccountsFailure: () => true,
            },
        ],
        // The backend turns a provider rejection into an actionable 400 (a key it won't accept, a
        // role that can read nothing). Surface that rather than a generic empty state.
        accountsError: [
            null as string | null,
            {
                loadCredentialAccounts: () => null,
                loadCredentialAccountsSuccess: () => null,
                loadCredentialAccountsFailure: (_, { error, errorObject }) =>
                    errorObject?.data?.detail ?? errorObject?.detail ?? error ?? null,
            },
        ],
    }),

    listeners(({ actions }) => ({
        setCredentials: async (_, breakpoint) => {
            // Longer than the OAuth logic's search debounce: this fires while the user is still
            // typing credentials, and each attempt costs a token exchange against the provider.
            await breakpoint(CREDENTIALS_DEBOUNCE_MS)
            actions.loadCredentialAccounts()
        },
    })),
])