Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add transformValues option to performMutation and formAction #110

Merged
merged 5 commits into from
Nov 29, 2022
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
3 changes: 3 additions & 0 deletions apps/web/app/routes/examples.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ export default function Component() {
<SidebarLayout.NavLink to={'/examples/actions/field-error'}>
Field error
</SidebarLayout.NavLink>
<SidebarLayout.NavLink to={'/examples/actions/transform-values'}>
Transform values
</SidebarLayout.NavLink>
<SidebarLayout.NavTitle>Modes</SidebarLayout.NavTitle>
<SidebarLayout.NavLink to={'/examples/modes/on-submit'}>
onSubmit
Expand Down
70 changes: 70 additions & 0 deletions apps/web/app/routes/examples/actions/transform-values.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import hljs from 'highlight.js/lib/common'
import type {
ActionFunction,
LoaderFunction,
MetaFunction,
} from '@remix-run/node'
import { formAction } from '~/formAction'
import { z } from 'zod'
import Form from '~/ui/form'
import { metaTags } from '~/helpers'
import { makeDomainFunction } from 'domain-functions'
import Example from '~/ui/example'

const title = 'Transform values'
const description =
'In this example, we use different schemas for the form and the mutation, transforming the form values before calling the mutation.'

export const meta: MetaFunction = () => metaTags({ title, description })

const code = `const formSchema = z.object({
firstName: z.string().min(1),
email: z.string().min(1).email(),
})

const mutationSchema = formSchema.extend({
country: z.enum(['BR', 'US']),
})

const mutation = makeDomainFunction(mutationSchema)(async (values) => values)

export const action: ActionFunction = async ({ request }) =>
formAction({
request,
schema: formSchema,
mutation,
transformValues: (values) => ({ ...values, country: 'US' }),
})

export default () => <Form schema={schema} />`

const formSchema = z.object({
firstName: z.string().min(1),
email: z.string().min(1).email(),
})

const mutationSchema = formSchema.extend({
country: z.enum(['BR', 'US']),
})

export const loader: LoaderFunction = () => ({
code: hljs.highlight(code, { language: 'ts' }).value,
})

const mutation = makeDomainFunction(mutationSchema)(async (values) => values)

export const action: ActionFunction = async ({ request }) =>
formAction({
request,
schema: formSchema,
mutation,
transformValues: (values) => ({ ...values, country: 'US' }),
})

export default function Component() {
return (
<Example title={title} description={description}>
<Form schema={formSchema} />
</Example>
)
}
104 changes: 104 additions & 0 deletions apps/web/tests/examples/actions/transform-values.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import { test, testWithoutJS, expect } from 'tests/setup/tests'

const route = '/examples/actions/transform-values'

test('With JS enabled', async ({ example }) => {
const { firstName, email, button, page } = example

await page.goto(route)

// Render
await example.expectField(firstName)
await example.expectField(email)
await expect(button).toBeEnabled()

// Client-side validation
await button.click()

// Show field errors and focus on the first field
await example.expectError(
firstName,
'String must contain at least 1 character(s)',
)
await example.expectError(
email,
'String must contain at least 1 character(s)',
)
await expect(firstName.input).toBeFocused()

// Make first field be valid, focus goes to the second field
await firstName.input.fill('John')
await button.click()
await example.expectValid(firstName)
await expect(email.input).toBeFocused()

// Try another invalid message
await email.input.fill('john')
await example.expectError(email, 'Invalid email')

// Make form be valid
await email.input.fill('john@doe.com')
await example.expectValid(email)

// Submit form
button.click()
await expect(button).toBeDisabled()

await example.expectData({
firstName: 'John',
email: 'john@doe.com',
country: 'US',
})
})

testWithoutJS('With JS disabled', async ({ example }) => {
const { firstName, email, button, page } = example

await page.goto(route)

// Server-side validation
await button.click()
await page.reload()

// Show field errors and focus on the first field
await example.expectError(
firstName,
'String must contain at least 1 character(s)',
)

await example.expectErrors(
email,
'String must contain at least 1 character(s)',
'Invalid email',
)

await example.expectAutoFocus(firstName)
await example.expectNoAutoFocus(email)

// Make first field be valid, focus goes to the second field
await firstName.input.fill('John')
await button.click()
await page.reload()
await example.expectValid(firstName)
await example.expectNoAutoFocus(firstName)
await example.expectAutoFocus(email)

// Try another invalid message
await email.input.fill('john')
await button.click()
await page.reload()
await example.expectError(email, 'Invalid email')

// Make form be valid and test selecting an option
await email.input.fill('john@doe.com')

// Submit form
await button.click()
await page.reload()

await example.expectData({
firstName: 'John',
email: 'john@doe.com',
country: 'US',
})
})
8 changes: 7 additions & 1 deletion packages/remix-forms/src/mutations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ type PerformMutationProps<Schema extends FormSchema, D extends unknown> = {
schema: Schema
mutation: DomainFunction<D>
environment?: unknown
transformValues?: (
values: FormValues<z.infer<Schema>>,
) => Record<string, unknown>
}

type FormActionProps<Schema extends FormSchema, D extends unknown> = {
Expand Down Expand Up @@ -60,11 +63,12 @@ async function performMutation<Schema extends FormSchema, D extends unknown>({
schema,
mutation,
environment,
transformValues = (values) => values,
}: PerformMutationProps<Schema, D>): Promise<
PerformMutation<z.infer<Schema>, D>
> {
const values = await getFormValues(request, schema)
const result = await mutation(values, environment)
const result = await mutation(transformValues(values), environment)

if (result.success) {
return { success: true, data: result.data }
Expand Down Expand Up @@ -97,6 +101,7 @@ function createFormAction({
schema,
mutation,
environment,
transformValues,
beforeAction,
beforeSuccess,
successPath,
Expand All @@ -111,6 +116,7 @@ function createFormAction({
schema,
mutation,
environment,
transformValues,
})

if (result.success) {
Expand Down