All files / dal blog-analytics.dal.ts

100% Statements 4/4
100% Branches 4/4
100% Functions 2/2
100% Lines 4/4

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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            14x                                     6x       6x                                       6x      
// Data Access Layer for Blog Analytics
import { desc, eq } from "drizzle-orm";
import type { DrizzleD1Database } from "drizzle-orm/d1";
import * as schema from "../db/schema";
 
export class BlogAnalyticsDal {
	constructor(private db: DrizzleD1Database<typeof schema>) {}
 
	// Top blogs by 30-day views or 30-day clicks. Only published blogs.
	async getTopPerformingBlogs(
		limit = 10,
		metric: "views" | "clicks" = "views",
	): Promise<
		Array<{
			blogId: string;
			title: string;
			slug: string;
			totalPageViews: number;
			totalProClicks: number;
			totalProjectClicks: number;
			views30d: number;
			clicks30d: number;
		}>
	> {
		const orderByColumn =
			metric === "views"
				? schema.analyticsBlogSummary.views30d
				: schema.analyticsBlogSummary.clicks30d;
 
		const result = await this.db
			.select({
				blogId: schema.analyticsBlogSummary.blogId,
				title: schema.blogs.title,
				slug: schema.blogs.slug,
				totalPageViews: schema.analyticsBlogSummary.totalPageViews,
				totalProClicks: schema.analyticsBlogSummary.totalProClicks,
				totalProjectClicks: schema.analyticsBlogSummary.totalProjectClicks,
				views30d: schema.analyticsBlogSummary.views30d,
				clicks30d: schema.analyticsBlogSummary.clicks30d,
			})
			.from(schema.analyticsBlogSummary)
			.innerJoin(
				schema.blogs,
				eq(schema.analyticsBlogSummary.blogId, schema.blogs.id),
			)
			.where(eq(schema.blogs.status, "published"))
			.orderBy(desc(orderByColumn))
			.limit(limit);
 
		return result;
	}
}