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

feat: effect-ts resolver #676

Merged
merged 7 commits into from
May 11, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
2 changes: 1 addition & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"prettier.configPath": "./prettier.config.cjs",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
"source.fixAll.eslint": "explicit"
},
"typescript.tsdk": "node_modules/typescript/lib"
}
19 changes: 19 additions & 0 deletions effect-ts/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"name": "@hookform/resolvers/effect-ts",
"amdName": "hookformResolversEffectTs",
"version": "1.0.0",
"private": true,
"description": "React Hook Form validation resolver: effect-ts",
"main": "dist/effect-ts.js",
"module": "dist/effect-ts.module.js",
"umd:main": "dist/effect-ts.umd.js",
"source": "src/index.ts",
"types": "dist/index.d.ts",
"license": "MIT",
"peerDependencies": {
"@hookform/resolvers": "^2.0.0",
"@effect/schema": "^0.66.14",
"effect": "^3.1.2",
"react-hook-form": "^7.0.0"
}
}
88 changes: 88 additions & 0 deletions effect-ts/src/__tests__/Form-native-validation.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import { useForm } from 'react-hook-form';
import { effectTsResolver } from '..';
import { Schema } from '@effect/schema';

const USERNAME_REQUIRED_MESSAGE = 'username field is required';
const PASSWORD_REQUIRED_MESSAGE = 'password field is required';

const schema = Schema.Struct({
username: Schema.String.pipe(
Schema.nonEmpty({ message: () => USERNAME_REQUIRED_MESSAGE }),
),
password: Schema.String.pipe(
Schema.nonEmpty({ message: () => PASSWORD_REQUIRED_MESSAGE }),
),
});

interface FormData {
username: string;
password: string;
}

interface Props {
onSubmit: (data: FormData) => void;
}

function TestComponent({ onSubmit }: Props) {
const { register, handleSubmit } = useForm<FormData>({
resolver: effectTsResolver(schema),
shouldUseNativeValidation: true,
});

return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('username')} placeholder="username" />

<input {...register('password')} placeholder="password" />

<button type="submit">submit</button>
</form>
);
}

test("form's native validation with effect-ts", async () => {
const handleSubmit = vi.fn();
render(<TestComponent onSubmit={handleSubmit} />);

// username
let usernameField = screen.getByPlaceholderText(
/username/i,
) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(true);
expect(usernameField.validationMessage).toBe('');

// password
let passwordField = screen.getByPlaceholderText(
/password/i,
) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(true);
expect(passwordField.validationMessage).toBe('');

await user.click(screen.getByText(/submit/i));

// username
usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(false);
expect(usernameField.validationMessage).toBe(USERNAME_REQUIRED_MESSAGE);

// password
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(false);
expect(passwordField.validationMessage).toBe(PASSWORD_REQUIRED_MESSAGE);

await user.type(screen.getByPlaceholderText(/username/i), 'joe');
await user.type(screen.getByPlaceholderText(/password/i), 'password');

// username
usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(true);
expect(usernameField.validationMessage).toBe('');

// password
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(true);
expect(passwordField.validationMessage).toBe('');
});
59 changes: 59 additions & 0 deletions effect-ts/src/__tests__/Form.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import { useForm } from 'react-hook-form';
import { effectTsResolver } from '..';
import { Schema } from '@effect/schema';

const USERNAME_REQUIRED_MESSAGE = 'username field is required';
const PASSWORD_REQUIRED_MESSAGE = 'password field is required';

const schema = Schema.Struct({
username: Schema.String.pipe(
Schema.nonEmpty({ message: () => USERNAME_REQUIRED_MESSAGE }),
),
password: Schema.String.pipe(
Schema.nonEmpty({ message: () => PASSWORD_REQUIRED_MESSAGE }),
),
});

type FormData = Schema.Schema.Type<typeof schema>;

interface Props {
onSubmit: (data: FormData) => void;
}

function TestComponent({ onSubmit }: Props) {
const {
register,
handleSubmit,
formState: { errors },
} = useForm<FormData>({
resolver: effectTsResolver(schema), // Useful to check TypeScript regressions
});

return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('username')} />
{errors.username && <span role="alert">{errors.username.message}</span>}

<input {...register('password')} />
{errors.password && <span role="alert">{errors.password.message}</span>}

<button type="submit">submit</button>
</form>
);
}

test("form's validation with Zod and TypeScript's integration", async () => {
const handleSubmit = vi.fn();
render(<TestComponent onSubmit={handleSubmit} />);

expect(screen.queryAllByRole('alert')).toHaveLength(0);

await user.click(screen.getByText(/submit/i));

expect(screen.getByText(/username field is required/i)).toBeInTheDocument();
expect(screen.getByText(/password field is required/i)).toBeInTheDocument();
expect(handleSubmit).not.toHaveBeenCalled();
});
124 changes: 124 additions & 0 deletions effect-ts/src/__tests__/__fixtures__/data.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import { Schema } from '@effect/schema';
import { Field, InternalFieldName } from 'react-hook-form';

