summaryrefslogtreecommitdiff
path: root/packages/backend/src/core/entities/SystemWebhookEntityService.ts
blob: e18734091c62218e29281f4871de7e4a5a15632a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*
 * SPDX-FileCopyrightText: syuilo and misskey-project
 * SPDX-License-Identifier: AGPL-3.0-only
 */

import { Inject, Injectable } from '@nestjs/common';
import { In } from 'typeorm';
import { DI } from '@/di-symbols.js';
import type { MiSystemWebhook, SystemWebhooksRepository } from '@/models/_.js';
import { bindThis } from '@/decorators.js';
import { Packed } from '@/misc/json-schema.js';

@Injectable()
export class SystemWebhookEntityService {
	constructor(
		@Inject(DI.systemWebhooksRepository)
		private systemWebhooksRepository: SystemWebhooksRepository,
	) {
	}

	@bindThis
	public async pack(
		src: MiSystemWebhook['id'] | MiSystemWebhook,
		opts?: {
			webhooks: Map<string, MiSystemWebhook>
		},
	): Promise<Packed<'SystemWebhook'>> {
		const webhook = typeof src === 'object'
			? src
			: opts?.webhooks.get(src) ?? await this.systemWebhooksRepository.findOneByOrFail({ id: src });

		return {
			id: webhook.id,
			isActive: webhook.isActive,
			updatedAt: webhook.updatedAt.toISOString(),
			latestSentAt: webhook.latestSentAt?.toISOString() ?? null,
			latestStatus: webhook.latestStatus,
			name: webhook.name,
			on: webhook.on,
			url: webhook.url,
			secret: webhook.secret,
		};
	}

	@bindThis
	public async packMany(src: MiSystemWebhook['id'][] | MiSystemWebhook[]): Promise<Packed<'SystemWebhook'>[]> {
		if (src.length === 0) {
			return [];
		}

		const webhooks = Array.of<MiSystemWebhook>();
		webhooks.push(
			...src.filter((it): it is MiSystemWebhook => typeof it === 'object'),
		);

		const ids = src.filter((it): it is MiSystemWebhook['id'] => typeof it === 'string');
		if (ids.length > 0) {
			webhooks.push(
				...await this.systemWebhooksRepository.findBy({ id: In(ids) }),
			);
		}

		return Promise
			.all(
				webhooks.map(x =>
					this.pack(x, {
						webhooks: new Map(webhooks.map(x => [x.id, x])),
					}),
				),
			)
			.then(it => it.sort((a, b) => a.id.localeCompare(b.id)));
	}
}