Skip to content

Commit

Permalink
feat: pass field names and a context as arguments to a Vest suite (#584)
Browse files Browse the repository at this point in the history
  • Loading branch information
vonagam committed Aug 17, 2023
1 parent e5e7346 commit 3519701
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 10 deletions.
13 changes: 13 additions & 0 deletions vest/src/__tests__/vest.ts
Expand Up @@ -68,4 +68,17 @@ describe('vestResolver', () => {
),
).toMatchSnapshot();
});

it('should call a suite with values, validated field names and a context as arguments', async () => {
const suite = vi.fn(validationSuite) as any as typeof validationSuite;

await vestResolver(suite)(validData, { some: 'context' }, {
fields: { username: fields.username },
names: ['username'],
shouldUseNativeValidation,
});

expect(suite).toHaveBeenCalledTimes(1);
expect(suite).toHaveBeenCalledWith(validData, ['username'], { some: 'context' });
});
});
17 changes: 10 additions & 7 deletions vest/src/types.ts
@@ -1,20 +1,23 @@
import {
FieldValues,
FieldName,
ResolverOptions,
ResolverResult,
} from 'react-hook-form';
import * as Vest from 'vest';

export type ICreateResult = ReturnType<typeof Vest.create>;
export type ICreateResult<TValues extends FieldValues = FieldValues, TContext = any> = ReturnType<
typeof Vest.create<(values: TValues, names?: FieldName<TValues>[], context?: TContext) => void>
>;

export type Resolver = (
schema: ICreateResult,
export type Resolver = <TValues extends FieldValues, TContext>(
schema: ICreateResult<TValues, TContext>,
schemaOptions?: never,
factoryOptions?: { mode?: 'async' | 'sync', rawValues?: boolean; },
) => <TFieldValues extends FieldValues, TContext>(
values: TFieldValues,
) => (
values: TValues,
context: TContext | undefined,
options: ResolverOptions<TFieldValues>,
) => Promise<ResolverResult<TFieldValues>>;
options: ResolverOptions<TValues>,
) => Promise<ResolverResult<TValues>>;

export type VestErrors = Record<string, string[]>;
6 changes: 3 additions & 3 deletions vest/src/vest.ts
Expand Up @@ -25,11 +25,11 @@ const parseErrorSchema = (

export const vestResolver: Resolver =
(schema, _, resolverOptions = {}) =>
async (values, _context, options) => {
async (values, context, options) => {
const result =
resolverOptions.mode === 'sync'
? schema(values)
: await promisify(schema)(values);
? schema(values, options.names, context)
: await promisify(schema)(values, options.names, context);

if (result.hasErrors()) {
return {
Expand Down

0 comments on commit 3519701

Please sign in to comment.