Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] POC: Introducing total/activity generic metric API endpoints #40

Open
wants to merge 1 commit into
base: develop-stable
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
159 changes: 159 additions & 0 deletions apps/api/src/activity/activity.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
import {
ApiBadRequestResponse,
ApiParam,
ApiQuery,
ApiResponse,
ApiTags,
} from '@nestjs/swagger';
import { Controller, Get, Param, Query } from '@nestjs/common';

import {
ContractContext,
MetricResponse,
MetricQuery,
LeaderboardMetricResponse,
TotalMetric,
DaoStatsMetric,
DaoContractContext,
} from '@dao-stats/common';
import { ActivityInterval } from '@dao-stats/common/types/activity-interval';

import { ContractContextPipe, MetricQueryPipe } from '../pipes';
import { ActivityApiMetricService } from './interfaces/activity-api-metric.interface';
import { ActivityApiMetricPipe } from './pipes/activity-api-metric.pipe';
import { ActivityApiMetric } from './types/activity-api-metric';

@ApiTags('Activity')
@Controller('activity')
export class ActivityController {
@ApiResponse({
status: 200,
type: TotalMetric,
})
@ApiBadRequestResponse({
description: 'Bad Request Response based on the query params set',
})
@ApiParam({
name: 'metric',
description: `Activity Metric: e.g ${ActivityApiMetric.DaoActivity}`,
enum: ActivityApiMetric,
})
@ApiQuery({
name: 'interval',
description: `Activity Interval: e.g ${ActivityInterval.Week}`,
enum: ActivityInterval,
})
@Get('/:metric')
async totals(
@Param(ContractContextPipe) context: ContractContext,
@Param('metric', ActivityApiMetricPipe)
service: ActivityApiMetricService<ActivityApiMetric>,
@Query('interval') interval: ActivityInterval,
): Promise<TotalMetric> {
return service.getActivity(context, interval);
}

@ApiResponse({
status: 200,
type: MetricResponse,
})
@ApiBadRequestResponse({
description: 'Bad Request Response based on the query params set',
})
@ApiParam({
name: 'metric',
description: `Total Metric: e.g ${DaoStatsMetric.DaoCount}`,
enum: ActivityApiMetric,
})
@ApiQuery({
name: 'interval',
description: `Activity Interval: e.g ${ActivityInterval.Week}`,
enum: ActivityInterval,
})
@Get('/:metric/history')
async history(
@Param(ContractContextPipe) context: ContractContext,
@Param('metric', ActivityApiMetricPipe)
service: ActivityApiMetricService<ActivityApiMetric>,
@Query(MetricQueryPipe) metricQuery: MetricQuery,
@Query('interval') interval: ActivityInterval,
): Promise<MetricResponse> {
return service.getHistory(context, metricQuery, interval);
}

@ApiResponse({
status: 200,
type: LeaderboardMetricResponse,
})
@ApiBadRequestResponse({
description: 'Bad Request Response based on the query params set',
})
@ApiParam({
name: 'metric',
description: `Total Metric: e.g ${DaoStatsMetric.DaoCount}`,
enum: ActivityApiMetric,
})
@Get('/:metric/leaderboard')
async leaderboard(
@Param(ContractContextPipe) context: ContractContext,
@Param('metric', ActivityApiMetricPipe)
service: ActivityApiMetricService<ActivityApiMetric>,
): Promise<LeaderboardMetricResponse> {
return service.getLeaderboard(context);
}

@ApiResponse({
status: 200,
type: TotalMetric,
})
@ApiBadRequestResponse({
description: 'Bad Request Response based on the query params set',
})
@ApiParam({
name: 'metric',
description: `Activity Metric: e.g ${ActivityApiMetric.DaoActivity}`,
enum: ActivityApiMetric,
})
@ApiQuery({
name: 'interval',
description: `Activity Interval: e.g ${ActivityInterval.Week}`,
enum: ActivityInterval,
})
@Get('/:metric/:dao')
async daoTotals(
@Param(ContractContextPipe) context: DaoContractContext,
@Param('metric', ActivityApiMetricPipe)
service: ActivityApiMetricService<ActivityApiMetric>,
@Query('interval') interval: ActivityInterval,
): Promise<TotalMetric> {
return service.getActivity(context, interval);
}

@ApiResponse({
status: 200,
type: MetricResponse,
})
@ApiBadRequestResponse({
description: 'Bad Request Response based on the query params set',
})
@ApiParam({
name: 'metric',
description: `Activity Metric: e.g ${ActivityApiMetric.DaoActivity}`,
enum: ActivityApiMetric,
})
@ApiQuery({
name: 'interval',
description: `Activity Interval: e.g ${ActivityInterval.Week}`,
enum: ActivityInterval,
})
@Get('/:metric/:dao/history')
async daoHistory(
@Param(ContractContextPipe) context: DaoContractContext,
@Param('metric', ActivityApiMetricPipe)
service: ActivityApiMetricService<ActivityApiMetric>,
@Query(MetricQueryPipe) metricQuery: MetricQuery,
@Query('interval') interval: ActivityInterval,
): Promise<MetricResponse> {
return service.getHistory(context, metricQuery, interval);
}
}
21 changes: 21 additions & 0 deletions apps/api/src/activity/activity.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { CacheModule, Module } from '@nestjs/common';

