mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 21:04:23 +01:00
74 lines
2.2 KiB
TypeScript
74 lines
2.2 KiB
TypeScript
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
|
import type { SecretEntry, SecretKind, SetSecretRequest } from '@opencode-manager/shared/schemas'
|
|
import { deleteSecret, listSecrets, setSecret, type SecretScope } from '@/api/secrets'
|
|
|
|
interface SetSecretVariables {
|
|
kind: SecretKind
|
|
name: string
|
|
value: string
|
|
environment?: string
|
|
agentHidden?: boolean
|
|
allowedHosts?: string[]
|
|
}
|
|
|
|
function buildSetSecretRequest({
|
|
kind,
|
|
value,
|
|
environment,
|
|
agentHidden,
|
|
allowedHosts,
|
|
}: Omit<SetSecretVariables, 'name'>): SetSecretRequest {
|
|
if (kind !== 'secret') {
|
|
return environment ? { value, environment } : { value }
|
|
}
|
|
const request: SetSecretRequest = { value, agentHidden: agentHidden ?? false }
|
|
if (environment) request.environment = environment
|
|
if (agentHidden && allowedHosts && allowedHosts.length > 0) request.allowedHosts = allowedHosts
|
|
return request
|
|
}
|
|
|
|
interface DeleteSecretVariables {
|
|
kind: SecretKind
|
|
name: string
|
|
environment?: string
|
|
}
|
|
|
|
function scopeKey(scope: SecretScope): string {
|
|
return scope.scope === 'global' ? 'global' : `repo:${scope.repoId}`
|
|
}
|
|
|
|
function secretsQueryKey(scope: SecretScope, kind: SecretKind) {
|
|
return ['secrets', scopeKey(scope), kind] as const
|
|
}
|
|
|
|
export function useSecretEntries(scope: SecretScope, kind: SecretKind) {
|
|
return useQuery({
|
|
queryKey: secretsQueryKey(scope, kind),
|
|
queryFn: async (): Promise<SecretEntry[]> => (await listSecrets(scope, kind)).items,
|
|
})
|
|
}
|
|
|
|
export function useSetSecret(scope: SecretScope) {
|
|
const queryClient = useQueryClient()
|
|
|
|
return useMutation({
|
|
mutationFn: ({ kind, name, ...variables }: SetSecretVariables) =>
|
|
setSecret(scope, kind, name, buildSetSecretRequest({ kind, ...variables })),
|
|
onSuccess: (_result, variables) => {
|
|
queryClient.invalidateQueries({ queryKey: secretsQueryKey(scope, variables.kind) })
|
|
},
|
|
})
|
|
}
|
|
|
|
export function useDeleteSecret(scope: SecretScope) {
|
|
const queryClient = useQueryClient()
|
|
|
|
return useMutation({
|
|
mutationFn: ({ kind, name, environment }: DeleteSecretVariables) =>
|
|
deleteSecret(scope, kind, name, environment),
|
|
onSuccess: (_result, variables) => {
|
|
queryClient.invalidateQueries({ queryKey: secretsQueryKey(scope, variables.kind) })
|
|
},
|
|
})
|
|
}
|