Files
supabase/apps/studio/data/auth/user-create-mutation.ts
T
Ivan VasilovandJoshen Lim f29003e0e7 fix: Use protocol property when building API url (#30332)
* Fix the types for API settings to include protocol.

* Use the protocol property in all usages of endpoints.

* Update

* Lint

* Revert changes to retrieving protocol

* Remove console.logs

---------

Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
2024-11-06 22:22:24 +01:00

95 lines
2.3 KiB
TypeScript

import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { sqlKeys } from 'data/sql/keys'
import { post } from 'lib/common/fetch'
import { IS_PLATFORM } from 'lib/constants'
import { PROJECT_ENDPOINT_PROTOCOL } from 'pages/api/constants'
import type { ResponseError } from 'types'
import { authKeys } from './keys'
export type UserCreateVariables = {
projectRef?: string
protocol: string
endpoint: string
serviceApiKey: string
user: {
email: string
password: string
autoConfirmUser: string
}
}
export type UserCreateResponse = {
id: string
phone: string
role: string
updated_at: string
app_metadata: {
provider: string
providers: string[]
}
aud: string
created_at: string
email: string
email_confirmed_at: string
identities: any[]
user_metadata: any
}
export async function createUser({ protocol, endpoint, serviceApiKey, user }: UserCreateVariables) {
const response = await post(
`${protocol}://${endpoint}/auth/v1/admin/users`,
{
email: user.email,
password: user.password,
email_confirm: user.autoConfirmUser,
},
{
headers: {
apikey: serviceApiKey,
Authorization: `Bearer ${serviceApiKey}`,
},
}
)
if (response.error) throw response.error
return response
}
type UserCreateData = Awaited<ReturnType<typeof createUser>>
export const useUserCreateMutation = ({
onSuccess,
onError,
...options
}: Omit<
UseMutationOptions<UserCreateData, ResponseError, UserCreateVariables>,
'mutationFn'
> = {}) => {
const queryClient = useQueryClient()
return useMutation<UserCreateData, ResponseError, UserCreateVariables>(
(vars) => createUser(vars),
{
async onSuccess(data, variables, context) {
const { projectRef } = variables
Promise.all([
queryClient.invalidateQueries(authKeys.usersInfinite(projectRef)),
queryClient.invalidateQueries(sqlKeys.query(projectRef, authKeys.usersCount(projectRef))),
])
await onSuccess?.(data, variables, context)
},
async onError(data, variables, context) {
if (onError === undefined) {
toast.error(`Failed to create user: ${data.message}`)
} else {
onError(data, variables, context)
}
},
...options,
}
)
}