export const schema = Schema.Struct({
username: Schema.String.pipe(
Schema.nonEmpty({ message: () => 'A username is required' }),
),
password: Schema.String.pipe(
Schema.pattern(new RegExp('.*[A-Z].*'), {
message: () => 'At least 1 uppercase letter.',
}),
Schema.pattern(new RegExp('.*[a-z].*'), {
message: () => 'At least 1 lowercase letter.',
}),
Schema.pattern(new RegExp('.*\\d.*'), {
message: () => 'At least 1 number.',
}),
Schema.pattern(
new RegExp('.*[`~<>?,./!@#$%^&*()\\-_+="\'|{}\\[\\];:\\\\].*'),
{
message: () => 'At least 1 special character.',
},
),
Schema.minLength(8, { message: () => 'Must be at least 8 characters.' }),
),
accessToken: Schema.Union(Schema.String, Schema.Number),
birthYear: Schema.Number.pipe(
Schema.greaterThan(1900, {
message: () => 'Must be greater than the year 1900',
}),
Schema.filter((value) => value < new Date().getFullYear(), {
message: () => 'Must be before the current year.',
}),
),
email: Schema.String.pipe(
Schema.pattern(
new RegExp(
/^(?!\.)(?!.*\.\.)([A-Z0-9_+-.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9-]*\.)+[A-Z]{2,}$/i,
),
{
message: () => 'A valid email address is required.',
},
),
),
tags: Schema.Array(
Schema.Struct({
name: Schema.String,
}),
),
luckyNumbers: Schema.Array(Schema.Number),
enabled: Schema.Boolean,
animal: Schema.Union(Schema.String, Schema.Literal('bird', 'snake')),
vehicles: Schema.Array(
Schema.Union(
Schema.Struct({
type: Schema.Literal('car'),
brand: Schema.String,
horsepower: Schema.Number,
}),
Schema.Struct({
type: Schema.Literal('bike'),
speed: Schema.Number,
}),
),
),
});

export const validData: Schema.Schema.Type<typeof schema> = {
accessToken: 'abcd1234',
animal: 'dog',
birthYear: 2000,
email: '[email protected]',
enabled: true,
luckyNumbers: [1, 2, 3, 4, 5],
password: 'Super#Secret123',
tags: [{ name: 'move' }, { name: 'over' }, { name: 'zod' }, { name: ';)' }],
username: 'johnDoe',
vehicles: [
{ type: 'bike', speed: 5 },
{ type: 'car', brand: 'BMW', horsepower: 150 },
],
};

export const invalidData = {
username: 'test',
password: 'Password123',
repeatPassword: 'Password123',
birthYear: 2000,
accessToken: '1015d809-e99d-41ec-b161-981a3c243df8',
email: '[email protected]',
tags: [{ name: 'test' }],
enabled: true,
animal: ['dog'],
luckyNumbers: [1, 2, '3'],
like: [
{
id: '1',
name: 'name',
},
],
vehicles: [
{ type: 'car', brand: 'BMW', horsepower: 150 },
{ type: 'car', brand: 'Mercedes' },
],
};

export const fields: Record<InternalFieldName, Field['_f']> = {
username: {
ref: { name: 'username' },
name: 'username',
},
password: {
ref: { name: 'password' },
name: 'password',
},
email: {
ref: { name: 'email' },
name: 'email',
},
birthday: {
ref: { name: 'birthday' },
name: 'birthday',
},
};
40 changes: 40 additions & 0 deletions effect-ts/src/__tests__/__snapshots__/effect-ts.ts.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html

exports[`effectTsResolver > should return a single error from effectTsResolver when validation fails 1`] = `
{
"errors": {
"animal": {
"message": "Expected \\"snake\\", actual [\\"dog\\"]",
"ref": undefined,
"type": "Type",
},
"luckyNumbers": [
,
,
{
"message": "Expected a number, actual \\"3\\"",
"ref": undefined,
"type": "Type",
},
],
"password": {
"message": "At least 1 special character.",
"ref": {
"name": "password",
},
"type": "Refinement",
},
"vehicles": [
,
{
"horsepower": {
"message": "is missing",
"ref": undefined,
"type": "Missing",
},
},
],
},
"values": {},
}
`;
24 changes: 24 additions & 0 deletions effect-ts/src/__tests__/effect-ts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { effectTsResolver } from '..';
import { schema, validData, fields, invalidData } from './__fixtures__/data';

const shouldUseNativeValidation = false;

describe('effectTsResolver', () => {
it('should return values from effectTsResolver when validation pass', async () => {
const result = await effectTsResolver(schema)(validData, undefined, {
fields,
shouldUseNativeValidation,
});

expect(result).toEqual({ errors: {}, values: validData });
});

it('should return a single error from effectTsResolver when validation fails', async () => {
const result = await effectTsResolver(schema)(invalidData, undefined, {
fields,
shouldUseNativeValidation,
});

expect(result).toMatchSnapshot();
});
});
Loading