movie.controller.js 7.33 KB
Newer Older
Jiwon Yoon's avatar
Jiwon Yoon committed
1
import axios from 'axios'
Jiwon Yoon's avatar
Jiwon Yoon committed
2
import { Movie } from '../db/index.js'
Kim, Subin's avatar
Kim, Subin committed
3
4
import sequelize from 'sequelize'
const { Op } = sequelize
Jiwon Yoon's avatar
Jiwon Yoon committed
5

6
7
const getListfromDB = async (req, res) => {
    try {
Kim, Subin's avatar
Kim, Subin committed
8
        const findAll = await Movie.findAll({ attributes: ['movieId', 'title', 'release_date'] })
9
10
11
12
13
14
        res.json(findAll)
    } catch (error) {
        return res.status(500).send(error.message || "영화 목록 가져오기 중 에러 발생");
    }
}

Jiwon Yoon's avatar
Jiwon Yoon committed
15
const getMovieByCategory = async (req, res, next, category) => {
Jiwon Yoon's avatar
Jiwon Yoon committed
16
    try {
Kim, Subin's avatar
Kim, Subin committed
17
18
19
20
        const TMDBmovieIds = []
        const movieIds = []
        const response = await axios.get(`https://api.themoviedb.org/3/movie/${category}?api_key=${process.env.TMDB_APP_KEY}&language=ko-KR&page=1`)
        const TMDBmovies = response.data.results
Jiwon Yoon's avatar
Jiwon Yoon committed
21

Kim, Subin's avatar
Kim, Subin committed
22
23
24
        TMDBmovies.forEach(element => {
            TMDBmovieIds.push(element.id)
        })
Kim, Subin's avatar
Kim, Subin committed
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
        const responseAfterCompare = await Movie.findAll({
            where: {
                movieId: {
                    [Op.or]: TMDBmovieIds
                }
            }
        })
        responseAfterCompare.forEach(el => {
            movieIds.push(el.movieId)
        })
        req.movieIds = movieIds
        next()
    } catch (error) {
        return res.status(500).send(error.message || "영화 가져오기 중 에러 발생");
    }
}

const getMovieById = async (req, res) => {
    try {
        const movieIds = req.movieIds
        const elements = await Promise.all(
            movieIds.map(async (movieId) => {
                const movie = await axios.get(`https://api.themoviedb.org/3/movie/${movieId}?api_key=${process.env.TMDB_APP_KEY}&language=ko-KR`)
                return movie.data
            })
Kim, Subin's avatar
Kim, Subin committed
50
        )
Kim, Subin's avatar
Kim, Subin committed
51
52
53
        res.json(elements)
    } catch (error) {
        return res.status(500).send(error.message || "영화 가져오기 중 에러 발생");
Jiwon Yoon's avatar
Jiwon Yoon committed
54
55
56
    }
}

57
const movieforAdmin = async (req, res) => {
Kim, Subin's avatar
Kim, Subin committed
58
59
    try {
        const TMDBmovieIds = []
60
        const TMDBmovies = req.TMDBmovies
Kim, Subin's avatar
Kim, Subin committed
61
        const totalPage = req.totalPage
Kim, Subin's avatar
Kim, Subin committed
62
63
64
        TMDBmovies.forEach(element => {
            TMDBmovieIds.push(element.id)
        })
65
66
67
68
69
70
71
        const findDirectorResult = await Promise.all(TMDBmovieIds.map(async (movieId) => {
            let newObj = { id: movieId, name: "" }
            const { data } = await axios.get(`https://api.themoviedb.org/3/movie/${movieId}/credits?api_key=${process.env.TMDB_APP_KEY}&language=ko-KR`)
            const findDirectors = await data.crew.filter(element => element.job === "Director")
            if (findDirectors.length !== 0) {
                const name = findDirectors.reduce((acc, cur, idx) => {
                    if (idx !== 0) return acc + ', ' + cur.name
Kim, Subin's avatar
Kim, Subin committed
72
73
                    else return acc + cur.name
                }, '')
74
75
76
77
78
                newObj.name = name
            } else newObj.name = "없음"

            return newObj
        }))
Kim, Subin's avatar
Kim, Subin committed
79
        findDirectorResult.forEach(element => TMDBmovies.forEach(movie => {
80
81
            if (element.id === movie.id) movie.director = element.name
        }))
Kim, Subin's avatar
Kim, Subin committed
82
83
84
85
86
87
        const responseAfterCompare = await Movie.findAll({
            where: {
                movieId: TMDBmovieIds
            },
            attributes: ['movieId']
        })
88
89
90
        responseAfterCompare.forEach(element => TMDBmovies.forEach((movie) => {
            if (movie.existed !== true && movie.id === element.movieId) movie.existed = true
            else if (movie.existed !== true) movie.existed = false
Kim, Subin's avatar
Kim, Subin committed
91
        }))
Kim, Subin's avatar
Kim, Subin committed
92
        return res.json({ TMDBmovies, totalPage })
Kim, Subin's avatar
Kim, Subin committed
93
94
95
96
    } catch (error) {
        return res.status(500).send(error.message || "영화 가져오는 중 에러 발생")
    }
}
Jiwon Yoon's avatar
Jiwon Yoon committed
97

