|
| 1 | +import { useEffect, useState } from "react"; |
| 2 | +import { getSlackIntegrations } from "../repository/slack.integration.repository"; |
| 3 | + |
| 4 | +interface ISlackWebhook { |
| 5 | + id?: number; |
| 6 | + access_token_iv?: string; |
| 7 | + access_token: string; |
| 8 | + scope: string; |
| 9 | + user_id?: number; // FK to users table |
| 10 | + team_name: string; |
| 11 | + team_id: string; |
| 12 | + channel: string; |
| 13 | + channel_id: string; |
| 14 | + configuration_url: string; // configuration URL to manage the webhook |
| 15 | + url_iv?: string; |
| 16 | + url: string; // URL of the slack workspace |
| 17 | + created_at?: string; |
| 18 | + is_active?: boolean; |
| 19 | +} |
| 20 | +export interface SlackWebhook { |
| 21 | + id?: number; |
| 22 | + scope: string; |
| 23 | + teamName: string; |
| 24 | + teamId: string; |
| 25 | + channel: string; |
| 26 | + channelId: string; |
| 27 | + createdAt?: string; |
| 28 | + isActive?: boolean; |
| 29 | +} |
| 30 | + |
| 31 | +interface ApiResponse { |
| 32 | + data: ISlackWebhook[]; |
| 33 | +} |
| 34 | + |
| 35 | +const useSlackIntegrations = (userId: number | null) => { |
| 36 | + const [slackIntegrations, setSlackIntegrations] = useState<SlackWebhook[]>( |
| 37 | + [], |
| 38 | + ); |
| 39 | + const [loading, setLoading] = useState(true); |
| 40 | + const [error, setError] = useState<string | null>(null); |
| 41 | + |
| 42 | + const fetchSlackIntegrations = async () => { |
| 43 | + try { |
| 44 | + const controller = new AbortController(); |
| 45 | + const signal = controller.signal; |
| 46 | + setLoading(true); |
| 47 | + const response = await getSlackIntegrations({ id: userId!, signal }); |
| 48 | + |
| 49 | + const integrations: SlackWebhook[] = (response as ApiResponse).data.map( |
| 50 | + (item: ISlackWebhook): SlackWebhook => ({ |
| 51 | + id: item.id, |
| 52 | + scope: item.scope, |
| 53 | + teamName: item.team_name, |
| 54 | + teamId: item.team_id, |
| 55 | + channel: item.channel, |
| 56 | + channelId: item.channel_id, |
| 57 | + createdAt: item.created_at, |
| 58 | + isActive: item.is_active, |
| 59 | + }), |
| 60 | + ); |
| 61 | + |
| 62 | + setSlackIntegrations(integrations); |
| 63 | + setError(null); |
| 64 | + } catch (err) { |
| 65 | + setError( |
| 66 | + err instanceof Error |
| 67 | + ? err.message |
| 68 | + : "Failed to fetch slack integrations", |
| 69 | + ); |
| 70 | + } finally { |
| 71 | + setLoading(false); |
| 72 | + } |
| 73 | + }; |
| 74 | + |
| 75 | + useEffect(() => { |
| 76 | + fetchSlackIntegrations(); |
| 77 | + }, []); |
| 78 | + |
| 79 | + return { |
| 80 | + slackIntegrations, |
| 81 | + loading, |
| 82 | + error, |
| 83 | + refreshSlackIntegrations: fetchSlackIntegrations, |
| 84 | + }; |
| 85 | +}; |
| 86 | + |
| 87 | +export default useSlackIntegrations; |
0 commit comments