2023-07-27 05:31:52 +00:00
|
|
|
/*
|
|
|
|
* SPDX-FileCopyrightText: syuilo and other misskey contributors
|
|
|
|
* SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
*/
|
|
|
|
|
2022-09-17 18:27:08 +00:00
|
|
|
import { Inject, Injectable } from '@nestjs/common';
|
|
|
|
import { ulid } from 'ulid';
|
|
|
|
import { DI } from '@/di-symbols.js';
|
2022-09-20 20:33:11 +00:00
|
|
|
import type { Config } from '@/config.js';
|
2023-04-03 02:49:58 +00:00
|
|
|
import { genAid, parseAid } from '@/misc/id/aid.js';
|
2023-09-06 09:33:51 +00:00
|
|
|
import { genAidx, parseAidx } from '@/misc/id/aidx.js';
|
2023-04-08 19:41:06 +00:00
|
|
|
import { genMeid, parseMeid } from '@/misc/id/meid.js';
|
|
|
|
import { genMeidg, parseMeidg } from '@/misc/id/meidg.js';
|
2023-06-23 07:30:47 +00:00
|
|
|
import { genObjectId, parseObjectId } from '@/misc/id/object-id.js';
|
2022-12-04 06:03:09 +00:00
|
|
|
import { bindThis } from '@/decorators.js';
|
2023-04-08 19:41:06 +00:00
|
|
|
import { parseUlid } from '@/misc/id/ulid.js';
|
2022-09-17 18:27:08 +00:00
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
export class IdService {
|
2022-12-09 23:55:07 +00:00
|
|
|
private method: string;
|
2022-09-17 18:27:08 +00:00
|
|
|
|
|
|
|
constructor(
|
|
|
|
@Inject(DI.config)
|
|
|
|
private config: Config,
|
|
|
|
) {
|
2022-12-09 23:55:07 +00:00
|
|
|
this.method = config.id.toLowerCase();
|
2022-09-17 18:27:08 +00:00
|
|
|
}
|
|
|
|
|
2023-10-16 01:45:22 +00:00
|
|
|
/**
|
|
|
|
* 時間を元にIDを生成します(省略時は現在日時)
|
|
|
|
* @param time 日時
|
|
|
|
*/
|
2022-12-04 06:03:09 +00:00
|
|
|
@bindThis
|
2023-10-16 01:45:22 +00:00
|
|
|
public gen(time?: number): string {
|
|
|
|
const t = (!time || (time > Date.now())) ? Date.now() : time;
|
2023-07-07 22:08:16 +00:00
|
|
|
|
2022-12-09 23:55:07 +00:00
|
|
|
switch (this.method) {
|
2023-10-16 01:45:22 +00:00
|
|
|
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 18:27:08 +00:00
|
|
|
default: throw new Error('unrecognized id generation method');
|
|
|
|
}
|
|
|
|
}
|
2023-04-03 02:49:58 +00:00
|
|
|
|
|
|
|
@bindThis
|
|
|
|
public parse(id: string): { date: Date; } {
|
|
|
|
switch (this.method) {
|
|
|
|
case 'aid': return parseAid(id);
|
2023-09-06 09:33:51 +00:00
|
|
|
case 'aidx': return parseAidx(id);
|
2023-06-23 07:30:47 +00:00
|
|
|
case 'objectid': return parseObjectId(id);
|
2023-04-08 19:41:06 +00:00
|
|
|
case 'meid': return parseMeid(id);
|
|
|
|
case 'meidg': return parseMeidg(id);
|
|
|
|
case 'ulid': return parseUlid(id);
|
2023-04-03 02:49:58 +00:00
|
|
|
default: throw new Error('unrecognized id generation method');
|
|
|
|
}
|
|
|
|
}
|
2022-09-17 18:27:08 +00:00
|
|
|
}
|