misskey/packages/backend/src/core/IdService.ts

49 lines
1.4 KiB
TypeScript
Raw Normal View History

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