프로젝트/영화 검색 (Vue)

Vue 프로젝트 영화 정보 반환 API 만들기

IT Blue 2021. 8. 27. 16:21

 

Vue 프로젝트 영화 정보 반환 API 만들기

 

1. /src/functions 폴더 생성, /src/functions/movie.js /파일 생성

- Netlify Serverless Functions 로 사용

- /src/store/movie.js 내부 _fetchMovie() 를 옮김

const axios = require('axios')

exports.handler = async function (event) {
  const payload = JSON.parse(event.body)
  const { title, type, year, page, id } = payload
  const OMDB_API_KEY = ...
  const url = id 
    ? `https://www.omdbapi.com/?apikey=${OMDB_API_KEY}&i=${id}` 
    : `https://www.omdbapi.com/?apikey=${OMDB_API_KEY}&s=${title}&type=${type}&y=${year}&page=${page}`

  try {
    const { data } = await axios.get(url)
    if (data.Error) {
      return {
        statusCode: 400,
        body: data.Error
      }
    }
    return {
      statusCode: 200,
      body: JSON.stringify(data)
    }
  } catch (error) {
    return {
      statusCode: error.response.status,
      body: error.message
    }
  }
}

 

2. /src/store/movie.js 수정

- _fetchMovie() 를 수정

- Netlify Serverless Functions 로 요청이 들어가도록 수정

- error 객체 처리

async searchMovies({ state, commit }, payload) {
      ...
      try {
        ...
      } catch ({ message }) {
        commit('updateState', {
          movies: [],
          message
        })
      } finally {
        ...
      }
...

async function _fetchMovie(payload) {
  return await axios.post('/.netlify/functions/movie', payload)
}