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: computed-types resolver #162

Merged
merged 4 commits into from
May 12, 2021
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
1 change: 0 additions & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ module.exports = {
plugins: ['@typescript-eslint'],
extends: [
'plugin:@typescript-eslint/recommended',
'prettier/@typescript-eslint',
'plugin:prettier/recommended',
],
parserOptions: {
Expand Down
1 change: 1 addition & 0 deletions .husky/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
_
5 changes: 5 additions & 0 deletions .husky/pre-commit
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

yarn lint:types
yarn lint-staged
41 changes: 41 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,47 @@ const App = () => {
export default App;
```

### [computed-types](https://github.com/neuledge/computed-types)

TypeScript-first schema validation with static type inference

[![npm](https://img.shields.io/bundlephobia/minzip/computed-types?style=for-the-badge)](https://bundlephobia.com/result?p=computed-types)

```tsx
import React from 'react';
import { useForm } from 'react-hook-form';
import { computedTypesResolver } from '@hookform/resolvers/zod';
import Schema, { number, string } from 'computed-types';

const schema = Schema({
username: string.trim().error('username field is required'),
password: string.trim().error('password field is required'),
password: number,
});

const App = () => {
const {
register,
handleSubmit,
formState: { errors },
} = useForm({
resolver: computedTypesResolver(schema),
});

return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('name')} />
{errors.name?.message && <p>{errors.name?.message}</p>}
<input type="number" {...register('age', { valueAsNumber: true })} />
{errors.age?.message && <p>{errors.age?.message}</p>}
<input type="submit" />
</form>
);
};

export default App;
```

## Backers

Thanks goes to all our backers! [[Become a backer](https://opencollective.com/react-hook-form#backer)].
Expand Down
17 changes: 17 additions & 0 deletions computed-types/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"name": "computed-types",
"amdName": "hookformResolversComputedTypes",
"version": "1.0.0",
"private": true,
"description": "React Hook Form validation resolver: computed-types",
"main": "dist/computed-types.js",
"module": "dist/computed-types.module.js",
"umd:main": "dist/computed-types.umd.js",
"source": "src/index.ts",
"types": "dist/index.d.ts",
"license": "MIT",
"peerDependencies": {
"react-hook-form": "^7.0.0",
"@hookform/resolvers": "^2.0.0"
}
}
54 changes: 54 additions & 0 deletions computed-types/src/__tests__/Form.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import React from 'react';
import { render, screen, act } from '@testing-library/react';
import user from '@testing-library/user-event';
import { useForm } from 'react-hook-form';
import Schema, { Type, string } from 'computed-types';
import { computedTypesResolver } from '..';

const schema = Schema({
username: string.trim().error('username field is required'),
password: string.trim().error('password field is required'),
});

type FormData = Type<typeof schema> & { unusedProperty: string };

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

function TestComponent({ onSubmit }: Props) {
const {
register,
handleSubmit,
formState: { errors },
} = useForm<FormData>({
resolver: computedTypesResolver(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 computed-types and TypeScript's integration", async () => {
const handleSubmit = jest.fn();
render(<TestComponent onSubmit={handleSubmit} />);

expect(screen.queryAllByRole(/alert/i)).toHaveLength(0);

await act(async () => {
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();
});
72 changes: 72 additions & 0 deletions computed-types/src/__tests__/__fixtures__/data.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { Field, InternalFieldName } from 'react-hook-form';
import Schema, { Type, string, number, array, boolean } from 'computed-types';

export const schema = Schema({
username: string.regexp(/^\w+$/).min(3).max(30),
password: string
.regexp(new RegExp('.*[A-Z].*'), 'One uppercase character')
.regexp(new RegExp('.*[a-z].*'), 'One lowercase character')
.regexp(new RegExp('.*\\d.*'), 'One number')
.regexp(
new RegExp('.*[`~<>?,./!@#$%^&*()\\-_+="\'|{}\\[\\];:\\\\].*'),
'One special character',
)
.min(8, 'Must be at least 8 characters in length'),
repeatPassword: string,
accessToken: Schema.either(string, number).optional(),
birthYear: number.min(1900).max(2013).optional(),
email: string
.regexp(/^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/)
.error('Incorrect email'),
tags: array.of(string),
enabled: boolean,
like: array
.of({
id: number,
name: string.min(4).max(4),
})
.optional(),
});

export const validData: Type<typeof schema> = {
username: 'Doe',
password: 'Password123_',
repeatPassword: 'Password123_',
accessToken: 'accessToken',
birthYear: 2000,
email: '[email protected]',
tags: ['tag1', 'tag2'],
enabled: true,
like: [
{
id: 1,
name: 'name',
},
],
};

