summaryrefslogtreecommitdiff
path: root/src/misc/cafy-id.ts
blob: 621f7e79484bd50a13a46b397542d8569291a35f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import * as mongo from 'mongodb';
import { Context } from 'cafy';
import isObjectId from './is-objectid';

export const isAnId = (x: any) => mongo.ObjectID.isValid(x);
export const isNotAnId = (x: any) => !isAnId(x);
export const transform = (x: string | mongo.ObjectID): mongo.ObjectID => {
	if (x == null) return null;

	if (isAnId(x) && !isObjectId(x)) {
		return new mongo.ObjectID(x);
	} else {
		return x as mongo.ObjectID;
	}
};
export const transformMany = (xs: (string | mongo.ObjectID)[]): mongo.ObjectID[] => {
	if (xs == null) return null;

	return xs.map(x => transform(x));
};

export type ObjectId = mongo.ObjectID;

/**
 * ID
 */
export default class ID extends Context<string> {
	constructor() {
		super();

		this.push((v: any) => {
			if (!isObjectId(v) && isNotAnId(v)) {
				return new Error('must-be-an-id');
			}
			return true;
		});
	}

	public getType() {
		return super.getType('string');
	}
}