add posthog to trpc context and add view video event

This commit is contained in:
MarconLP 2023-04-23 13:13:43 +02:00
parent 9ad8bcf507
commit ba7766f2f6
No known key found for this signature in database
GPG key ID: A08A9C8B623F5EA5
3 changed files with 26 additions and 3 deletions

View file

@ -41,8 +41,8 @@ export const videoRouter = createTRPCRouter({
get: publicProcedure
.input(z.object({ videoId: z.string() }))
.query(async ({ ctx, input }) => {
const { s3 } = ctx;
const video = await ctx.prisma.video.findUnique({
const { s3, posthog, session, prisma } = ctx;
const video = await prisma.video.findUnique({
where: {
id: input.videoId,
},
@ -54,10 +54,25 @@ export const videoRouter = createTRPCRouter({
throw new TRPCError({ code: "NOT_FOUND" });
}
if (video.userId !== ctx?.session?.user.id && !video.sharing) {
if (!session || (video.userId !== session?.user.id && !video.sharing)) {
throw new TRPCError({ code: "FORBIDDEN" });
}
posthog.capture({
distinctId: session.user.id,
event: "viewing video",
properties: {
videoId: video.id,
videoCreatedAt: video.createdAt,
videoUpdatedAt: video.updatedAt,
videoUser: video.user.id,
videoSharing: video.sharing,
videoDeleteAfterLinkExpires: video.delete_after_link_expires,
videoShareLinkExpiresAt: video.shareLinkExpiresAt,
},
});
void posthog.shutdownAsync();
const getObjectCommand = new GetObjectCommand({
Bucket: env.AWS_BUCKET_NAME,
Key: video.userId + "/" + video.id,

View file

@ -41,6 +41,7 @@ const createInnerTRPCContext = (opts: CreateContextOptions) => {
session: opts.session,
prisma,
s3,
posthog,
stripe,
req: opts.req,
res: opts.res,
@ -79,6 +80,7 @@ import { ZodError } from "zod";
import { s3 } from "~/server/aws/s3";
import { stripe } from "~/server/stripe";
import { type NextApiRequest, type NextApiResponse } from "next";
import { posthog } from "~/server/posthog";
const t = initTRPC.context<typeof createTRPCContext>().create({
transformer: superjson,

6
src/server/posthog.ts Normal file
View file

@ -0,0 +1,6 @@
import { PostHog } from "posthog-node";
import { env } from "~/env.mjs";
export const posthog = new PostHog(env.NEXT_PUBLIC_POSTHOG_KEY, {
host: env.NEXT_PUBLIC_POSTHOG_HOST,
});