movie.controller.js 8.97 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 {
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 || "영화 목록 가져오기 중 에러 발생");
    }
}

15
const movieforAdmin = async (req, res) => {
Kim, Subin's avatar
Kim, Subin committed
16
17
    try {
        const TMDBmovieIds = []
18
        const TMDBmovies = req.TMDBmovies
Kim, Subin's avatar
Kim, Subin committed
19
        const totalPage = req.totalPage
Kim, Subin's avatar
Kim, Subin committed
20
21
22
        TMDBmovies.forEach(element => {
            TMDBmovieIds.push(element.id)
        })
23
24
25
26
27
28
29
        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
30
31
                    else return acc + cur.name
                }, '')
32
33
34
35
36
                newObj.name = name
            } else newObj.name = "없음"

            return newObj
        }))
37
        findDirectorResult.forEach(element => TMDBmovies.forEach(movie => {
38
39
            if (element.id === movie.id) movie.director = element.name
        }))
Kim, Subin's avatar
Kim, Subin committed
40
41
42
43
44
45
        const responseAfterCompare = await Movie.findAll({
            where: {
                movieId: TMDBmovieIds
            },
            attributes: ['movieId']
        })
46
47
48
        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
49
        }))
Kim, Subin's avatar
Kim, Subin committed
50
        return res.json({ TMDBmovies, totalPage })
Kim, Subin's avatar
Kim, Subin committed
51
52
53
54
    } catch (error) {
        return res.status(500).send(error.message || "영화 가져오는 중 에러 발생")
    }
}
Jiwon Yoon's avatar
Jiwon Yoon committed
55

56
57
58
59
60
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
61
        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}`)
62
        req.TMDBmovies = response.data.results
Kim, Subin's avatar
Kim, Subin committed
63
        req.totalPage = response.data.total_pages
64
65
66
        next()
    } catch (error) {
        return res.status(500).send(error.message || "영화 가져오는 중 에러 발생")
Jiwon Yoon's avatar
Jiwon Yoon committed
67
68
69
    }
}

한규민's avatar
한규민 committed
70
const getMovieById = async (req, res, next) => {
한규민's avatar
한규민 committed
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
    try {
        const reservation = req.reservation
        const movieId = reservation.map(movie => movie.movieId);
        const elements = await Promise.all(
            movieId.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`)
                const movieData = {
                    movieId : movie.data.id,
                    poster_path : movie.data.poster_path,
                    title : movie.data.title
                }
                return movieData
            })
        )
        reservation.map(reservation => {
한규민's avatar
한규민 committed
86
            const movieId = elements.find(el => reservation.movieId === el.movieId ); 
한규민's avatar
한규민 committed
87
88
89
90
91
92
            reservation.dataValues = {
                ...reservation.dataValues,
                poster_path: movieId.poster_path,
                title: movieId.title
            }
        });
한규민's avatar
한규민 committed
93
94
        req.reservation = reservation;
        next();
한규민's avatar
한규민 committed
95
96
97
98
99
    } catch (error) {
        return res.status(500).send(error.message || "영화 가져오기 중 에러 발생");
    }
}

