-
Notifications
You must be signed in to change notification settings - Fork 248
feat: add zod
example
#328
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
Open
berkinanik
wants to merge
6
commits into
remix-run:main
Choose a base branch
from
berkinanik:zod
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
ebebe23
feat: add `zod` example
berkinanik d3e3af0
fix: refactor with suggested changes
berkinanik 37c825b
feat: add debounced submission and field errors to products form
berkinanik e132695
Merge branch 'main' into zod
berkinanik 70c9560
feat: migrate to remix-run v2 route convention
berkinanik 1efee39
chore: rename products file
berkinanik File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
/** @type {import('eslint').Linter.Config} */ | ||
module.exports = { | ||
extends: ["@remix-run/eslint-config", "@remix-run/eslint-config/node"], | ||
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
node_modules | ||
|
||
/.cache | ||
/build | ||
/public/build | ||
.env |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
# Zod Example | ||
|
||
This example demonstrates how to use [Zod](https://npm.im/zod) for server-side validation and data transformation in a Remix application. It includes a user registration form and a product listing page. | ||
|
||
In the user registration form, Zod is used to validate and transform POST data which is submitted by the form in the action handler. | ||
|
||
In the product listing page, Zod is used to validate and transform GET query parameters which are used for filtering and pagination in the loader. | ||
|
||
Every validation and data transformation is done on the server-side, so the client can use the app without JavaScript enabled. | ||
|
||
Enjoy Remix's progressively enhanced forms 💿 and Zod's type safety 💎! | ||
|
||
## Preview | ||
|
||
Open this example on [CodeSandbox](https://codesandbox.com): | ||
|
||
[](https://codesandbox.io/s/github/remix-run/examples/tree/main/zod) | ||
|
||
## Example | ||
|
||
### `app/root.tsx` | ||
|
||
A simple error boundary component is added to catch the errors and display error messages. | ||
|
||
### `app/routes/index.tsx` | ||
|
||
This file contains the user registration form and its submission handling logic. It leverages Zod for validating and transforming the POST data. | ||
|
||
### `app/routes/products.tsx` | ||
|
||
This file implements the product listing page, including filters and pagination. It leverages Zod for URL query parameter validation and transforming. A cache control header is added to the response to ensure the page is cached also. | ||
|
||
--- | ||
|
||
Following two files are used for mocking and functionality demonstration. They are not directly related to Zod or Remix. | ||
|
||
#### `app/lib/product.server.ts` | ||
|
||
This file defines the schema for the product data and provides a mock product list. It's used to ensure the type safety of the product data. | ||
|
||
#### `app/lib/utils.server.ts` | ||
|
||
This file contains `isDateFormat` utility which is used for date validation for `<input type="date" />` and a function for calculating days until the next birthday. | ||
|
||
## Related Links | ||
|
||
- [Remix Documentation](https://remix.run/docs) | ||
- [Zod Documentation](https://github.com/colinhacks/zod/#zod) | ||
- [Zod: Coercion for Primitives](https://github.com/colinhacks/zod/#coercion-for-primitives) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,87 @@ | ||
import * as z from "zod"; | ||
|
||
const ProductSchema = z.object({ | ||
id: z.number().int().positive(), | ||
name: z.string(), | ||
price: z.number(), | ||
}); | ||
|
||
type Product = z.infer<typeof ProductSchema>; | ||
|
||
export const mockProducts: Product[] = [ | ||
{ | ||
id: 1, | ||
name: "Laptop", | ||
price: 900, | ||
}, | ||
{ | ||
id: 2, | ||
name: "Smartphone", | ||
price: 700, | ||
}, | ||
{ | ||
id: 3, | ||
name: "T-shirt", | ||
price: 20, | ||
}, | ||
{ | ||
id: 4, | ||
name: "Jeans", | ||
price: 50, | ||
}, | ||
{ | ||
id: 5, | ||
name: "Running Shoes", | ||
price: 90, | ||
}, | ||
{ | ||
id: 6, | ||
name: "Bluetooth Speaker", | ||
price: 50, | ||
}, | ||
{ | ||
id: 7, | ||
name: "Dress Shirt", | ||
price: 30, | ||
}, | ||
{ | ||
id: 8, | ||
name: "Gaming Console", | ||
price: 350, | ||
}, | ||
{ | ||
id: 9, | ||
name: "Sneakers", | ||
price: 120, | ||
}, | ||
{ | ||
id: 10, | ||
name: "Watch", | ||
price: 200, | ||
}, | ||
{ | ||
id: 11, | ||
name: "Hoodie", | ||
price: 40, | ||
}, | ||
{ | ||
id: 12, | ||
name: "Guitar", | ||
price: 300, | ||
}, | ||
{ | ||
id: 13, | ||
name: "Fitness Tracker", | ||
price: 80, | ||
}, | ||
{ | ||
id: 14, | ||
name: "Backpack", | ||
price: 50, | ||
}, | ||
{ | ||
id: 15, | ||
name: "Dumbbell Set", | ||
price: 130, | ||
}, | ||
]; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
export const isDateFormat = (date: string): boolean => { | ||
return /^\d{4}-\d{2}-\d{2}$/.test(date); | ||
}; | ||
|
||
export const calculateDaysUntilNextBirthday = (birthday: Date): number => { | ||
const today = new Date(); | ||
const currentYear = today.getFullYear(); | ||
const birthdayThisYear = new Date( | ||
currentYear, | ||
birthday.getMonth(), | ||
birthday.getDate(), | ||
); | ||
const diff = birthdayThisYear.getTime() - today.getTime(); | ||
const days = Math.ceil(diff / (1000 * 3600 * 24)); | ||
return days < 0 ? 365 + days : days; | ||
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
import type { MetaFunction } from "@remix-run/node"; | ||
import { | ||
Links, | ||
LiveReload, | ||
Meta, | ||
Outlet, | ||
Scripts, | ||
ScrollRestoration, | ||
} from "@remix-run/react"; | ||
|
||
export const meta: MetaFunction = () => ({ | ||
charset: "utf-8", | ||
title: "Remix 💿 + Zod 💎", | ||
viewport: "width=device-width,initial-scale=1", | ||
}); | ||
|
||
export default function App() { | ||
return ( | ||
<html lang="en"> | ||
<head> | ||
<Meta /> | ||
<Links /> | ||
</head> | ||
<body> | ||
<Outlet /> | ||
<ScrollRestoration /> | ||
<Scripts /> | ||
<LiveReload /> | ||
</body> | ||
</html> | ||
); | ||
} | ||
|
||
export const ErrorBoundary = ({ error }: { error: Error }) => { | ||
return ( | ||
<div> | ||
<h1>App Error</h1> | ||
<pre>{error.message}</pre> | ||
</div> | ||
); | ||
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,170 @@ | ||
import { ActionArgs, json } from "@remix-run/node"; | ||
import { Form, Link, useActionData, useNavigation } from "@remix-run/react"; | ||
import * as z from "zod"; | ||
|
||
import { | ||
calculateDaysUntilNextBirthday, | ||
isDateFormat, | ||
} from "~/lib/utils.server"; | ||
|
||
export const action = async ({ request }: ActionArgs) => { | ||
const formData = await request.formData(); | ||
const payload = Object.fromEntries(formData.entries()); | ||
|
||
const currentDate = new Date(); | ||
|
||
const schema = z.object({ | ||
firstName: z | ||
.string() | ||
.min(2, "Must be at least 2 characters") | ||
.max(50, "Must be less than 50 characters"), | ||
email: z.string().email("Must be a valid email"), | ||
birthday: z.coerce | ||
.date() | ||
.min( | ||
new Date( | ||
currentDate.getFullYear() - 26, | ||
currentDate.getMonth(), | ||
currentDate.getDate(), | ||
), | ||
"Must be younger than 25", | ||
) | ||
.max( | ||
new Date( | ||
currentDate.getFullYear() - 18, | ||
currentDate.getMonth(), | ||
currentDate.getDate(), | ||
), | ||
"Must be at least 18 years old", | ||
), | ||
}); | ||
|
||
const parseResult = schema.safeParse(payload); | ||
|
||
if (!parseResult.success) { | ||
const fields = { | ||
firstName: typeof payload.firstName === "string" ? payload.firstName : "", | ||
email: typeof payload.email === "string" ? payload.email : "", | ||
birthday: | ||
typeof payload.birthday === "string" && isDateFormat(payload.birthday) | ||
? payload.birthday | ||
: "", | ||
}; | ||
|
||
return json( | ||
{ | ||
fieldErrors: parseResult.error.flatten().fieldErrors, | ||
fields, | ||
message: null, | ||
}, | ||
{ | ||
status: 400, | ||
}, | ||
); | ||
} | ||
|
||
return json({ | ||
fieldErrors: null, | ||
fields: null, | ||
message: `Hello ${parseResult.data.firstName}! We will send an email to ${ | ||
parseResult.data.email | ||
} for your discount code in ${calculateDaysUntilNextBirthday( | ||
parseResult.data.birthday, | ||
)} days.`, | ||
}); | ||
}; | ||
|
||
const errorTextStyle: React.CSSProperties = { | ||
fontWeight: "bold", | ||
color: "red", | ||
marginInline: 0, | ||
marginBlock: "0.25rem", | ||
}; | ||
|
||
export default function RegisterView() { | ||
const actionData = useActionData<typeof action>(); | ||
const navigation = useNavigation(); | ||
const isSubmitting = navigation.state === "submitting"; | ||
|
||
if (actionData?.message) { | ||
return ( | ||
<div> | ||
<h3>{actionData.message}</h3> | ||
<hr /> | ||
<Link to="/products">View Products</Link> | ||
</div> | ||
); | ||
} | ||
|
||
return ( | ||
<div> | ||
<h1>Register for a birthday discount!</h1> | ||
<Form method="post"> | ||
<div> | ||
<label htmlFor="firstName">First Name:</label> | ||
<input | ||
type="text" | ||
id="firstName" | ||
name="firstName" | ||
defaultValue={actionData?.fields?.firstName} | ||
/> | ||
{actionData?.fieldErrors?.firstName | ||
? actionData.fieldErrors.firstName.map((error, index) => ( | ||
<p style={errorTextStyle} key={`first-name-error-${index}`}> | ||
{error} | ||
</p> | ||
)) | ||
: null} | ||
</div> | ||
|
||
<br /> | ||
|
||
<div> | ||
<label htmlFor="email">Email:</label> | ||
<input | ||
type="email" | ||
id="email" | ||
name="email" | ||
defaultValue={actionData?.fields?.email} | ||
/> | ||
{actionData?.fieldErrors?.email | ||
? actionData.fieldErrors.email.map((error, index) => ( | ||
MichaelDeBoey marked this conversation as resolved.
Show resolved
Hide resolved
|
||
<p style={errorTextStyle} key={`email-error-${index}`}> | ||
{error} | ||
</p> | ||
)) | ||
: null} | ||
</div> | ||
|
||
<br /> | ||
|
||
<div> | ||
<label htmlFor="birthday">Birthday:</label> | ||
<input | ||
type="date" | ||
id="birthday" | ||
name="birthday" | ||
defaultValue={actionData?.fields?.birthday} | ||
/> | ||
{actionData?.fieldErrors?.birthday | ||
? actionData.fieldErrors.birthday.map((error, index) => ( | ||
MichaelDeBoey marked this conversation as resolved.
Show resolved
Hide resolved
|
||
<p style={errorTextStyle} key={`birthday-error-${index}`}> | ||
{error} | ||
</p> | ||
)) | ||
: null} | ||
</div> | ||
|
||
<br /> | ||
|
||
<button type="submit" disabled={isSubmitting}> | ||
Register | ||
</button> | ||
</Form> | ||
<hr /> | ||
<Link to="/products" prefetch="intent"> | ||
View Products | ||
</Link> | ||
</div> | ||
); | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.