Skip to content

Commit

Permalink
feat: Exposes isMongoId guard
Browse files Browse the repository at this point in the history
  • Loading branch information
ryasmi committed Jun 20, 2020
1 parent 919e7a9 commit 8772ab4
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 14 deletions.
23 changes: 11 additions & 12 deletions src/constrainedStrings/mongoId/mongoId.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { BaseError } from 'make-error'
import validator from 'validator'
import { string } from '../../valueRules/string/string'
import { constrain, Static } from '../../core'
import { isString } from '../../valueRules/string/string'
import { Constrained } from '../../core'

export class InvalidMongoIdError extends BaseError {
constructor() {
Expand All @@ -11,16 +11,15 @@ export class InvalidMongoIdError extends BaseError {

export const mongoIdSymbol = Symbol()

export type MongoId = Constrained<typeof mongoIdSymbol, string>

export function isMongoId(input: unknown): input is MongoId {
return isString(input) && validator.isMongoId(input)
}

export function mongoId(input: unknown) {
try {
const stringInput = string(input)
if (validator.isMongoId(stringInput)) {
return constrain(mongoIdSymbol, stringInput)
}
throw new Error()
} catch (err) {
throw new InvalidMongoIdError()
if (isMongoId(input)) {
return input
}
throw new InvalidMongoIdError()
}

export type MongoId = Static<typeof mongoId>
2 changes: 1 addition & 1 deletion src/constrainedStrings/mongoId/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

[Back to root readme.md](../../../readme.md)

This function can be used to check the type of the input is a valid mongoId as shown in the example below. It should only throw `rulr.InvalidMongoIdError`. This function uses [the much loved validator package](https://github.com/validatorjs/validator.js).
This function uses `rulr.isMongoId` to check the input is a valid mongoId as shown in the example below. It should only throw `rulr.InvalidMongoIdError`. This function uses [the much loved validator package](https://github.com/validatorjs/validator.js).

```ts
import * as rulr from 'rulr'
Expand Down
7 changes: 6 additions & 1 deletion src/lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,12 @@ export {
MimeType,
InvalidMimeTypeError,
} from './constrainedStrings/mimeType/mimeType'
export { mongoId, MongoId, InvalidMongoIdError } from './constrainedStrings/mongoId/mongoId'
export {
mongoId,
isMongoId,
MongoId,
InvalidMongoIdError,
} from './constrainedStrings/mongoId/mongoId'
export {
scormInteractionType,
ScormInteractionType,
Expand Down

0 comments on commit 8772ab4

Please sign in to comment.