Skip to content

Commit

Permalink
feat: implement validator to validate a collection of record links
Browse files Browse the repository at this point in the history
  • Loading branch information
IamSebastianDev committed Feb 26, 2023
1 parent 85c79d4 commit 74b8fc6
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ export {
ValidateNested,
Contains,
IsString,
CollectionOf,
RecordFrom,
Link,
} from './lib';
export type { Collection, ObjectId, JSONDocument } from './lib';
Expand Down
47 changes: 47 additions & 0 deletions src/lib/Validators/CollectionOf.validator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/** @format */

import { RecordLink, ValidatorFunction } from '../../types';
import { FlotsamValidationError } from '../../utils';
import { Collection, ObjectId } from '../Db';
import { isRecordLink } from './isRecordLink.util';

export const CollectionOf = (collection: string | Collection<Record<PropertyKey, unknown>>): ValidatorFunction => {
let namespace = collection;

if (collection instanceof Collection && 'namespace' in collection) {
namespace = collection.namespace;
}

return <T, K>(value: unknown, propertyName?: string, document?: K) => {
// skip null or undefined values by default
if (value === null || value === undefined) {
return true;
}

if (!Array.isArray(value)) {
throw new FlotsamValidationError(
`Expected property '${propertyName}' to be of type 'Array'. Found property to be of type '${typeof value}' instead.`
);
}

if (Array.isArray(value)) {
return value.every((entry, index) => {
if (isRecordLink(entry)) {
const [parsedNamespace, id] = entry.split(':');

if (!ObjectId.is(id)) {
throw new FlotsamValidationError(
`Expected property '${propertyName}'[${index}] to be a valid RecordLink of Collection '${namespace}'.`
);
}

return parsedNamespace === namespace && ObjectId.is(id);
}

return false;
});
}

return true;
};
};
1 change: 1 addition & 0 deletions src/lib/Validators/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@ export { IsString } from './IsString.validator';
export type { ValidatorFunction } from '../../types';
export { IsDate } from './IsDate.validator';
export { ValidateNested } from './ValidateNested';
export { CollectionOf } from './CollectionOf.validator';
export { RecordFrom } from './RecordFrom.validator';

0 comments on commit 74b8fc6

Please sign in to comment.