TwitchClone / src / pages / api / mux-webhook.tsx
mux-webhook.tsx
Raw
import { NextApiRequest, NextApiResponse } from "next";
import { prisma } from "../../server/db";
import { appRouter } from "../../server/api/root";

interface MuxWebhookData {
  passthrough: string;
  playback_ids: { id: string }[];
  id: string;
  video?: string;
}

interface MuxWebhookBody {
  data: MuxWebhookData;
  type: string;
}

export default async function muxWebhookHandler(
  req: NextApiRequest,
  res: NextApiResponse
): Promise<void> {
  //@ts-ignore // eslint-disable-next-line
  // const { method, body } = req;
  const { method } = req;
  const body = req.body as MuxWebhookBody;
  // const session = await getServerSession(req, res, authOptions);
  // console.log(session, "session");

  switch (method) {
    case "POST": {
      // const { data, type } = body;
      // const typedBody = body as MuxWebhookBody;
      const { data, type } = body;
      console.log(`Event type: ${type}`);

      if (type === "video.asset.ready") {
        const input = {
          uuid: data.passthrough,
          playbackId: data.playback_ids[0]?.id || "",
          assetId: data.id,
        };

        const l_ = appRouter.lambda.createCaller({
          session: null,
          prisma,
        });

        try {
          // console.log("Calling hookContentUpdate with input:", input);
          const res_ = await l_.hookContentUpdate(input);
          console.log("hookContentUpdate result:", res_);
          // res.status(200).json({ data: { ...res_ } });
          if (data.video) {
            console.log(`Video asset for room ${data.video} is ready.`);
          }
        } catch (err) {
          // ... rest of the error handling code
        }
      } else {
        // handle other event types
      }
      res.status(200).json({ data: { ...res } });
      break;
    }

    default:
      res.setHeader("Allow", ["POST"]);
      res.status(405).end(`Method ${method || ""} Not Allowed`);
  }
}