2022-09-17 20:27:08 +02:00
|
|
|
import { Inject, Injectable } from '@nestjs/common';
|
|
|
|
import { ulid } from 'ulid';
|
|
|
|
import { DI } from '@/di-symbols.js';
|
2022-09-20 22:33:11 +02:00
|
|
|
import type { Config } from '@/config.js';
|
2023-04-03 04:49:58 +02:00
|
|
|
import { genAid, parseAid } from '@/misc/id/aid.js';
|
2022-09-17 20:27:08 +02:00
|
|
|
import { genMeid } from '@/misc/id/meid.js';
|
|
|
|
import { genMeidg } from '@/misc/id/meidg.js';
|
|
|
|
import { genObjectId } from '@/misc/id/object-id.js';
|
2022-12-04 07:03:09 +01:00
|
|
|
import { bindThis } from '@/decorators.js';
|
2022-09-17 20:27:08 +02:00
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
export class IdService {
|
2022-12-10 00:55:07 +01:00
|
|
|
private method: string;
|
2022-09-17 20:27:08 +02:00
|
|
|
|
|
|
|
constructor(
|
|
|
|
@Inject(DI.config)
|
|
|
|
private config: Config,
|
|
|
|
) {
|
2022-12-10 00:55:07 +01:00
|
|
|
this.method = config.id.toLowerCase();
|
2022-09-17 20:27:08 +02:00
|
|
|
}
|
|
|
|
|
2022-12-04 07:03:09 +01:00
|
|
|
@bindThis
|
2022-09-17 20:27:08 +02:00
|
|
|
public genId(date?: Date): string {
|
|
|
|
if (!date || (date > new Date())) date = new Date();
|
|
|
|
|
2022-12-10 00:55:07 +01:00
|
|
|
switch (this.method) {
|
2022-09-17 20:27:08 +02: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');
|
|
|
|
}
|
|
|
|
}
|
2023-04-03 04:49:58 +02:00
|
|
|
|
|
|
|
@bindThis
|
|
|
|
public parse(id: string): { date: Date; } {
|
|
|
|
switch (this.method) {
|
|
|
|
case 'aid': return parseAid(id);
|
|
|
|
// TODO
|
|
|
|
//case 'meid':
|
|
|
|
//case 'meidg':
|
|
|
|
//case 'ulid':
|
|
|
|
//case 'objectid':
|
|
|
|
default: throw new Error('unrecognized id generation method');
|
|
|
|
}
|
|
|
|
}
|
2022-09-17 20:27:08 +02:00
|
|
|
}
|