Views API

Jun's Coding Journey·2022년 11월 25일
0

[Challenge] Youtube Clone

목록 보기
17/19

Register View Controller

Most of the time, node.js is not used to render templates. In fact, we can change the frontend without inputting any form.

To register a view controller we first need to create a router that has a url.

import express from "express";
import { registerView } from "../controllers/videoController";

const apiRouter = express.Router();

apiRouter.post("/videos/:id([0-9a-f]{24})/view", registerView);

export default apiRouter;

Next, we need to create a controller that will grab the id of an uploaded video and increase the view count.

export const registerView = async (req, res) => {
  const { id } = req.params;
  const video = await Video.findById(id);
  if (!video) {
    return res.status(404);
  }
  video.meta.views = video.meta.views + 1;
  await video.save();
  return res.status(200);
};

Register View Event

To actually add a view count after watching an uploaded video, we need to use two events called timeupdate (this will not work on a div element) and ended.

By using the ended event on a function, we can try to fetch a url and post the information of the view count on the backend as soon as the video ends.

const handleEnded = () => {
  const { id } = videoContainer.dataset;
  fetch(`/api/videos/${id}/view`, {
    method: "POST",
  });
};

Additionally, we need to actually send a request to the backend everytime a video is watched. To do this, we need to fix the status method to sendStatus().

export const registerView = async (req, res) => {
  const { id } = req.params;
  const video = await Video.findById(id);
  if (!video) {
    return res.sendStatus(404);
  }
  video.meta.views = video.meta.views + 1;
  await video.save();
  return res.sendStatus(200);
};
profile
Greatness From Small Beginnings

0개의 댓글