-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: implement validator to validate a collection of record links
- Loading branch information
1 parent
85c79d4
commit 74b8fc6
Showing
3 changed files
with
50 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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,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; | ||
}; | ||
}; |
This file contains 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