register watch count

김종민·2022년 11월 8일
0

Youtube

목록 보기
20/23

video의 view count를 새어주는
작업,
그리고 view count를 DB에 저장해서
다시뿌려주는 작업.
api를 사용하는데, rendering 하는것 없이 api가
사용되는 구조를 잘 알아 놓는다


1. src/routes/apiRouter.js

import express from 'express'
import { registerView } from '../controllers/videoController'

const apiRouter = express.Router()

apiRouter.post('/videos/:id([0-9a-f]{24})/view', registerView)
///apiRouter를 하나 만들고 
///'/videos/:id/view'의 path를 하나만들고,
/// registerView 라는 controller를 등록하고
///videoController에 registerView를 만든다.

export default apiRouter

2. server.js

app.use(localsMiddleware)
app.use('/uploads', express.static('uploads')) //'/uploads' path로 uploads폴더에 접근허락해조
app.use('/static', express.static('assets')) //'/assets' path로 assets폴더에 접근허락해조
app.use('/', rootRouter)
app.use('/videos', videoRouter)
app.use('/users', userRouter)
app.use('/api', apiRouter)
///server.js에 apiRouter를 등록한다.

3.src/controllers/videoController.js

videoController안에 '/api/id/view로 접근했을떄, 실행될
함수를 만들어준다.

export const registerView = async (req, res) => {
  const { id } = req.params
  ///req.params로 id를 받아온다.
  const video = await Video.findById(id)
  ///받아온 id로 video를 찾는다.
  if (!video) {
    return res.sendStatus(404)
  }
  ///video가 없으면, 404를 return한다.
  
  video.meta.views = video.meta.views + 1
  ///DB의 video의 view값을 +1을 한다.
  
  await video.save()
  ///DB의 video를 save한다.
  ///await를 넣는 이유는 DB를 건딜기때문에 await를 해 준다.
  
  return res.sendStatus(200)
  ///200을 날린다.
  !!!!status를 날릴떄, status(200)을 하지 않고, 
  ///sendStatus를 하는 이유는 
  /// sendStatus와 status의 차이는,
  /// status는 상태코드 뒤에 반드시
  ///return res.status(400).redirect('/')
  ///와 같이 redirect나 render를 해주어야한다.
  /// redner나 redirect없이 마무리 할려면, 
  ///반드시 sendStatus를 사용해야 한다.
  
  !!!아래에서 JS에서 이 API를 사용해보겠습니다.
}

4.src/client/js/videoPlayer.js

우선 JS에서(front)에서 video id를 받아오기 위해서는
watch.pug파일에서 video을 id를 뽑아내야한다,

방법은 dataSet이라는 것을 이용한다.

4-1.watch.pug

watch.pug에는 controller에서 video data를 보내주었음.
data-id=video._id 로 id에 video._id 값을 담아준다.
이제videoPlayer.js에서 pug에서 보내준 id를 사용해보자

block content
    div#videoContainer(data-id=video._id)
        video(src="/" + video.fileUrl)
        div#videoControls.videoControls

4-2.videoPlayer.js

console.log('videoContainer', videoContainer.dataset)
///위와 같이 console을 찍어보면, watch.pug에서
///data-id로 보낸 video의 id를 확인할 수 있음.

const hadleEnded = () => {
  const { id } = videoContainer.dataset
  fetch(`/api/videos/${id}/view`, { method: 'POST' })
}
///dataset을 이용해서, watch.pug파일에서 보내준, id값을
///받은 다음, 위에서 만든 path로 POST요청을 보낸다.
///위 path로 fetch로 POST요청을 하면
///registerView함수가 실행된다.

video.addEventListener('ended', hadleEnded)
///video에 event를 달아주는데, 'ended'는 video가
///끝났을떄를 의미하며, 
///'ended', handleEnded는 비디오가 끝났을때,
///handleEnded함수를 실행시켜라는 뜻이다.
profile
코딩하는초딩쌤

2개의 댓글

comment-user-thumbnail
2023년 4월 26일

@drift boss
이 기사 덕분에 사용된 구조에 대해 알 수 있었습니다.

답글 달기
comment-user-thumbnail
2024년 2월 28일

Delhi Escort Service takes excellent pleasure in offering exceptional services, with their main objective being to bring joy to their male clients by showing off sensuous bodies. Independent Delhi Escorts are attractive beauties who will make your experience pleasurable by fulfilling all your sexual fantasies and all erotica needs. Available day or night to meet these desires.

답글 달기