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

61 lines
1.7 KiB
TypeScript
Raw Normal View History

/*
* SPDX-FileCopyrightText: syuilo and other misskey contributors
* SPDX-License-Identifier: AGPL-3.0-only
*/
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';
import { genAid, parseAid } from '@/misc/id/aid.js';
import { genAidx, parseAidx } from '@/misc/id/aidx.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-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
}
/**
* IDを生成します()
* @param time
*/
@bindThis
public gen(time?: number): string {
const t = (!time || (time > Date.now())) ? Date.now() : time;
2022-12-10 00:55:07 +01:00
switch (this.method) {
case 'aid': return genAid(t);
case 'aidx': return genAidx(t);
case 'meid': return genMeid(t);
case 'meidg': return genMeidg(t);
case 'ulid': return ulid(t);
case 'objectid': return genObjectId(t);
2022-09-17 20:27:08 +02:00
default: throw new Error('unrecognized id generation method');
}
}
@bindThis
public parse(id: string): { date: Date; } {
switch (this.method) {
case 'aid': return parseAid(id);
case 'aidx': return parseAidx(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-17 20:27:08 +02:00
}