67 lines
2.3 KiB
TypeScript
67 lines
2.3 KiB
TypeScript
import type { Logger, UseCaseOutputPort, UseCase } from '@core/shared/application';
|
|
import type { IPageViewRepository } from '../../domain/repositories/IPageViewRepository';
|
|
import { PageView } from '../../domain/entities/PageView';
|
|
import type { EntityType, VisitorType } from '../../domain/types/PageView';
|
|
import { Result } from '@core/shared/application/Result';
|
|
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
|
|
|
|
export interface RecordPageViewInput {
|
|
entityType: EntityType;
|
|
entityId: string;
|
|
visitorId?: string;
|
|
visitorType: VisitorType;
|
|
sessionId: string;
|
|
referrer?: string;
|
|
userAgent?: string;
|
|
country?: string;
|
|
}
|
|
|
|
export interface RecordPageViewOutput {
|
|
pageViewId: string;
|
|
}
|
|
|
|
export type RecordPageViewErrorCode = 'REPOSITORY_ERROR';
|
|
|
|
export class RecordPageViewUseCase implements UseCase<RecordPageViewInput, RecordPageViewOutput, RecordPageViewErrorCode> {
|
|
constructor(
|
|
private readonly pageViewRepository: IPageViewRepository,
|
|
private readonly logger: Logger,
|
|
) {}
|
|
|
|
async execute(input: RecordPageViewInput): Promise<Result<RecordPageViewOutput, ApplicationErrorCode<RecordPageViewErrorCode, { message: string }>>> {
|
|
try {
|
|
const pageView = PageView.create({
|
|
id: crypto.randomUUID(),
|
|
entityType: input.entityType,
|
|
entityId: input.entityId,
|
|
visitorId: input.visitorId,
|
|
visitorType: input.visitorType,
|
|
sessionId: input.sessionId,
|
|
referrer: input.referrer,
|
|
userAgent: input.userAgent,
|
|
country: input.country,
|
|
});
|
|
|
|
await this.pageViewRepository.save(pageView);
|
|
|
|
this.logger.info('Page view recorded', {
|
|
pageViewId: pageView.id,
|
|
entityId: input.entityId,
|
|
entityType: input.entityType,
|
|
});
|
|
|
|
const result = Result.ok<RecordPageViewOutput, ApplicationErrorCode<RecordPageViewErrorCode, { message: string }>>({
|
|
pageViewId: pageView.id,
|
|
});
|
|
return result;
|
|
} catch (error) {
|
|
const err = error as Error;
|
|
this.logger.error('Failed to record page view', err, { input });
|
|
const result = Result.err<RecordPageViewOutput, ApplicationErrorCode<RecordPageViewErrorCode, { message: string }>>({
|
|
code: 'REPOSITORY_ERROR',
|
|
details: { message: err.message ?? 'Failed to record page view' },
|
|
});
|
|
return result;
|
|
}
|
|
}
|
|
} |