-
Notifications
You must be signed in to change notification settings - Fork 1
feat(validator): add unique validator constraint #179
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
Merged
Merged
Changes from 23 commits
Commits
Show all changes
24 commits
Select commit
Hold shift + click to select a range
ed8044d
Add unique constraint passing case
EmanFateen 55d0aba
Detect duplicate values in unique constraint
EmanFateen 1dc9de0
Support custom unique constraint messages
EmanFateen 9cdefee
Cover optional unique constraint values
EmanFateen 945e1f6
Validate non-array unique constraint values
EmanFateen bc0907f
Support unique constraint normalizers
EmanFateen 7d0c8ff
Support unique field combinations
EmanFateen 59bb967
Register built-in unique constraint
EmanFateen b0845a1
chore: remove unneeded test
EmanFateen 459e9aa
feat(validator): Add type validator constraint (#173)
EmanFateen 0cc1b39
Register built-in unique constraint
EmanFateen 01718be
chore: remove un-need code
EmanFateen d87d7c4
chore: code refactoring
EmanFateen 06c4dbe
chore: return violation if the value is not an array
EmanFateen 569094d
chore: in case no fields
EmanFateen c607159
chore: refactor code
EmanFateen a5f3652
chore: refactor code
EmanFateen afa5c65
chore: refactor code
EmanFateen db4c44d
chore: refactor code
EmanFateen fc0f420
chore: cover new test case
EmanFateen c210c15
chore: refactor test cases
EmanFateen 30450bc
chore: rafctor code
EmanFateen 621106d
fix: adjust semantics and unit tests
imdhemy 47bae93
chore: remove unnecessary type assertions
imdhemy File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,311 @@ | ||
| import { ConstraintContext } from '@/validator/constraint-validator'; | ||
| import { describe, expect, test } from 'vitest'; | ||
| import { unique, UniqueOptions } from './unique'; | ||
|
|
||
| describe('unique', () => { | ||
| describe('non-array values', () => { | ||
| test('validation passes when the value is undefined', () => { | ||
| const value = undefined; | ||
| const context: ConstraintContext = createContext('tags', value, { message: 'Tags must be unique' }); | ||
|
|
||
| const violations = unique(value, context); | ||
|
|
||
| expect(violations).toHaveLength(0); | ||
| }); | ||
|
|
||
| test('validation fails when the value is null', () => { | ||
| const value = null; | ||
| const context: ConstraintContext = createContext('tags', value, {} as UniqueOptions); | ||
|
|
||
| const violations = unique(value, context); | ||
|
|
||
| expect(violations).toHaveLength(1); | ||
| expect(violations[0]).toEqual({ | ||
| path: 'tags', | ||
| constraint: 'unique', | ||
| message: 'This value must be a list.', | ||
| value, | ||
| }); | ||
| }); | ||
|
|
||
| test('validation fails when the value is not an array', () => { | ||
| const value = 'admin'; | ||
| const context: ConstraintContext = createContext('tags', value, {} as UniqueOptions); | ||
|
|
||
| const violations = unique(value, context); | ||
|
|
||
| expect(violations).toHaveLength(1); | ||
| expect(violations[0]).toEqual({ | ||
| path: 'tags', | ||
| constraint: 'unique', | ||
| message: 'This value must be a list.', | ||
| value, | ||
| }); | ||
| }); | ||
| }); | ||
|
|
||
|
imdhemy marked this conversation as resolved.
|
||
| describe('arrays of scalars', () => { | ||
| test('validation passes when array elements are unique', () => { | ||
| const value = ['7', 7, true, null, undefined]; | ||
| const context: ConstraintContext = createContext('tags', value, {} as UniqueOptions); | ||
|
|
||
| const violations = unique(value, context); | ||
|
|
||
| expect(violations).toHaveLength(0); | ||
| }); | ||
|
|
||
| test('validation passes when the array contains a null value', () => { | ||
| const value = [null]; | ||
| const context: ConstraintContext = createContext('tags', value, {} as UniqueOptions); | ||
|
|
||
| const violations = unique(value, context); | ||
|
|
||
| expect(violations).toHaveLength(0); | ||
| }); | ||
|
|
||
| test('validation passes when the array contains an undefined value', () => { | ||
| const value = [undefined]; | ||
| const context: ConstraintContext = createContext('tags', value, {} as UniqueOptions); | ||
|
|
||
| const violations = unique(value, context); | ||
|
|
||
| expect(violations).toHaveLength(0); | ||
| }); | ||
|
|
||
| test('validation fails when an array contains duplicate null values', () => { | ||
| const value = [null, null]; | ||
| const context: ConstraintContext = createContext('tags', value, {} as UniqueOptions); | ||
|
|
||
| const violations = unique(value, context); | ||
|
|
||
| expect(violations).toHaveLength(1); | ||
| expect(violations[0]).toEqual({ | ||
| path: 'tags', | ||
| constraint: 'unique', | ||
| message: 'This value must contain only unique items.', | ||
| value, | ||
| }); | ||
| }); | ||
|
|
||
| test('validation fails when an array contains duplicate undefined values', () => { | ||
| const value = [undefined, undefined]; | ||
| const context: ConstraintContext = createContext('tags', value, {} as UniqueOptions); | ||
|
|
||
| const violations = unique(value, context); | ||
|
|
||
| expect(violations).toHaveLength(1); | ||
| expect(violations[0]).toEqual({ | ||
| path: 'tags', | ||
| constraint: 'unique', | ||
| message: 'This value must contain only unique items.', | ||
| value, | ||
| }); | ||
| }); | ||
|
|
||
| test('validation fails when an array contains duplicate elements', () => { | ||
| const value = ['admin', 'editor', 'admin']; | ||
| const context: ConstraintContext = createContext('tags', value, {} as UniqueOptions); | ||
|
|
||
| const violations = unique(value, context); | ||
|
|
||
| expect(violations).toHaveLength(1); | ||
| expect(violations[0]).toEqual({ | ||
| path: 'tags', | ||
| constraint: 'unique', | ||
| message: 'This value must contain only unique items.', | ||
| value, | ||
| }); | ||
| }); | ||
| }); | ||
|
|
||
| describe('arrays of arrays', () => { | ||
| test('validation passes when nested arrays have different values', () => { | ||
| const value = [['admin'], ['editor']]; | ||
| const context: ConstraintContext = createContext('tags', value, {} as UniqueOptions); | ||
|
|
||
| const violations = unique(value, context); | ||
|
|
||
| expect(violations).toHaveLength(0); | ||
| }); | ||
|
|
||
| test('validation fails when nested arrays have the same values', () => { | ||
| const value = [['admin'], ['admin']]; | ||
| const context: ConstraintContext = createContext('tags', value, {} as UniqueOptions); | ||
|
|
||
| const violations = unique(value, context); | ||
|
|
||
| expect(violations).toHaveLength(1); | ||
| expect(violations[0]).toEqual({ | ||
| path: 'tags', | ||
| constraint: 'unique', | ||
| message: 'This value must contain only unique items.', | ||
| value, | ||
| }); | ||
| }); | ||
| }); | ||
|
|
||
| describe('arrays of objects', () => { | ||
| test('validation passes when objects have different values', () => { | ||
| const value = [{ id: 1 }, { id: 2 }]; | ||
| const context: ConstraintContext = createContext('tags', value, {} as UniqueOptions); | ||
|
|
||
| const violations = unique(value, context); | ||
|
|
||
| expect(violations).toHaveLength(0); | ||
| }); | ||
|
|
||
| test('validation fails when objects have the same values', () => { | ||
| const value = [{ id: 1 }, { id: 1 }]; | ||
| const context: ConstraintContext = createContext('tags', value, {} as UniqueOptions); | ||
|
|
||
| const violations = unique(value, context); | ||
|
|
||
| expect(violations).toHaveLength(1); | ||
| expect(violations[0]).toEqual({ | ||
| path: 'tags', | ||
| constraint: 'unique', | ||
| message: 'This value must contain only unique items.', | ||
| value, | ||
| }); | ||
| }); | ||
|
|
||
| test('validation passes when the configured field combinations are unique', () => { | ||
| const value = [ | ||
| { latitude: 10, longitude: 20, label: 'first', name: 'first-location' }, | ||
| { latitude: 10, longitude: 30, label: 'first', name: 'last-location' }, | ||
| ]; | ||
| const context: ConstraintContext = createContext('coordinates', value, { | ||
| fields: ['latitude', 'longitude', 'label'], | ||
| }); | ||
|
|
||
| const violations = unique(value, context); | ||
|
|
||
| expect(violations).toHaveLength(0); | ||
| }); | ||
|
|
||
| test('validation fails when the configured field combinations contain duplicates', () => { | ||
| const value = [ | ||
| { latitude: 10, longitude: 20, label: 'first', name: 'first-location' }, | ||
| { latitude: 10, longitude: 20, label: 'first', name: 'last-location' }, | ||
| ]; | ||
| const context: ConstraintContext = createContext('coordinates', value, { | ||
| fields: ['latitude', 'longitude', 'label'], | ||
| }); | ||
|
|
||
| const violations = unique(value, context); | ||
|
|
||
| expect(violations).toHaveLength(1); | ||
| expect(violations[0]).toEqual({ | ||
| path: 'coordinates', | ||
| constraint: 'unique', | ||
| message: 'This value must contain only unique items.', | ||
| value, | ||
| }); | ||
| }); | ||
|
|
||
| test('validation fails when fields are configured and an element is not an object', () => { | ||
| const value = [{ id: 1 }, 'admin']; | ||
| const context: ConstraintContext = createContext('tags', value, { | ||
| fields: ['id'], | ||
| }); | ||
|
|
||
| const violations = unique(value, context); | ||
|
|
||
| expect(violations).toHaveLength(1); | ||
| expect(violations[0]).toEqual({ | ||
| path: 'tags', | ||
| constraint: 'unique', | ||
| message: 'This value must be a list of objects.', | ||
| value, | ||
| }); | ||
| }); | ||
| }); | ||
|
|
||
| describe('options', () => { | ||
| test('validation uses a custom message when it fails', () => { | ||
| const value = ['admin', 'admin']; | ||
| const context: ConstraintContext = createContext('tags', value, { message: 'Tags must be unique' }); | ||
|
|
||
| const violations = unique(value, context); | ||
|
|
||
| expect(violations).toHaveLength(1); | ||
| expect(violations[0]).toEqual({ | ||
| path: 'tags', | ||
| constraint: 'unique', | ||
| message: 'Tags must be unique', | ||
| value, | ||
| }); | ||
| }); | ||
|
|
||
| test('validation normalizes each array element before checking uniqueness', () => { | ||
| const value = [' admin ', 'admin']; | ||
| const context: ConstraintContext = createContext('tags', value, { | ||
| normalizer: (element: unknown) => (typeof element === 'string' ? element.trim() : element), | ||
| }); | ||
|
|
||
| const violations = unique(value, context); | ||
|
|
||
| expect(violations).toHaveLength(1); | ||
| expect(violations[0]).toEqual({ | ||
| path: 'tags', | ||
| constraint: 'unique', | ||
| message: 'This value must contain only unique items.', | ||
| value, | ||
| }); | ||
| }); | ||
|
|
||
| test('validation normalizes each object before checking configured field combinations', () => { | ||
| const value = [ | ||
| { latitude: 10, longitude: 20, label: ' first', name: 'first-location' }, | ||
| { latitude: 10, longitude: 20, label: 'first', name: 'last-location' }, | ||
| ]; | ||
| const context: ConstraintContext = createContext('coordinates', value, { | ||
| fields: ['latitude', 'longitude', 'label'], | ||
| normalizer: (element: unknown) => | ||
| typeof element === 'object' && element !== null && 'label' in element | ||
| ? { ...element, label: String(element.label).trim() } | ||
| : element, | ||
| }); | ||
|
|
||
| const violations = unique(value, context); | ||
|
|
||
| expect(violations).toHaveLength(1); | ||
| expect(violations[0]).toEqual({ | ||
| path: 'coordinates', | ||
| constraint: 'unique', | ||
| message: 'This value must contain only unique items.', | ||
| value, | ||
| }); | ||
| }); | ||
|
|
||
| test('validation fails when fields are configured and normalization returns a non-object element', () => { | ||
| const value = [{ id: 1 }, { id: 2 }]; | ||
| const context: ConstraintContext = createContext('tags', value, { | ||
| fields: ['id'], | ||
| normalizer: (element: unknown) => | ||
| typeof element === 'object' && element !== null && 'id' in element && element.id === 2 ? 'admin' : element, | ||
| }); | ||
|
|
||
| const violations = unique(value, context); | ||
|
|
||
| expect(violations).toHaveLength(1); | ||
| expect(violations[0]).toEqual({ | ||
| path: 'tags', | ||
| constraint: 'unique', | ||
| message: 'This value must be a list of objects.', | ||
| value, | ||
| }); | ||
| }); | ||
| }); | ||
|
|
||
| function createContext(path: string, value: unknown, options: UniqueOptions): ConstraintContext<UniqueOptions> { | ||
| return { | ||
| path, | ||
| root: { [path]: value }, | ||
| value, | ||
| constraint: 'unique', | ||
| options, | ||
| runNestedRules: () => [], | ||
| }; | ||
| } | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,60 @@ | ||
| import { ConstraintOptions } from '@/validator/constraint'; | ||
| import { ConstraintContext } from '@/validator/constraint-validator'; | ||
| import { Violation } from '@/validator/violation'; | ||
| import { isDeepStrictEqual } from 'node:util'; | ||
|
|
||
| const DEFAULT_MESSAGE = 'This value must contain only unique items.'; | ||
| const NOT_ARRAY_MESSAGE = 'This value must be a list.'; | ||
| const FIELDS_REQUIRE_OBJECTS_MESSAGE = 'This value must be a list of objects.'; | ||
|
imdhemy marked this conversation as resolved.
|
||
|
|
||
| export type UniqueOptions = ConstraintOptions<{ | ||
| message?: string; | ||
| normalizer?: (value: unknown) => unknown; | ||
| fields?: string[]; | ||
| }>; | ||
|
|
||
| const createViolation = (value: unknown, context: ConstraintContext, message: string): Violation => ({ | ||
| path: context.path, | ||
| constraint: context.constraint, | ||
| message, | ||
| value, | ||
| }); | ||
|
|
||
| const pickFields = (value: Record<string, unknown>, fields: string[]): Record<string, unknown> => | ||
| Object.fromEntries(fields.map(field => [field, value[field]])); | ||
|
|
||
| const normalizeElements = (value: unknown[], normalizer?: (value: unknown) => unknown): unknown[] => | ||
| normalizer ? value.map(element => normalizer(element)) : value; | ||
|
|
||
| const hasConfiguredFields = (fields?: string[]): fields is string[] => fields !== undefined && fields.length > 0; | ||
|
|
||
| const isRecord = (value: unknown): value is Record<string, unknown> => | ||
| typeof value === 'object' && value !== null && !Array.isArray(value); | ||
|
|
||
| const containsOnlyRecords = (values: unknown[]): values is Record<string, unknown>[] => values.every(isRecord); | ||
|
|
||
| const prepareComparableElements = (value: unknown[], fields?: string[]): unknown[] => | ||
| hasConfiguredFields(fields) ? value.map(element => pickFields(element as Record<string, unknown>, fields)) : value; | ||
|
|
||
| const hasOnlyUniqueValues = (values: unknown[]): boolean => | ||
| values.every((value, index) => | ||
| values.every((candidate, candidateIndex) => candidateIndex <= index || !isDeepStrictEqual(value, candidate)), | ||
|
imdhemy marked this conversation as resolved.
|
||
| ); | ||
|
|
||
|
imdhemy marked this conversation as resolved.
|
||
| export function unique(value: unknown, context: ConstraintContext<UniqueOptions>): Violation[] { | ||
| if (value === undefined) return []; | ||
|
|
||
| if (!Array.isArray(value)) return [createViolation(value, context, context.options.message ?? NOT_ARRAY_MESSAGE)]; | ||
|
|
||
| const normalizedElements = normalizeElements(value, context.options.normalizer); | ||
|
|
||
| if (hasConfiguredFields(context.options.fields) && !containsOnlyRecords(normalizedElements)) { | ||
| return [createViolation(value, context, context.options.message ?? FIELDS_REQUIRE_OBJECTS_MESSAGE)]; | ||
| } | ||
|
|
||
| const comparableElements = prepareComparableElements(normalizedElements, context.options.fields); | ||
|
|
||
| if (hasOnlyUniqueValues(comparableElements)) return []; | ||
|
|
||
| return [createViolation(value, context, context.options.message ?? DEFAULT_MESSAGE)]; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.