From 8772ab410f191bd35d7d7d3df5cd0cfd00ab524e Mon Sep 17 00:00:00 2001 From: Ryan Smith <0ryansmith1994@gmail.com> Date: Sat, 20 Jun 2020 19:23:32 +0100 Subject: [PATCH] feat: Exposes isMongoId guard --- src/constrainedStrings/mongoId/mongoId.ts | 23 +++++++++++------------ src/constrainedStrings/mongoId/readme.md | 2 +- src/lib.ts | 7 ++++++- 3 files changed, 18 insertions(+), 14 deletions(-) diff --git a/src/constrainedStrings/mongoId/mongoId.ts b/src/constrainedStrings/mongoId/mongoId.ts index ab5cbfc2d..d5141834b 100644 --- a/src/constrainedStrings/mongoId/mongoId.ts +++ b/src/constrainedStrings/mongoId/mongoId.ts @@ -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() { @@ -11,16 +11,15 @@ export class InvalidMongoIdError extends BaseError { export const mongoIdSymbol = Symbol() +export type MongoId = Constrained + +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 diff --git a/src/constrainedStrings/mongoId/readme.md b/src/constrainedStrings/mongoId/readme.md index 047c4fe7a..0c3ec9f5b 100644 --- a/src/constrainedStrings/mongoId/readme.md +++ b/src/constrainedStrings/mongoId/readme.md @@ -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' diff --git a/src/lib.ts b/src/lib.ts index 15bdecfbc..a505030a7 100644 --- a/src/lib.ts +++ b/src/lib.ts @@ -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,