2022-09-17 21:27:08 +03:00
|
|
|
import { Inject, Injectable } from '@nestjs/common';
|
|
|
|
import { ulid } from 'ulid';
|
|
|
|
import { DI } from '@/di-symbols.js';
|
|
|
|
import { Config } from '@/config.js';
|
|
|
|
import { genAid } from '@/misc/id/aid.js';
|
|
|
|
import { genMeid } from '@/misc/id/meid.js';
|
|
|
|
import { genMeidg } from '@/misc/id/meidg.js';
|
|
|
|
import { genObjectId } from '@/misc/id/object-id.js';
|
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
export class IdService {
|
2022-09-18 21:11:50 +03:00
|
|
|
private metohd: string;
|
2022-09-17 21:27:08 +03:00
|
|
|
|
|
|
|
constructor(
|
|
|
|
@Inject(DI.config)
|
|
|
|
private config: Config,
|
|
|
|
) {
|
2022-09-18 21:11:50 +03:00
|
|
|
this.metohd = config.id.toLowerCase();
|
2022-09-17 21:27:08 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
public genId(date?: Date): string {
|
|
|
|
if (!date || (date > new Date())) date = new Date();
|
|
|
|
|
2022-09-18 21:11:50 +03:00
|
|
|
switch (this.metohd) {
|
2022-09-17 21:27:08 +03:00
|
|
|
case 'aid': return genAid(date);
|
|
|
|
case 'meid': return genMeid(date);
|
|
|
|
case 'meidg': return genMeidg(date);
|
|
|
|
case 'ulid': return ulid(date.getTime());
|
|
|
|
case 'objectid': return genObjectId(date);
|
|
|
|
default: throw new Error('unrecognized id generation method');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|