msyM
Convex Community9mo ago
6 replies
msy

Aggregating by userId and creationTime

Hi im using the Aggregate Convex component.
I'm having trouble trying to figure out how I might implement these functions. Right now I believe they are aggregating all tasks. I was wondering how i could further filter to specific userIds?

import { TableAggregate } from "@convex-dev/aggregate";
import { v } from "convex/values";
import { components } from "../_generated/api";
import { DataModel } from "../_generated/dataModel";
import { query } from "../_generated/server";
import { getDocumentOrThrow } from "../utils/db";

const durationAggregate = new TableAggregate<{
  Key: number;
  DataModel: DataModel;
  TableName: "tasks";
}>(components.aggregate, {
  sortKey: (doc) => doc._creationTime,
  sumValue: (doc) => doc.duration,
});

export const totalFocusTimeByUser = query({
  args: {
    userId: v.id("users"),
  },
  handler: async (ctx, args) => {
    await getDocumentOrThrow(ctx, "users", args.userId);
    const totalFocusTime = await durationAggregate.sum(ctx);
    return totalFocusTime;
  },
});

export const totalFocusTimeByUserForWeek = query({
  args: {
    userId: v.id("users"),
  },
  handler: async (ctx, args) => {
    await getDocumentOrThrow(ctx, "users", args.userId);
    const totalFocusTimeByWeek = await durationAggregate.sum(ctx);
    return totalFocusTimeByWeek;
  },
});
Was this page helpful?