TwitchClone / src / pages / api / upload-video.ts
upload-video.ts
Raw
// // pages/api/upload.js
import type { NextApiRequest, NextApiResponse } from "next";
import Mux from "@mux/mux-node";
// import { v4 } from "uuid";
console.log("process.env.MUX_TOKEN_ID", process.env.MUX_TOKEN_ID);
console.log("process.env.MUX_TOKEN_SECRET", process.env.MUX_SECRET_KEY);
const { Video } = new Mux(
  process.env.MUX_TOKEN_ID || "",
  process.env.MUX_SECRET_KEY || ""
);

export default async function uploadHandler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const { method } = req;
  const id = req.query.input;

  console.log("firing", id, method);
  switch (method) {
    case "POST":
      try {
        if (!id) {
          res
            .status(500)
            .json({ error: "Error creating upload: no id passed" });
          return;
        }
        // const tempId = v4();
        const upload = await Video.Uploads.create({
          new_asset_settings: {
            playback_policy: "public",
            passthrough: id as string,
          },
          cors_origin: "*",
        });
        console.log(upload, "upload");
        res.json({
          roomId: id,
          assetId: upload.id,
          url: upload.url,
        });
      } catch (e) {
        console.error("Request error", e);
        res.status(500).json({ error: "Error creating upload" });
      }
      break;
    default:
      res.setHeader("Allow", ["POST"]);
      res.status(405).end(`Method ${method || "undefinedMethod"} Not Allowed`);
  }
}
// // see: https://github.com/vercel/next.js/tree/canary/examples/with-mux-video
// import { NextApiRequest, NextApiResponse } from "next";
// import Mux from "@mux/mux-node";
// const { Video } = new Mux();

// export default async function uploadHandler(
//   req: NextApiRequest,
//   res: NextApiResponse
// ) {
//   const { method } = req;

//   switch (method) {
//     case "POST":
//       try {
//         const upload = await Video.Uploads.create({
//           new_asset_settings: { playback_policy: "public" },
//           cors_origin: "*",
//         });
//         res.json({
//           id: upload.id,
//           url: upload.url,
//         });
//       } catch (e) {
//         console.error("Request error", e);
//         res.status(500).json({ error: "Error creating upload" });
//       }
//       break;
//     default:
//       res.setHeader("Allow", ["POST"]);
//       res.status(405).end(`Method ${method} Not Allowed`);
//   }
// }