Commit c42e9ffb authored by 한규민's avatar 한규민
Browse files

Merge branch 'master' into gyumin

parents 6aa99cb4 fdd2a316
......@@ -3,67 +3,124 @@ import sequelize from 'sequelize';
const { Op } = sequelize
import { Movie } from '../db/index.js'
const comparePopularMovie = async (req, res) => {
const responsePopular = await axios.get(`https://api.themoviedb.org/3/movie/popular?api_key=${process.env.TMDB_APP_KEY}&language=ko-KR`)
const movies = responsePopular.data.results
const movieIds = []
movies.forEach(element => {
movieIds.push(element.id)
});
console.log(movieIds)
const getMovieByCategory = async (req, res, next, category) => {
try {
console.log(category)
const TMDBmovieIds = []
const movieIds = []
console.log(process.env.TMDB_APP_KEY)
const response = await axios.get(`https://api.themoviedb.org/3/movie/${category}?api_key=${process.env.TMDB_APP_KEY}&language=ko-KR&page=1`)
console.log(response.data)
const TMDBmovies = response.data.results
TMDBmovies.forEach(element => {
TMDBmovieIds.push(element.id)
})
console.log(TMDBmovies)
const responseAfterCompare = await Movie.findAll({
where: {
movieId: {
[Op.or]: movieIds
[Op.or]: TMDBmovieIds
}
}
})
const popularMovieIds = []
responseAfterCompare.forEach(el => {
popularMovieIds.push(el.movieId)
movieIds.push(el.movieId)
})
console.log('popularMovieIds=', popularMovieIds)
const m = await Promise.all(
popularMovieIds.map(async(el) => {
const movie = await axios.get(`https://api.themoviedb.org/3/movie/${el}?api_key=${process.env.TMDB_APP_KEY}&language=ko-KR`)
console.log('movieIds=', movieIds)
req.movieIds = movieIds
next()
} catch (error) {
return res.status(500).send(error.message || "영화 가져오기 중 에러 발생");
}
}
const getMovieById = async (req, res) => {
try {
const movieIds = req.movieIds
console.log(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
})
)
res.json(m)
console.log(elements)
res.json(elements)
} catch (error) {
console.log(error)
return res.status(500).send(error.message || "영화 가져오기 중 에러 발생");
}
}
const upcommingMovie = async (req, res) => {
const responsePopular = await axios.get(`https://api.themoviedb.org/3/movie/upcoming?api_key=${process.env.TMDB_APP_KEY}&language=ko-KR&page=1`)
const movies = responsePopular.data.results
const movieIds = []
movies.forEach(element => {
movieIds.push(element.id)
});
console.log(movieIds)
const movieforAdmin = async (req, res) => {
try {
const TMDBmovieIds = []
const TMDBmovies = req.TMDBmovies
TMDBmovies.forEach(element => {
TMDBmovieIds.push(element.id)
})
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
else return acc + cur.name}, '')
newObj.name = name
} else newObj.name = "없음"
return newObj
}))
findDirectorResult.forEach(element => TMDBmovies.forEach(movie => {
if (element.id === movie.id) movie.director = element.name
}))
const responseAfterCompare = await Movie.findAll({
where: {
movieId: {
[Op.or]: movieIds
}
}
movieId: TMDBmovieIds
},
attributes: ['movieId']
})
const popularMovieIds = []
responseAfterCompare.forEach(el => {
popularMovieIds.push(el.movieId)
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
}))
return res.json(TMDBmovies)
} catch (error) {
return res.status(500).send(error.message || "영화 가져오는 중 에러 발생")
}
}
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]
// 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}`)
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=6`)
req.TMDBmovies = response.data.results
next()
} catch (error) {
return res.status(500).send(error.message || "영화 가져오는 중 에러 발생")
}
}
const getMovieList = async(req,res)=>{
try {
const movieList = await Movie.findAll()
// console.log(movieList)
const movieIds=[]
movieList.forEach(el => {
movieIds.push(el.movieId)
})
console.log('popularMovieIds=', popularMovieIds)
const m = await Promise.all(
popularMovieIds.map(async(el) => {
const movie = await axios.get(`https://api.themoviedb.org/3/movie/${el}?api_key=${process.env.TMDB_APP_KEY}&language=ko-KR`)
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
})
)
res.json(m)
)
console.log(elements)
res.json(elements)
} catch (error) {
console.log(error)
}
......@@ -72,14 +129,69 @@ const upcommingMovie = async (req, res) => {
const create = async (req, res) => {
try {
const { movieId } = req.params
const newMovie = await Movie.create({ movieId: movieId });
return res.json(newMovie);
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 || "영화 삭제 중 에러 발생");
}
}
const findonlyTitle = async (req, res) => {
try {
const { keyword } = req.query
const movieIds = []
const { count, rows } = await Movie.findAndCountAll({
where: {
title: {
[Op.substring]: keyword
}
}
});
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 })
} catch (error) {
return res.status(500).send(error.message || "영화 검색 중 에러 발생");
}
}
const findaboutAll = async (req, res, next) => {
try {
const { keyword } = 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`)
req.TMDBmovies = response.data.results
next()
} catch (error) {
return res.status(500).send(error.message || "영화 등록 중 에러 발생");
return res.status(500).send(error.message || "영화 검색 중 에러 발생");
}
}
export default {
comparePopularMovie,
getMovieByCategory,
getMovieById,
getAllMovie,
getMovieList,
create,
remove,
findonlyTitle,
findaboutAll,
movieforAdmin
}
......@@ -2,7 +2,7 @@ import jwt from "jsonwebtoken";
import config from "../config/app.config.js";
import { User, Role } from '../db/index.js'
const login = async(req, res) => {
const login = async (req, res) => {
try {
const { id, password } = req.body;
//사용자 존재 확인
......@@ -47,21 +47,21 @@ const login = async(req, res) => {
}
const logout = async(req, res) => {
try{
const logout = async (req, res) => {
try {
res.cookie()
}catch(error) {
} catch (error) {
console.error(error);
return res.status(500).send("로그인 에러");
} }
}
const compareId = async (req, res) => {
const id = req.params.userId;
const userid = await User.findOne({where:{userId: id}});
if(userid !== null){
const userid = await User.findOne({ where: { userId: id } });
if (userid !== null) {
return res.json(true);
}else{
} else {
return res.json(false);
}
}
......@@ -71,11 +71,11 @@ const signup = async (req, res) => {
// 휴대폰 중복 확인
const userMbnum = String(req.body.userMbnum);
try {
const mbnum = await User.findOne({ where: { phoneNumber: userMbnum } });
const mbnum = await User.findOne({ where: { phoneNumber: userMbnum } });
if (mbnum) {
return res.status(422).send(`이미 있는 휴대폰번호입니다.`);
}
const role = await Role.findOne({ where: {name: "user"} })
const role = await Role.findOne({ where: { name: "user" } })
const newUser = await User.create({
userId: userId,
nickname: userNickName,
......
......@@ -2,6 +2,7 @@ import { Sequelize } from "sequelize";
import UserModel from "../models/user.model.js";
import RoleModel from "../models/role.model.js";
import MovieModel from "../models/movie.model.js";
import CinemaModel from "../models/cinema.model.js";
import dbConfig from "../config/db.config.js";
const sequelize = new Sequelize(
......@@ -23,6 +24,10 @@ const sequelize = new Sequelize(
const User = UserModel(sequelize)
const Role = RoleModel(sequelize)
const Movie = MovieModel(sequelize)
const Cinema = CinemaModel(sequelize)
User.belongsTo(Role);
Role.hasOne(User);
User.belongsTo(Role);
Role.hasOne(User);
......@@ -31,5 +36,6 @@ export {
sequelize,
User,
Role,
Movie
Movie,
Cinema
}
\ No newline at end of file
......@@ -10,7 +10,7 @@ dotenv.config({
});
sequelize
.sync({ force: false })
.sync({ force: true })
.then(async () => {
await Promise.all(
Object.keys(ROLE_NAME).map((name) => {
......
import Sequelize from "sequelize";
const { DataTypes } = Sequelize;
const CinemaModel = (sequelize) => {
const Cinema = sequelize.define(
"cinema",
{
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
cinemaName: {
type: DataTypes.STRING,
},
transportation: {
type: DataTypes.TEXT
},
parking: {
type: DataTypes.TEXT
},
address: {
type: DataTypes.STRING
}
},
{
timestamps: true,
freezeTableName: true,
tableName: "cinemas"
}
);
return Cinema;
};
export default CinemaModel;
\ No newline at end of file
......@@ -15,6 +15,12 @@ const MovieModel = (sequelize) => {
type: DataTypes.INTEGER,
unique: true,
},
title: {
type: DataTypes.STRING,
},
release_date: {
type: DataTypes.STRING,
},
ticket_sales: {
type: DataTypes.FLOAT,
defaultValue: 0.0,
......
import express from "express";
import cinemaCtrl from "../controllers/cinema.controller.js";
const router = express.Router();
router
.route("/")
.get(cinemaCtrl.getAll)
.put(cinemaCtrl.edit)
export default router;
\ No newline at end of file
import express from "express";
import userRouter from './user.route.js'
import movieRouter from './movie.route.js'
import cinemaRouter from "./cinema.route.js";
const router = express.Router();
router.use('/movie', movieRouter)
router.use('/auth', userRouter)
router.use('/cinema', cinemaRouter)
export default router;
\ No newline at end of file
......@@ -5,11 +5,34 @@ const router = express.Router();
router
.route("/")
.post(movieCtrl.comparePopularMovie)
.get(movieCtrl.comparePopularMovie)
// .post(movieCtrl.comparePopularMovie)
router.route('/showmovies/:category')
.get(movieCtrl.getMovieById)
router.route('/movielist')
.get(movieCtrl.getMovieList)
router
.route("/all")
.get(movieCtrl.getAllMovie,
movieCtrl.movieforAdmin
)
router
.route("/search/home")
.get(movieCtrl.findonlyTitle)
router
.route("/search/admin")
.get(movieCtrl.findaboutAll,
movieCtrl.movieforAdmin
)
router
.route("/:movieId")
.post(movieCtrl.create)
.delete(movieCtrl.remove)
router.param('category', movieCtrl.getMovieByCategory)
export default router;
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment