Sharkey/src/misc/cafy-id.ts

56 lines
1.2 KiB
TypeScript
Raw Normal View History

2018-04-24 12:13:06 +03:00
import * as mongo from 'mongodb';
2018-07-05 17:36:07 +03:00
import { Context } from 'cafy';
2018-10-16 05:38:09 +03:00
import isObjectId from './is-objectid';
2018-04-24 12:13:06 +03:00
2018-06-18 03:54:53 +03:00
export const isAnId = (x: any) => mongo.ObjectID.isValid(x);
export const isNotAnId = (x: any) => !isAnId(x);
2018-11-01 20:32:24 +02:00
export const transform = (x: string | mongo.ObjectID): mongo.ObjectID => {
if (x === undefined) return undefined;
if (x === null) return null;
2018-11-01 20:32:24 +02:00
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;
2018-04-24 12:13:06 +03:00
/**
* ID
*/
2019-02-13 09:33:07 +02:00
export default class ID<Maybe = string> extends Context<string | Maybe> {
constructor(optional = false, nullable = false) {
super(optional, nullable);
2018-04-24 12:13:06 +03:00
2018-11-01 20:32:24 +02:00
this.push((v: any) => {
2018-10-16 05:38:09 +03:00
if (!isObjectId(v) && isNotAnId(v)) {
2018-04-24 12:13:06 +03:00
return new Error('must-be-an-id');
}
return true;
});
}
2018-07-06 06:38:07 +03:00
public getType() {
return super.getType('string');
}
2019-02-13 09:33:07 +02:00
public makeOptional(): ID<undefined> {
return new ID(true, false);
}
public makeNullable(): ID<null> {
return new ID(false, true);
}
public makeOptionalNullable(): ID<undefined | null> {
return new ID(true, true);
}
2018-04-24 12:13:06 +03:00
}