IndieMamba
IndieMamba

Reputation: 73

Issue with Filtering Data by Date Input Parameter in Prisma Query

I'm working on a procedure that filters data based on the creation date within the last 24 hours. The code works perfectly when the date is explicitly specified within the procedure:

appReqscreated24H: protectedProcedure
  .query(async ({ ctx }) => {
    return await ctx.prisma.appRequest.count({
      where: {
        created_at: {
          gte: new Date(Date.now() - 24 * 60 * 60 * 1000)
        },
        NOT: {
          status: {
            in: [RequestStatus.COMPLETE]
          }
        }
      }
    })
  })

However, when I try to pass the date as an input parameter, the code doesn't work as expected:

appReqscreated24H: protectedProcedure
  .input(
    z.object({
      startDate: z.date()
    }) 
  )
  .query(async ({ ctx, input }) => {
    return await ctx.prisma.appRequest.count({
      where: {
        created_at: {
          gte: input.startDate
        },
        NOT: {
          status: {
            in: [RequestStatus.COMPLETE]
          }
        }
      }
    })
  }),

I've compared the types and they appear to be identical, yet I'm encountering issues with it not functioning as expected. As someone new to this, I would greatly appreciate any assistance. Thank you in advance!

Upvotes: 0

Views: 40

Answers (1)

Mehmet Doğan
Mehmet Doğan

Reputation: 1

It sounds like the issue may stem from how the date is being passed from the client to your backend, rather than from the Prisma query or the Zod schema itself.

export const appReqscreated24H = protectedProcedure
  .input(
    z.object({
      startDate: z.preprocess((value) => {
        // If it's already a Date, just return it
        if (value instanceof Date) {
          return value;
        }
        // If it's a string, convert it to a Date
        if (typeof value === "string") {
          return new Date(value);
        }
        // If it's anything else, throw an error
        throw new Error("Invalid date input");
      }, z.date())
    })
  )
  .query(async ({ ctx, input }) => {
    return ctx.prisma.appRequest.count({
      where: {
        created_at: {
          gte: input.startDate
        },
        NOT: {
          status: {
            in: [RequestStatus.COMPLETE]
          }
        }
      }
    });
  });

With this change, your procedure should behave the same as when you hard-coded new Date(Date.now() - 24 * 60 * 60 * 1000), because Prisma will now reliably receive a valid Date object every time.

Upvotes: 0

Related Questions