export const invalidData = {
password: '___',
email: '',
birthYear: 'birthYear',
like: [{ id: 'z' }],
};

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',
},
};
65 changes: 65 additions & 0 deletions computed-types/src/__tests__/__snapshots__/computed-types.ts.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`computedTypesResolver should return a single error from computedTypesResolver when validation fails 1`] = `
Object {
"errors": Object {
"birthYear": Object {
"message": "Expect value to be \\"number\\"",
"ref": undefined,
"type": "ValidationError",
Copy link
Member Author

@jorisre jorisre May 8, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Always the same type, feel free to suggest a better way

},
"email": Object {
"message": "Incorrect email",
"ref": Object {
"name": "email",
},
"type": "ValidationError",
},
"enabled": Object {
"message": "Expect value to be \\"boolean\\"",
"ref": undefined,
"type": "ValidationError",
},
"like": Object {
"id": Object {
"message": "Expect value to be \\"number\\"",
"ref": undefined,
"type": "ValidationError",
},
"message": "id: Expect value to be \\"number\\"",
"name": Object {
"message": "Expect value to be \\"string\\"",
"ref": undefined,
"type": "ValidationError",
},
"ref": undefined,
"type": "ValidationError",
},
"password": Object {
"message": "One uppercase character",
"ref": Object {
"name": "password",
},
"type": "ValidationError",
},
"repeatPassword": Object {
"message": "Expect value to be \\"string\\"",
"ref": undefined,
"type": "ValidationError",
},
"tags": Object {
"message": "Expecting value to be an array",
"ref": undefined,
"type": "ValidationError",
},
"username": Object {
"message": "Expect value to be \\"string\\"",
"ref": Object {
"name": "username",
},
"type": "ValidationError",
},
},
"values": Object {},
}
`;
20 changes: 20 additions & 0 deletions computed-types/src/__tests__/computed-types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { computedTypesResolver } from '..';
import { schema, validData, invalidData, fields } from './__fixtures__/data';

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

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

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

expect(result).toMatchSnapshot();
});
});
42 changes: 42 additions & 0 deletions computed-types/src/computed-types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import type { FieldErrors } from 'react-hook-form';
import { toNestError } from '@hookform/resolvers';
import type { ValidationError } from 'computed-types';
import type { Resolver } from './types';

const parseErrorSchema = (
computedTypesError: ValidationError,
parsedErrors: FieldErrors = {},
path = '',
) => {
return (computedTypesError.errors || []).reduce((acc, error) => {
const _currentPath = String(error.path[0]);
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

path is always an array of one item

const _path = path ? `${path}.${_currentPath}` : _currentPath;

acc[_path] = {
type: error.error.name,
message: error.error.message,
};

parseErrorSchema(error.error, acc, _path);

return acc;
}, parsedErrors);
};

export const computedTypesResolver: Resolver = (schema) => async (
values,
_,
options,
) => {
try {
return {
errors: {},
values: await schema(values),
};
} catch (error) {
return {
values: {},
errors: toNestError(parseErrorSchema(error), options.fields),
};
}
};
2 changes: 2 additions & 0 deletions computed-types/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './computed-types';
export * from './types';
14 changes: 14 additions & 0 deletions computed-types/src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import type {
FieldValues,
ResolverResult,
UnpackNestedValue,
ResolverOptions,
} from 'react-hook-form';

export type Resolver = (
schema: any,
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can't find a good way to type the schema.

@kotarella1110 if you want to play with that one, (no worries if you haven't time :))

) => <TFieldValues extends FieldValues, TContext>(
values: UnpackNestedValue<TFieldValues>,
context: TContext | undefined,
options: ResolverOptions<TFieldValues>,
) => Promise<ResolverResult<TFieldValues>>;
1 change: 1 addition & 0 deletions config/node-13-exports.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const subRepositories = [
'class-validator',
'io-ts',
'nope',
'computed-types',
];

const copySrc = () => {
Expand Down
2 changes: 1 addition & 1 deletion nope/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type {
ResolverResult,
UnpackNestedValue,
} from 'react-hook-form';
import type NopeObject from 'nope-validator/lib/cjs/NopeObject';
import type { NopeObject } from 'nope-validator/lib/cjs/NopeObject';
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nope V1 update


type ValidateOptions = Parameters<NopeObject['validate']>[2];
type Context = Parameters<NopeObject['validate']>[1];
Expand Down
Loading