♻️ Abstract code for getting subscription status

This commit is contained in:
Luke Vella 2023-08-23 19:47:25 +01:00
parent 06eca8f61c
commit fe1933716d
3 changed files with 49 additions and 52 deletions

View file

@ -1,6 +1,7 @@
import { prisma } from "@rallly/database";
import { z } from "zod";
import { getSubscriptionStatus } from "../../utils/auth";
import { possiblyPublicProcedure, privateProcedure, router } from "../trpc";
export const user = router({
@ -27,47 +28,7 @@ export const user = router({
};
}
const user = await prisma.user.findUnique({
where: {
id: ctx.user.id,
},
select: {
subscription: {
select: {
active: true,
},
},
},
});
if (user?.subscription?.active === true) {
return {
active: true,
};
}
const userPaymentData = await prisma.userPaymentData.findUnique({
where: {
userId: ctx.user.id,
},
select: {
endDate: true,
},
});
if (
userPaymentData?.endDate &&
userPaymentData.endDate.getTime() > Date.now()
) {
return {
active: true,
legacy: true,
};
}
return {
active: false,
};
return await getSubscriptionStatus(ctx.user.id);
}),
changeName: privateProcedure
.input(

View file

@ -1,7 +1,7 @@
import { prisma } from "@rallly/database";
import { initTRPC, TRPCError } from "@trpc/server";
import superjson from "superjson";
import { getSubscriptionStatus } from "../utils/auth";
import { Context } from "./context";
const t = initTRPC.context<Context>().create({
@ -38,16 +38,7 @@ export const proProcedure = t.procedure.use(
});
}
const isPro = Boolean(
await prisma.userPaymentData.findFirst({
where: {
userId: ctx.user.id,
endDate: {
gt: new Date(),
},
},
}),
);
const { active: isPro } = await getSubscriptionStatus(ctx.user.id);
if (!isPro) {
throw new TRPCError({

View file

@ -0,0 +1,45 @@
import { prisma } from "@rallly/database";
export const getSubscriptionStatus = async (userId: string) => {
const user = await prisma.user.findUnique({
where: {
id: userId,
},
select: {
subscription: {
select: {
active: true,
},
},
},
});
if (user?.subscription?.active === true) {
return {
active: true,
};
}
const userPaymentData = await prisma.userPaymentData.findFirst({
where: {
userId,
endDate: {
gt: new Date(),
},
},
});
if (
userPaymentData?.endDate &&
userPaymentData.endDate.getTime() > Date.now()
) {
return {
active: true,
legacy: true,
};
}
return {
active: false,
};
};