-
Notifications
You must be signed in to change notification settings - Fork 3.5k
Expand file tree
/
Copy pathenvironment.ts
More file actions
167 lines (147 loc) · 5.17 KB
/
environment.ts
File metadata and controls
167 lines (147 loc) · 5.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
import { createLogger } from '@sim/logger'
import { keepPreviousData, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import type { EnvironmentVariable, WorkspaceEnvironmentData } from '@/lib/environment/api'
import { fetchPersonalEnvironment, fetchWorkspaceEnvironment } from '@/lib/environment/api'
import { workspaceCredentialKeys } from '@/hooks/queries/credentials'
import { API_ENDPOINTS } from '@/stores/constants'
const logger = createLogger('EnvironmentQueries')
/**
* Query key factories for environment variable queries
*/
export const environmentKeys = {
all: ['environment'] as const,
personal: () => [...environmentKeys.all, 'personal'] as const,
workspace: (workspaceId: string) => [...environmentKeys.all, 'workspace', workspaceId] as const,
}
/**
* Hook to fetch personal environment variables
*/
export function usePersonalEnvironment() {
return useQuery({
queryKey: environmentKeys.personal(),
queryFn: ({ signal }) => fetchPersonalEnvironment(signal),
staleTime: 60 * 1000,
})
}
/**
* Hook to fetch workspace environment variables
*/
export function useWorkspaceEnvironment<TData = WorkspaceEnvironmentData>(
workspaceId: string,
options?: { select?: (data: WorkspaceEnvironmentData) => TData }
) {
return useQuery({
queryKey: environmentKeys.workspace(workspaceId),
queryFn: ({ signal }) => fetchWorkspaceEnvironment(workspaceId, signal),
enabled: !!workspaceId,
staleTime: 60 * 1000, // 1 minute
placeholderData: keepPreviousData,
...options,
})
}
/**
* Save personal environment variables mutation
*/
interface SavePersonalEnvironmentParams {
variables: Record<string, string>
}
export function useSavePersonalEnvironment() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: async ({ variables }: SavePersonalEnvironmentParams) => {
const transformedVariables = Object.entries(variables).reduce(
(acc, [key, value]) => ({
...acc,
[key]: { key, value },
}),
{}
)
const response = await fetch(API_ENDPOINTS.ENVIRONMENT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
variables: Object.entries(transformedVariables).reduce(
(acc, [key, value]) => ({
...acc,
[key]: (value as EnvironmentVariable).value,
}),
{}
),
}),
})
if (!response.ok) {
throw new Error(`Failed to save environment variables: ${response.statusText}`)
}
logger.info('Saved personal environment variables')
return transformedVariables
},
onSettled: () => {
queryClient.invalidateQueries({ queryKey: environmentKeys.personal() })
queryClient.invalidateQueries({ queryKey: workspaceCredentialKeys.lists() })
},
})
}
/**
* Upsert workspace environment variables mutation
*/
interface UpsertWorkspaceEnvironmentParams {
workspaceId: string
variables: Record<string, string>
}
export function useUpsertWorkspaceEnvironment() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: async ({ workspaceId, variables }: UpsertWorkspaceEnvironmentParams) => {
const response = await fetch(API_ENDPOINTS.WORKSPACE_ENVIRONMENT(workspaceId), {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ variables }),
})
if (!response.ok) {
throw new Error(`Failed to update workspace environment: ${response.statusText}`)
}
logger.info(`Upserted workspace environment variables for workspace: ${workspaceId}`)
return await response.json()
},
onSettled: (_data, _error, variables) => {
queryClient.invalidateQueries({
queryKey: environmentKeys.workspace(variables.workspaceId),
})
queryClient.invalidateQueries({ queryKey: environmentKeys.personal() })
queryClient.invalidateQueries({ queryKey: workspaceCredentialKeys.lists() })
},
})
}
/**
* Remove workspace environment variables mutation
*/
interface RemoveWorkspaceEnvironmentParams {
workspaceId: string
keys: string[]
}
export function useRemoveWorkspaceEnvironment() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: async ({ workspaceId, keys }: RemoveWorkspaceEnvironmentParams) => {
const response = await fetch(API_ENDPOINTS.WORKSPACE_ENVIRONMENT(workspaceId), {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ keys }),
})
if (!response.ok) {
throw new Error(`Failed to remove workspace environment keys: ${response.statusText}`)
}
logger.info(`Removed ${keys.length} workspace environment keys for workspace: ${workspaceId}`)
return await response.json()
},
onSettled: (_data, _error, variables) => {
queryClient.invalidateQueries({
queryKey: environmentKeys.workspace(variables.workspaceId),
})
queryClient.invalidateQueries({ queryKey: environmentKeys.personal() })
queryClient.invalidateQueries({ queryKey: workspaceCredentialKeys.lists() })
},
})
}