fix: convert to kysely queries

This commit is contained in:
Mythie
2024-05-29 20:03:51 +10:00
parent 3d81b15d71
commit ab949afbb6
3 changed files with 24 additions and 36 deletions

View File

@ -1,28 +1,19 @@
import { sql } from 'kysely';
import { DateTime } from 'luxon';
import { kyselyPrisma } from '@documenso/prisma';
import { kyselyPrisma, sql } from '@documenso/prisma';
import { DocumentStatus } from '@documenso/prisma/client';
export type GetCompletedDocumentsMonthlyResult = Array<{
month: string;
count: number;
cume_count: number;
}>;
export const getCompletedDocumentsMonthly = async () => {
const qb = kyselyPrisma.$kysely
.selectFrom('Document')
.select(({ fn, ref }) => [
fn<Date>('DATE_TRUNC', [sql.lit('MONTH'), ref('Document.updatedAt')]).as('month'),
.select(({ fn }) => [
fn<Date>('DATE_TRUNC', [sql.lit('MONTH'), 'Document.updatedAt']).as('month'),
fn.count('id').as('count'),
fn
.sum(fn.count('id'))
// Feels like a bug in the Kysely extension but I just can not do this orderBy in a type-safe manner
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions, @typescript-eslint/no-explicit-any
.over((ob) =>
ob.orderBy(fn('DATE_TRUNC', [sql.lit('MONTH'), ref('Document.updatedAt')]) as any),
)
.over((ob) => ob.orderBy(fn('DATE_TRUNC', [sql.lit('MONTH'), 'Document.updatedAt']) as any))
.as('cume_count'),
])
.where(() => sql`"Document"."status" = ${DocumentStatus.COMPLETED}::"DocumentStatus"`)

View File

@ -1,30 +1,25 @@
import { DateTime } from 'luxon';
import { prisma } from '@documenso/prisma';
export type GetUserMonthlyGrowthResult = Array<{
month: string;
count: number;
cume_count: number;
}>;
type GetUserMonthlyGrowthQueryResult = Array<{
month: Date;
count: bigint;
cume_count: bigint;
}>;
import { kyselyPrisma, sql } from '@documenso/prisma';
export const getUserMonthlyGrowth = async () => {
const result = await prisma.$queryRaw<GetUserMonthlyGrowthQueryResult>`
SELECT
DATE_TRUNC('month', "createdAt") AS "month",
COUNT("id") as "count",
SUM(COUNT("id")) OVER (ORDER BY DATE_TRUNC('month', "createdAt")) as "cume_count"
FROM "User"
GROUP BY "month"
ORDER BY "month" DESC
LIMIT 12
`;
const qb = kyselyPrisma.$kysely
.selectFrom('User')
.select(({ fn }) => [
fn<Date>('DATE_TRUNC', [sql.lit('MONTH'), 'User.createdAt']).as('month'),
fn.count('id').as('count'),
fn
.sum(fn.count('id'))
// Feels like a bug in the Kysely extension but I just can not do this orderBy in a type-safe manner
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions, @typescript-eslint/no-explicit-any
.over((ob) => ob.orderBy(fn('DATE_TRUNC', [sql.lit('MONTH'), 'User.createdAt']) as any))
.as('cume_count'),
])
.groupBy('month')
.orderBy('month', 'desc')
.limit(12);
const result = await qb.execute();
return result.map((row) => ({
month: DateTime.fromJSDate(row.month).toFormat('yyyy-MM'),