-
-
Notifications
You must be signed in to change notification settings - Fork 161
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
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
_ |
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 |
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" | ||
} | ||
} |
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(); | ||
}); |
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: 'john@doe.com', | ||
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', | ||
}, | ||
}; |
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", | ||
}, | ||
"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 {}, | ||
} | ||
`; |
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(); | ||
}); | ||
}); |
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]); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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), | ||
}; | ||
} | ||
}; |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
export * from './computed-types'; | ||
export * from './types'; |
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, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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>>; |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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'; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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]; | ||
|
There was a problem hiding this comment.
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