98
99
100
101
102
const getAllMovie = async (req, res, next) => {
    try {
        const { pageNum } = req.query
        const now = new Date()
        const monthAgo = new Date(now.setMonth(now.getMonth() - 1)).toJSON().split(/T/)[0]
Kim, Subin's avatar
Kim, Subin committed
103
        const response = await axios.get(`https://api.themoviedb.org/3/discover/movie?api_key=${process.env.TMDB_APP_KEY}&language=ko-KR&region=KR&sort_by=release_date.asc&release_date.gte=${monthAgo}&page=${pageNum}`)
104
        req.TMDBmovies = response.data.results
Kim, Subin's avatar
Kim, Subin committed
105
        req.totalPage = response.data.total_pages
106
107
108
        next()
    } catch (error) {
        return res.status(500).send(error.message || "영화 가져오는 중 에러 발생")
Jiwon Yoon's avatar
Jiwon Yoon committed
109
110
111
    }
}

Kim, Subin's avatar
Kim, Subin committed
112
const getMovieList = async (req, res) => {
Jiwon Yoon's avatar
Jiwon Yoon committed
113
    try {
Jiwon Yoon's avatar
Jiwon Yoon committed
114
        const movieList = await Movie.findAll()
Kim, Subin's avatar
Kim, Subin committed
115
        const movieIds = []
Jiwon Yoon's avatar
Jiwon Yoon committed
116
117
        movieList.forEach(el => {
            movieIds.push(el.movieId)
Jiwon Yoon's avatar
Jiwon Yoon committed
118
        })
Jiwon Yoon's avatar
Jiwon Yoon committed
119
120
121
        const elements = await Promise.all(
            movieIds.map(async (movieId) => {
                const movie = await axios.get(`https://api.themoviedb.org/3/movie/${movieId}?api_key=${process.env.TMDB_APP_KEY}&language=ko-KR`)
Jiwon Yoon's avatar
Jiwon Yoon committed
122
123
                return movie.data
            })
124
        )
Jiwon Yoon's avatar
Jiwon Yoon committed
125
        res.json(elements)
Jiwon Yoon's avatar
Jiwon Yoon committed
126
    } catch (error) {
Kim, Subin's avatar
Kim, Subin committed
127
        return res.status(500).send(error.message || "영화 정보 가져오는 중 에러 발생")
Jiwon Yoon's avatar
Jiwon Yoon committed
128
129
130
    }
}

131
132
133
const create = async (req, res) => {
    try {
        const { movieId } = req.params
Kim, Subin's avatar
Kim, Subin committed
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
        const { data } = await axios.get(`https://api.themoviedb.org/3/movie/${movieId}?api_key=${process.env.TMDB_APP_KEY}&language=ko-KR`)
        const newMovie = await Movie.create({ movieId: data.id, title: data.title, release_date: data.release_date })
        return res.json(newMovie)
    } catch (error) {
        return res.status(500).send(error.message || "영화 등록 중 에러 발생")
    }
}

const remove = async (req, res) => {
    try {
        const { movieId } = req.params
        const delMovie = await Movie.destroy({ where: { movieId: movieId } })
        return res.json(delMovie)
    } catch (error) {
        return res.status(500).send(error.message || "영화 삭제 중 에러 발생");
    }
}

152
const findonlyTitle = async (req, res) => {
Kim, Subin's avatar
Kim, Subin committed
153
    try {
154
        const { keyword } = req.query
Kim, Subin's avatar
Kim, Subin committed
155
        const movieIds = []
Kim, Subin's avatar
Kim, Subin committed
156
157
158
        const { count, rows } = await Movie.findAndCountAll({
            where: {
                title: {
159
                    [Op.substring]: keyword
Kim, Subin's avatar
Kim, Subin committed
160
161
162
                }
            }
        });
Kim, Subin's avatar
Kim, Subin committed
163
164
165
166
167
168
169
170
171
172
        if (rows) {
            rows.forEach(movie => movieIds.push(movie.movieId))
            const elements = await Promise.all(
                movieIds.map(async (movieId) => {
                    const movie = await axios.get(`https://api.themoviedb.org/3/movie/${movieId}?api_key=${process.env.TMDB_APP_KEY}&language=ko-KR`)
                    return movie.data
                })
            )
            return res.json({ count: movieIds.length, results: elements })
        } else return res.json({ count: count, results: rows })
173
    } catch (error) {
Kim, Subin's avatar
Kim, Subin committed
174
        return res.status(500).send(error.message || "영화 검색 중 에러 발생");
175
176
177
    }
}

178
179
const findaboutAll = async (req, res, next) => {
    try {
Kim, Subin's avatar
Kim, Subin committed
180
181
        const { keyword, pageNum } = req.query
        const response = await axios.get(`https://api.themoviedb.org/3/search/movie?api_key=${process.env.TMDB_APP_KEY}&language=kr-KR&query=${encodeURI(keyword)}&region=KR&page=${pageNum}`)
182
        req.TMDBmovies = response.data.results
Kim, Subin's avatar
Kim, Subin committed
183
        req.totalPage = response.data.total_pages
184
        next()
185
    } catch (error) {
186
        return res.status(500).send(error.message || "영화 검색 중 에러 발생");
187
188
189
190
    }
}

export default {
191
    getListfromDB,
Jiwon Yoon's avatar
Jiwon Yoon committed
192
193
    getMovieByCategory,
    getMovieById,
Kim, Subin's avatar
Kim, Subin committed
194
    getAllMovie,
Jiwon Yoon's avatar
Jiwon Yoon committed
195
    getMovieList,
196
    create,
Kim, Subin's avatar
Kim, Subin committed
197
    remove,
198
199
200
    findonlyTitle,
    findaboutAll,
    movieforAdmin
Jiwon Yoon's avatar
Jiwon Yoon committed
201
}