sharkey/packages/backend/src/server/api/endpoints/federation/stats.ts

82 lines
2.3 KiB
TypeScript
Raw Normal View History

2022-06-28 13:05:20 +09:00
import { IsNull, MoreThan, Not } from 'typeorm';
2022-09-18 03:27:08 +09:00
import { Inject, Injectable } from '@nestjs/common';
2022-09-21 05:33:11 +09:00
import type { FollowingsRepository, InstancesRepository } from '@/models/index.js';
2022-09-18 03:27:08 +09:00
import { awaitAll } from '@/misc/prelude/await-all.js';
import { Endpoint } from '@/server/api/endpoint-base.js';
import { InstanceEntityService } from '@/core/entities/InstanceEntityService.js';
import { DI } from '@/di-symbols.js';
export const meta = {
tags: ['federation'],
requireCredential: false,
allowGet: true,
cacheSec: 60 * 60,
} as const;
export const paramDef = {
type: 'object',
properties: {
2022-06-30 20:15:14 +09:00
limit: { type: 'integer', minimum: 1, maximum: 100, default: 10 },
},
required: [],
} as const;
// eslint-disable-next-line import/no-default-export
2022-09-18 03:27:08 +09:00
@Injectable()
export default class extends Endpoint<typeof meta, typeof paramDef> {
constructor(
@Inject(DI.instancesRepository)
private instancesRepository: InstancesRepository,
2022-09-18 03:27:08 +09:00
@Inject(DI.followingsRepository)
private followingsRepository: FollowingsRepository,
2022-06-28 13:05:20 +09:00
2022-09-18 03:27:08 +09:00
private instanceEntityService: InstanceEntityService,
) {
super(meta, paramDef, async (ps, me) => {
const [topSubInstances, topPubInstances, allSubCount, allPubCount] = await Promise.all([
this.instancesRepository.find({
where: {
followersCount: MoreThan(0),
},
order: {
followersCount: 'DESC',
},
take: ps.limit,
}),
this.instancesRepository.find({
where: {
followingCount: MoreThan(0),
},
order: {
followingCount: 'DESC',
},
take: ps.limit,
}),
this.followingsRepository.count({
where: {
followeeHost: Not(IsNull()),
},
}),
this.followingsRepository.count({
where: {
followerHost: Not(IsNull()),
},
}),
]);
const gotSubCount = topSubInstances.map(x => x.followersCount).reduce((a, b) => a + b, 0);
const gotPubCount = topPubInstances.map(x => x.followingCount).reduce((a, b) => a + b, 0);
return await awaitAll({
topSubInstances: this.instanceEntityService.packMany(topSubInstances),
otherFollowersCount: Math.max(0, allSubCount - gotSubCount),
topPubInstances: this.instanceEntityService.packMany(topPubInstances),
otherFollowingCount: Math.max(0, allPubCount - gotPubCount),
});
});
}
}