Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions packages/authentication/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# @baseapp-frontend/authentication

## 5.1.0

### Minor Changes

- Added the useRequestEmailChange hook and some icons and ilustrations

## 5.0.7

### Patch Changes
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
import {
ComponentWithProviders,
mockFetch,
mockFetchError,
renderHook,
} from '@baseapp-frontend/test'

import { z } from 'zod'

import { withAuthenticationTestProviders } from '../../../tests/utils'
import useRequestEmailChange from '../index'

describe('useRequestEmailChange', () => {
const newEmail = 'newemail@example.com'
const requestEmailChangeUrl = '/change-email'

afterEach(() => {
;(global.fetch as jest.Mock).mockClear()

Check warning on line 18 in packages/authentication/modules/access/useRequestEmailChange/__tests__/useRequestEmailChange.test.tsx

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Prefer `globalThis` over `global`.

See more on https://sonarcloud.io/project/issues?id=silverlogic_baseapp-frontend&issues=AZyLqmKaLbuc123cDRWa&open=AZyLqmKaLbuc123cDRWa&pullRequest=330
})

test('should run onSuccess', async () => {
mockFetch(requestEmailChangeUrl, {
method: 'POST',
status: 200,
response: {
newEmail,
},
})

let hasOnSuccessRan = false

const { result } = renderHook(
() =>
useRequestEmailChange({
defaultValues: {
newEmail,
},
requestEmailChangeOptions: {
onSuccess: () => {
hasOnSuccessRan = true
},
},
}),
{
wrapper: withAuthenticationTestProviders(ComponentWithProviders),
},
)

await result.current.form.handleSubmit()

expect(hasOnSuccessRan).toBe(true)
})

test('should run onError', async () => {
mockFetchError(requestEmailChangeUrl, { error: 'error', status: 500, method: 'POST' })

let hasOnErrorRan = false

const { result } = renderHook(
() =>
useRequestEmailChange({
defaultValues: {
newEmail,
},
requestEmailChangeOptions: {
onError: () => {
hasOnErrorRan = true
},
},
}),
{
wrapper: withAuthenticationTestProviders(ComponentWithProviders),
},
)

await result.current.form.handleSubmit()

expect(hasOnErrorRan).toBe(true)
})

test('should run onError when email is invalid', async () => {
mockFetch(requestEmailChangeUrl, {
method: 'POST',
status: 200,
response: {},
})

let hasOnSuccessRan = false

const { result } = renderHook(
() =>
useRequestEmailChange({
defaultValues: {
newEmail: 'invalid-email',
},
requestEmailChangeOptions: {
onSuccess: () => {
hasOnSuccessRan = true
},
},
}),
{
wrapper: withAuthenticationTestProviders(ComponentWithProviders),
},
)

await result.current.form.handleSubmit()

expect(hasOnSuccessRan).toBe(false)
})

test('should allow custom defaultValues and validationSchema', async () => {
mockFetch(requestEmailChangeUrl, {
method: 'POST',
status: 200,
response: {},
})

const customDefaultValues = {
newEmail: 'custom@example.com',
}

const customValidationSchema = z.object({
newEmail: z.string().min(1),
})

let hasOnSuccessRan = false

const { result } = renderHook(
() =>
useRequestEmailChange({
defaultValues: customDefaultValues,
validationSchema: customValidationSchema,
requestEmailChangeOptions: {
onSuccess: () => {
hasOnSuccessRan = true
},
},
}),
{
wrapper: withAuthenticationTestProviders(ComponentWithProviders),
},
)

await result.current.form.handleSubmit()

expect(hasOnSuccessRan).toBe(true)
})

describe('resendRequestEmailChangeMutation', () => {
const resendRequestEmailChangeUrl = '/change-email/resend-confirm'

test('should successfully resend email change request', async () => {
mockFetch(resendRequestEmailChangeUrl, {
method: 'POST',
status: 200,
response: {},
})

const { result } = renderHook(() => useRequestEmailChange({}), {
wrapper: withAuthenticationTestProviders(ComponentWithProviders),
})

await result.current.resendRequestEmailChangeMutation.mutateAsync()

expect(global.fetch).toHaveBeenCalledWith(

Check warning on line 166 in packages/authentication/modules/access/useRequestEmailChange/__tests__/useRequestEmailChange.test.tsx

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Prefer `globalThis` over `global`.

See more on https://sonarcloud.io/project/issues?id=silverlogic_baseapp-frontend&issues=AZyLqmKaLbuc123cDRWb&open=AZyLqmKaLbuc123cDRWb&pullRequest=330
expect.stringContaining(resendRequestEmailChangeUrl),
expect.objectContaining({
method: 'POST',
}),
)
})

test('should handle error when resending email change request fails', async () => {
mockFetchError(resendRequestEmailChangeUrl, {
error: 'error',
status: 500,
method: 'POST',
})

const { result } = renderHook(() => useRequestEmailChange({}), {
wrapper: withAuthenticationTestProviders(ComponentWithProviders),
})

await expect(
result.current.resendRequestEmailChangeMutation.mutateAsync(),
).rejects.toBeDefined()
})
})
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { ZOD_MESSAGE } from '@baseapp-frontend/utils'

import { z } from 'zod'

import type { RequestEmailChangeRequest } from './types'

export const DEFAULT_VALIDATION_SCHEMA = z.object({
newEmail: z.string().email(ZOD_MESSAGE.email).min(1, ZOD_MESSAGE.required),
})

export const DEFAULT_INITIAL_VALUES: RequestEmailChangeRequest = {
newEmail: '',
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
import { setFormApiErrors } from '@baseapp-frontend/utils'

import { zodResolver } from '@hookform/resolvers/zod'
import { useMutation } from '@tanstack/react-query'
import { type SubmitHandler, useForm } from 'react-hook-form'

import AuthApi from '../../../services/auth'
import { ConfirmEmailParams } from '../../../types/auth'
import { DEFAULT_INITIAL_VALUES, DEFAULT_VALIDATION_SCHEMA } from './constants'
import type { RequestEmailChangeRequest, UseRequestEmailChange } from './types'

const useRequestEmailChange = ({
validationSchema = DEFAULT_VALIDATION_SCHEMA,
defaultValues = DEFAULT_INITIAL_VALUES,
ApiClass = AuthApi,
enableFormApiErrors = true,
requestEmailChangeOptions = {},
resendRequestEmailChangeOptions = {},
verifyEmailChangeOptions = {},
resendVerifyEmailChangeOptions = {},
confirmEmailChangeOptions = {},
cancelEmailChangeOptions = {},
}: UseRequestEmailChange) => {
const form = useForm<RequestEmailChangeRequest>({
defaultValues,
resolver: zodResolver(validationSchema),
mode: 'onChange',
})

const requestEmailChangeMutation = useMutation({
mutationFn: ({ newEmail }: RequestEmailChangeRequest) =>
ApiClass.requestEmailChange({ newEmail }),
...requestEmailChangeOptions,
onError: (err, variables, context) => {
if (enableFormApiErrors) {
setFormApiErrors(form, err)
}
requestEmailChangeOptions?.onError?.(err, variables, context)
},
onSuccess: (response, variables, context) => {
requestEmailChangeOptions?.onSuccess?.(response, variables, context)
},
})

const resendRequestEmailChangeMutation = useMutation({
mutationFn: () => ApiClass.resendRequestEmailChange(),
...resendRequestEmailChangeOptions,
onError: (err, variables, context) => {
if (enableFormApiErrors) {
setFormApiErrors(form, err)
}
resendRequestEmailChangeOptions?.onError?.(err, variables, context)
},
onSuccess: (response, variables, context) => {
resendRequestEmailChangeOptions?.onSuccess?.(response, variables, context)
},
})

const verifyEmailChangeMutation = useMutation({
mutationFn: ({ id, token }: ConfirmEmailParams) => ApiClass.verifyEmailChange({ id, token }),
...verifyEmailChangeOptions,
onError: (err, variables, context) => {
if (enableFormApiErrors) {
setFormApiErrors(form, err)
}
verifyEmailChangeOptions?.onError?.(err, variables, context)
},
onSuccess: (response, variables, context) => {
verifyEmailChangeOptions?.onSuccess?.(response, variables, context)
},
})

const resendVerifyEmailChangeMutation = useMutation({
mutationFn: () => ApiClass.resendVerifyEmailChange(),
...resendVerifyEmailChangeOptions,
onError: (err, variables, context) => {
if (enableFormApiErrors) {
setFormApiErrors(form, err)
}
resendVerifyEmailChangeOptions?.onError?.(err, variables, context)
},
onSuccess: (response, variables, context) => {
resendVerifyEmailChangeOptions?.onSuccess?.(response, variables, context)
},
})

const confirmEmailChangeMutation = useMutation({
mutationFn: ({ id, token }: ConfirmEmailParams) => ApiClass.confirmEmailChange({ id, token }),
...confirmEmailChangeOptions,
onError: (err, variables, context) => {
if (enableFormApiErrors) {
setFormApiErrors(form, err)
}
confirmEmailChangeOptions?.onError?.(err, variables, context)
},
onSuccess: (response, variables, context) => {
confirmEmailChangeOptions?.onSuccess?.(response, variables, context)
},
})

const cancelEmailChangeMutation = useMutation({
mutationFn: () => ApiClass.cancelEmailChange(),
...cancelEmailChangeOptions,
onError: (err, variables, context) => {
if (enableFormApiErrors) {
setFormApiErrors(form, err)
}
cancelEmailChangeOptions?.onError?.(err, variables, context)
},
onSuccess: (response, variables, context) => {
cancelEmailChangeOptions?.onSuccess?.(response, variables, context)
},
})

const handleSubmit: SubmitHandler<RequestEmailChangeRequest> = async (values) => {
try {
await requestEmailChangeMutation.mutateAsync(values)
} catch (error) {
// mutateAsync will raise an error if there's an API error
}

Check warning on line 120 in packages/authentication/modules/access/useRequestEmailChange/index.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Handle this exception or don't catch it at all.

See more on https://sonarcloud.io/project/issues?id=silverlogic_baseapp-frontend&issues=AZyLqmHyLbuc123cDRWZ&open=AZyLqmHyLbuc123cDRWZ&pullRequest=330
}

return {
form: {
...form,
handleSubmit: form.handleSubmit(handleSubmit),
},
requestEmailChangeMutation,
resendRequestEmailChangeMutation,
verifyEmailChangeMutation,
resendVerifyEmailChangeMutation,
confirmEmailChangeMutation,
cancelEmailChangeMutation,
}
}

export default useRequestEmailChange
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import type { UseMutationOptions } from '@tanstack/react-query'
import { z } from 'zod'

import AuthApi from '../../../services/auth'
import { ConfirmEmailParams } from '../../../types/auth'

type ApiClass = Pick<
typeof AuthApi,
| 'requestEmailChange'
| 'resendRequestEmailChange'
| 'verifyEmailChange'
| 'resendVerifyEmailChange'
| 'confirmEmailChange'
| 'cancelEmailChange'
>

export type RequestEmailChangeRequest = {
newEmail: string
}

export interface UseRequestEmailChange {
validationSchema?: z.ZodType<RequestEmailChangeRequest>
defaultValues?: RequestEmailChangeRequest
requestEmailChangeOptions?: UseMutationOptions<void, unknown, RequestEmailChangeRequest, unknown>
resendRequestEmailChangeOptions?: UseMutationOptions<void, unknown, void, unknown>
verifyEmailChangeOptions?: UseMutationOptions<void, unknown, ConfirmEmailParams, unknown>
resendVerifyEmailChangeOptions?: UseMutationOptions<void, unknown, void, unknown>
confirmEmailChangeOptions?: UseMutationOptions<void, unknown, ConfirmEmailParams, unknown>
cancelEmailChangeOptions?: UseMutationOptions<void, unknown, void, unknown>
ApiClass?: ApiClass
enableFormApiErrors?: boolean
}
2 changes: 1 addition & 1 deletion packages/authentication/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@baseapp-frontend/authentication",
"description": "Authentication modules.",
"version": "5.0.7",
"version": "5.1.0",
"main": "./index.ts",
"types": "dist/index.d.ts",
"sideEffects": false,
Expand Down
Loading
Loading