100
const getMovieList = async (req, res) => {
Jiwon Yoon's avatar
Jiwon Yoon committed
101
    try {
Kim, Subin's avatar
Kim, Subin committed
102
        const { category } = req.params
Jiwon Yoon's avatar
Jiwon Yoon committed
103
        const movieList = await Movie.findAll()
104
        const movieIds = []
Jiwon Yoon's avatar
Jiwon Yoon committed
105
106
        movieList.forEach(el => {
            movieIds.push(el.movieId)
Jiwon Yoon's avatar
Jiwon Yoon committed
107
        })
Jiwon Yoon's avatar
Jiwon Yoon committed
108
109
110
        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`)
111
112
113
114
                const cols = await Movie.findOne({
                    where: { "movieId": movieId },
                    attributes: ["ticket_sales", "vote_average"]
                })
Jiwon Yoon's avatar
Jiwon Yoon committed
115
116
                const totalReservationRate = await Movie.findAll({
                    attributes: [[sequelize.fn('SUM', sequelize.col('ticket_sales')), 'totalReservationRate']]
Kim, Subin's avatar
Kim, Subin committed
117
118
                });
                return { ...movie.data, ticket_sales: cols.ticket_sales, vote_average: cols.vote_average, totalReservationRate: totalReservationRate[0] }
119

Jiwon Yoon's avatar
Jiwon Yoon committed
120
            })
121
        )
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
        if (category === "popular") {
            for (let i = 0; i < elements.length; i++) {
                if (new Date(elements[i].release_date) > new Date()) {
                    elements.splice(i, 1);
                    i--;
                }
            }
            elements.sort(function (a, b) {
                return b.popularity - a.popularity
            })
            res.json(elements)
        } else if (category === "upcoming") {
            for (let i = 0; i < elements.length; i++) {
                if (new Date(elements[i].release_date) <= new Date()) {
                    elements.splice(i, 1);
                    i--;
                }
            }
            elements.sort(function (a, b) {
Jiwon Yoon's avatar
Jiwon Yoon committed
141
                return b.release_date - a.release_date
142
143
144
145
146
147
148
149
            })
            res.json(elements)
        } else {
            elements.sort(function (a, b) {
                return a.title - b.title
            })
            res.json(elements)
        }
Jiwon Yoon's avatar
Jiwon Yoon committed
150
    } catch (error) {
Kim, Subin's avatar
Kim, Subin committed
151
        return res.status(500).send(error.message || "영화 정보 가져오는 중 에러 발생")
Jiwon Yoon's avatar
Jiwon Yoon committed
152
153
154
    }
}

155
156
157
const create = async (req, res) => {
    try {
        const { movieId } = req.params
Kim, Subin's avatar
Kim, Subin committed
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
        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 || "영화 삭제 중 에러 발생");
    }
}

176
const findonlyTitle = async (req, res) => {
Kim, Subin's avatar
Kim, Subin committed
177
    try {
178
        const { keyword } = req.query
Kim, Subin's avatar
Kim, Subin committed
179
        const movieIds = []
180
        const findAll = await Movie.findAll({
Kim, Subin's avatar
Kim, Subin committed
181
182
            where: {
                title: {
183
                    [Op.substring]: keyword
Kim, Subin's avatar
Kim, Subin committed
184
185
186
                }
            }
        });
187
188
        if (findAll) {
            findAll.forEach(movie => movieIds.push(movie.movieId))
Kim, Subin's avatar
Kim, Subin committed
189
190
191
            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
192
193
194
195
196
197
                    const cols = await Movie.findOne({
                        where: { "movieId": movieId },
                        attributes: ["ticket_sales", "vote_average"]
                    })
                    const totalReservationRate = await Movie.findAll({
                        attributes: [[sequelize.fn('SUM', sequelize.col('ticket_sales')), 'totalReservationRate']]
Kim, Subin's avatar
Kim, Subin committed
198
199
                    });
                    return { ...movie.data, ticket_sales: cols.ticket_sales, vote_average: cols.vote_average, totalReservationRate: totalReservationRate[0] }
Kim, Subin's avatar
Kim, Subin committed
200
201
                })
            )
202
203
            return res.json(elements)
        } else return res.json(findAll)
204
    } catch (error) {
Kim, Subin's avatar
Kim, Subin committed
205
        return res.status(500).send(error.message || "영화 검색 중 에러 발생");
206
207
208
    }
}

209
210
const findaboutAll = async (req, res, next) => {
    try {
Kim, Subin's avatar
Kim, Subin committed
211
212
        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}`)
213
        req.TMDBmovies = response.data.results
Kim, Subin's avatar
Kim, Subin committed
214
        req.totalPage = response.data.total_pages
215
        next()
216
    } catch (error) {
217
        return res.status(500).send(error.message || "영화 검색 중 에러 발생");
218
219
220
221
    }
}

export default {
222
    getListfromDB,
Kim, Subin's avatar
Kim, Subin committed
223
    getAllMovie,
한규민's avatar
한규민 committed
224
    getMovieById,
Jiwon Yoon's avatar
Jiwon Yoon committed
225
    getMovieList,
226
    create,
Kim, Subin's avatar
Kim, Subin committed
227
    remove,
228
229
230
    findonlyTitle,
    findaboutAll,
    movieforAdmin
Jiwon Yoon's avatar
Jiwon Yoon committed
231
}