Skip to content

Commit

Permalink
Add support for uniqueItems in convertAction
Browse files Browse the repository at this point in the history
  • Loading branch information
nix6839 committed Oct 10, 2024
1 parent 46c1cfd commit 11e4568
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 1 deletion.
51 changes: 51 additions & 0 deletions packages/to-json-schema/src/convertAction.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -490,4 +490,55 @@ describe('convertAction', () => {
'The "transform" action cannot be converted to JSON Schema.'
);
});

test('should convert unique items action for array', () => {
expect(
convertAction(
{
type: 'array',
},
v.uniqueItems<v.ArrayInput>(),
undefined
)
).toStrictEqual({
type: 'array',
uniqueItems: true,
});
});

test('should throw error for unique items action with invalid type', () => {
expect(() =>
convertAction({}, v.uniqueItems<v.ArrayInput>(), undefined)
).toThrowError(
'The "unique_items" action is not supported on type "undefined".'
);
expect(() =>
convertAction(
{ type: 'string' },
v.uniqueItems<v.ArrayInput>(),
undefined
)
).toThrowError(
'The "unique_items" action is not supported on type "string".'
);
});

test('should force conversion for unique items action with invalid type', () => {
expect(
convertAction({}, v.uniqueItems<v.ArrayInput>(), { force: true })
).toStrictEqual({
uniqueItems: true,
});
expect(console.warn).toHaveBeenLastCalledWith(
'The "unique_items" action is not supported on type "undefined".'
);
expect(
convertAction({ type: 'string' }, v.uniqueItems<v.ArrayInput>(), {
force: true,
})
).toStrictEqual({ type: 'string', uniqueItems: true });
expect(console.warn).toHaveBeenLastCalledWith(
'The "unique_items" action is not supported on type "string".'
);
});
});
18 changes: 17 additions & 1 deletion packages/to-json-schema/src/convertAction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,11 @@ type Action =
number,
v.ErrorMessage<v.MultipleOfIssue<number, number>> | undefined
>
| v.TitleAction<unknown, string>;
| v.TitleAction<unknown, string>
| v.UniqueItemsAction<
v.ArrayInput,
v.ErrorMessage<v.UniqueItemsIssue<v.ArrayInput>> | undefined
>;

/**
* Converts any supported Valibot action to the JSON Schema format.
Expand Down Expand Up @@ -191,6 +195,18 @@ export function convertAction(
break;
}

case 'unique_items': {
if (jsonSchema.type !== 'array') {
throwOrWarn(
`The "${valibotAction.type}" action is not supported on type "${jsonSchema.type}".`,
config
);
}
jsonSchema.uniqueItems = true;

break;
}

default: {
throwOrWarn(
// @ts-expect-error
Expand Down

0 comments on commit 11e4568

Please sign in to comment.