@sonibble-creators/nest-microservice-pack
Version:
Microservice pack dependencies for NestJS
40 lines (35 loc) • 1.02 kB
text/typescript
import { IPrimaryKey, Primary } from '@mikro-orm/core';
import { MongoDriver, MongoPlatform, ObjectId } from '@mikro-orm/mongodb';
/**
* # StringMongoPlatform
*
* The string platform for serialize and deserialized of
* primary key.
*
* The concept is enable to use the string and validate to the
* primary key
*/
export class StringMongoPlatform extends MongoPlatform {
normalizePrimaryKey<T = number | string>(
data: Primary<T> | IPrimaryKey | ObjectId,
): T {
if (data instanceof ObjectId) {
return data.toHexString() as unknown as T;
}
return data as unknown as T;
}
denormalizePrimaryKey(data: number | string): IPrimaryKey {
return '' + data;
}
}
/**
* # StringMongoDriver
*
* Allow to use string in id (ObjectId) as primary key
* The result is become same, but when we need to get and use string type of id,
* this will be good choices
*
*/
export class StringMongoDriver extends MongoDriver {
protected readonly platform = new StringMongoPlatform();
}