import { CacheConfigService } from '@dao-stats/config/cache';
import { ContractModule } from '@dao-stats/common';
import { TransactionModule } from '@dao-stats/transaction';

import { ActivityController } from './activity.controller';
import metrics from './metrics';

@Module({
imports: [
CacheModule.registerAsync({
useClass: CacheConfigService,
}),
TransactionModule,
ContractModule,
],
providers: [...metrics],
controllers: [ActivityController],
})
export class ActivityModule {}
29 changes: 29 additions & 0 deletions apps/api/src/activity/interfaces/activity-api-metric.interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import {
ContractContext,
LeaderboardMetricResponse,
MetricQuery,
MetricResponse,
TotalMetric,
} from '@dao-stats/common';
import { ActivityInterval } from '@dao-stats/common/types/activity-interval';

import { ApiMetricService } from '../../common/interfaces/api-metric.interface';
import { ActivityApiMetric } from '../types/activity-api-metric';

export interface ActivityApiMetricService<T extends ActivityApiMetric>
extends ApiMetricService<T> {
getType(): T;

getActivity(
context: ContractContext,
interval: ActivityInterval,
): Promise<TotalMetric>;

getHistory(
context: ContractContext,
metricQuery: MetricQuery,
interval?: string,
): Promise<MetricResponse>;

getLeaderboard(context: ContractContext): Promise<LeaderboardMetricResponse>;
}
127 changes: 127 additions & 0 deletions apps/api/src/activity/metrics/dao-activity.metric.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
import { Injectable } from '@nestjs/common';
import moment from 'moment';

import {
ContractContext,
LeaderboardMetricResponse,
MetricQuery,
MetricResponse,
TotalMetric,
} from '@dao-stats/common';
import { TransactionService } from '@dao-stats/transaction';
import { ActivityInterval } from '@dao-stats/common/types/activity-interval';

import { ActivityApiMetricService } from '../interfaces/activity-api-metric.interface';
import { getDailyIntervals, getGrowth } from '../../utils';
import { ActivityApiMetric } from '../types/activity-api-metric';

@Injectable()
export class DaoActivityApiMetricService
implements ActivityApiMetricService<ActivityApiMetric>
{
constructor(private readonly transactionService: TransactionService) {}

getType(): ActivityApiMetric.DaoActivity {
return ActivityApiMetric.DaoActivity;
}

async getActivity(
context: ContractContext,
interval: ActivityInterval,
): Promise<TotalMetric> {
const intervalAgo = moment().subtract(1, interval);
const growthIntervalAgo = moment().subtract(2, interval);

const [activity, monthAgoActivity] = await Promise.all([
this.transactionService.getContractActivityCount(context, {
from: intervalAgo.valueOf(),
}),
this.transactionService.getContractActivityCount(context, {
from: growthIntervalAgo.valueOf(),
to: intervalAgo.valueOf(),
}),
]);

return {
count: activity.count,
growth: getGrowth(activity.count, monthAgoActivity.count),
};
}

async getHistory(
context: ContractContext,
metricQuery: MetricQuery,
interval?: ActivityInterval,
): Promise<MetricResponse> {
const metrics =
await this.transactionService.getContractActivityCountHistory(
context,
metricQuery,
interval,
);

return {
metrics: metrics.map(({ day, count }) => ({
timestamp: moment(day).valueOf(),
count,
})),
};
}

async getLeaderboard(
context: ContractContext,
): Promise<LeaderboardMetricResponse> {
const monthAgo = moment().subtract(1, 'month');
const days = getDailyIntervals(monthAgo.valueOf(), moment().valueOf());

const byDays = await this.transactionService.getActivityLeaderboard(
context,
{
from: monthAgo.valueOf(),
to: moment().valueOf(),
},
true,
);

const dayAgo = moment().subtract(1, 'days');
const dayAgoActivity = await this.transactionService.getActivityLeaderboard(
context,
{
to: dayAgo.valueOf(),
},
);

const totalActivity = await this.transactionService.getActivityLeaderboard(
context,
{
to: moment().valueOf(),
},
);

const metrics = totalActivity.map(({ receiver_account_id: dao, count }) => {
const dayAgoCount =
dayAgoActivity.find(
({ receiver_account_id }) => receiver_account_id === dao,
)?.count || 0;

return {
dao,
activity: {
count,
growth: getGrowth(count, dayAgoCount),
},
overview: days.map(({ end: timestamp }) => ({
timestamp,
count:
byDays.find(
({ receiver_account_id, day }) =>
receiver_account_id === dao &&
moment(day).isSame(moment(timestamp), 'day'),
)?.count || 0,
})),
};
});

return { metrics };
}
}
4 changes: 4 additions & 0 deletions apps/api/src/activity/metrics/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { DaoActivityApiMetricService } from './dao-activity.metric';
import { UserActivityApiMetricService } from './user-activity.metric';

export default [DaoActivityApiMetricService, UserActivityApiMetricService];
Loading