Commit 50d901cf authored by Kim, Subin's avatar Kim, Subin
Browse files

Pagination 수정 중

parent f1ca9c13
import axios from "axios"; import axios from "axios";
import { baseUrl, TMDBUrl } from "../utils/baseUrl.js"; import { baseUrl, TMDBUrl } from "../utils/baseUrl.js";
const getAllfromTM = async () => { const getAllfromTM = async (pageNum) => {
const payload = { const payload = {
params: { params: {
pageNum: 1 pageNum
} }
} }
const { data } = await axios.get(`${baseUrl}/api/movie/all`, payload) const { data } = await axios.get(`${baseUrl}/api/movie/all`, payload)
...@@ -55,10 +55,11 @@ const remove = async (movieId) => { ...@@ -55,10 +55,11 @@ const remove = async (movieId) => {
return data return data
} }
const search = async ({ type, keyword }) => { const search = async ({ type, keyword }, pageNum) => {
const payload = { const payload = {
params: { params: {
keyword keyword,
pageNum
} }
} }
const { data } = await axios.get(`${baseUrl}/api/movie/search/${type}`, payload) const { data } = await axios.get(`${baseUrl}/api/movie/search/${type}`, payload)
......
...@@ -8,39 +8,53 @@ import catchErrors from "../../utils/catchErrors.js"; ...@@ -8,39 +8,53 @@ import catchErrors from "../../utils/catchErrors.js";
const MovieEdit = () => { const MovieEdit = () => {
const [search, setSearch] = useState({ type: "admin", keyword: "" }) const [search, setSearch] = useState({ type: "admin", keyword: "" })
const [movieList, setMovieList] = useState([]) const [movieList, setMovieList] = useState([])
const [totalPages, setTotalPages] = useState(0)
const [activePage, setActivePage] = useState(1)
const [error, setError] = useState("") const [error, setError] = useState("")
useEffect(() => { useEffect(() => {
getMovieList() paginate(activePage)
}, []) }, [])
async function getMovieList() { async function paginate(pageNum) {
try { try {
setError("") const { TMDBmovies, totalPage } = (search.keyword !== '') ? await movieApi.search(search, pageNum) : await movieApi.getAllfromTM(pageNum)
const getMovieList = await movieApi.getAllfromTM() setActivePage(pageNum)
setMovieList(getMovieList) setTotalPages(totalPage)
setMovieList(TMDBmovies)
} catch (error) { } catch (error) {
catchErrors(error, setError) catchErrors(error, setError);
} }
} }
async function searchMovie() { const prevPage = () => {
try { if (activePage > 1) {
setError("") paginate(activePage - 1)
const findMovie = await movieApi.search(search) } else {
setMovieList(findMovie) paginate(1);
} catch (error) {
catchErrors(error, setError)
} }
} };
const nextPage = () => {
if (activePage < totalPages) {
paginate(activePage + 1)
} else {
paginate(totalPages);
}
};
return ( return (
<> <>
<div className="d-flex justify-content-md-end justify-content-center mb-3"> <div className="d-flex justify-content-md-end justify-content-center mb-3">
<Search search={search} setSearch={setSearch} handleClick={searchMovie} /> <Search search={search} setSearch={setSearch} handleClick={paginate} />
</div> </div>
<MovieTable movieList={movieList} /> <MovieTable movieList={movieList} />
<Pagination /> <Pagination
totalPages={totalPages}
activePage={activePage}
prevPage={prevPage}
nextPage={nextPage}
paginate={paginate} />
</> </>
) )
} }
......
const Pagination = () => { import PaginationBoot from "./PaginationBoot";
const Pagination = ({ totalPages, activePage, prevPage, nextPage, paginate }) => {
const pageWidth = 5
const section = Math.floor((activePage - 1) / pageWidth)
let startPage = section * pageWidth + 1
if (startPage < 1) startPage = 1
let endPage = startPage + pageWidth - 1
if (endPage > totalPages) endPage = totalPages
const pageNumbers = []
for (let i = startPage; i <= endPage; i++) {
pageNumbers.push(i);
}
return ( return (
<nav className="col-12 col-md-4 offset-md-4 my-2" aria-label="Page navigation"> <PaginationBoot>
<ul className="pagination justify-content-center mb-0"> <PaginationBoot.First
<li className="page-item"> disabled={activePage <= 1}
<a className="page-link" href="#" aria-label="Previous"> onClick={() => paginate(1)}
<span aria-hidden="true">&laquo;</span> />
</a> <PaginationBoot.Prev onClick={prevPage} disabled={activePage <= 1} />
</li> {pageNumbers.map((number, index) => <PaginationBoot.Item
<li className="page-item"><a className="page-link" href="#">1</a></li> key={index}
<li className="page-item"><a className="page-link" href="#">2</a></li> active={activePage === number}
<li className="page-item"><a className="page-link" href="#">3</a></li> onClick={() => {
<li className="page-item"> console.log("number", number);
<a className="page-link" href="#" aria-label="Next"> paginate(number);
<span aria-hidden="true">&raquo;</span> }}
</a> >
</li> {number}
</ul> </PaginationBoot.Item>
</nav> )}
<PaginationBoot.Next
onClick={nextPage}
disabled={activePage >= totalPages}
/>
<PaginationBoot.Last
disabled={activePage >= totalPages}
onClick={() => paginate(totalPages)}
/>
</PaginationBoot>
) )
// return (
// <nav className="col-12 col-md-4 offset-md-4 my-2" aria-label="Page navigation">
// <ul className="pagination justify-content-center mb-0">
// <li className="page-item">
// <a className="page-link" href="#" aria-label="Previous">
// <span aria-hidden="true">&laquo;</span>
// </a>
// </li>
// <li className="page-item"><a className="page-link" href="#">1</a></li>
// <li className="page-item"><a className="page-link" href="#">2</a></li>
// <li className="page-item"><a className="page-link" href="#">3</a></li>
// <li className="page-item">
// <a className="page-link" href="#" aria-label="Next">
// <span aria-hidden="true">&raquo;</span>
// </a>
// </li>
// </ul>
// </nav>
// )
} }
export default Pagination export default Pagination
\ No newline at end of file
import { Link } from "react-router-dom";
const PaginationBoot = ({ children }) => {
return (
<nav aria-label="page navigation">
<ul className="pagination justify-content-center py-3">{children}</ul>
</nav>
);
};
const PageItem = ({
active = false,
disabled = false,
className = "",
style,
activeLabel = "(current)",
children,
...props
}) => {
return (
<li
style={style}
className={`${className}` + " page-item " + (active ? "active " : "") + (disabled ? "disabled " : "")}
>
<Link to="#" className={"page-link border-0 shadow-none " + (active ? "rounded-circle text-white" : "text-dark")} {...props}>
{children}
</Link>
</li>
);
};
const createButton = (name, defaultValue, label = name) => {
function Button({ children, ...props }) {
return (
<PageItem {...props}>
<span aria-hidden="true">{children || defaultValue}</span>
<span className="visually-hidden">{label}</span>
</PageItem>
);
}
Button.displayName = name;
return Button;
};
PaginationBoot.First = createButton("First", <i className="bi bi-chevron-double-left"></i>);
PaginationBoot.Prev = createButton("Prev", <i className="bi bi-chevron-left"></i>);
PaginationBoot.Item = PageItem;
PaginationBoot.Next = createButton("Next", <i className="bi bi-chevron-right"></i>);
PaginationBoot.Last = createButton("Last", <i className="bi bi-chevron-double-right"></i>);
export default PaginationBoot
\ No newline at end of file
...@@ -9,7 +9,7 @@ const Search = ({ search, setSearch, handleClick }) => { ...@@ -9,7 +9,7 @@ const Search = ({ search, setSearch, handleClick }) => {
return ( return (
<div className="d-flex"> <div className="d-flex">
<input className={`form-control ${search.type === "home" ? styles.searchWhite : `${styles.search}`}`} name="keyword" type="text" autoComplete="off" onChange={handleSearch} /> <input className={`form-control ${search.type === "home" ? styles.searchWhite : `${styles.search}`}`} name="keyword" type="text" autoComplete="off" onChange={handleSearch} />
<i className={`bi bi-search align-self-center ${search.type === "home" ? "text-white" : "mx-2"} ${styles.icon}`} onClick={handleClick} style={{ fontSize: "1.3rem" }}></i> <i className={`bi bi-search align-self-center ${search.type === "home" ? "text-white" : "mx-2"} ${styles.icon}`} onClick={() => handleClick(1)} style={{ fontSize: "1.3rem" }}></i>
</div> </div>
) )
} }
......
...@@ -70,4 +70,13 @@ $theme-colors: map-merge($theme-colors, $custom-colors); ...@@ -70,4 +70,13 @@ $theme-colors: map-merge($theme-colors, $custom-colors);
// .carousel-inner .carousel-item-end, // .carousel-inner .carousel-item-end,
// .carousel-inner .carousel-item-start { // .carousel-inner .carousel-item-start {
// transform: translateX(0); // transform: translateX(0);
// } // }
\ No newline at end of file
.page-item.active .page-link {
background-color: #FEDC00;
border-color: #FEDC00;
}
.page-link:hover, .page-link:focus {
background-color: #fff;
}
\ No newline at end of file
...@@ -5,7 +5,7 @@ const { Op } = sequelize ...@@ -5,7 +5,7 @@ const { Op } = sequelize
const getListfromDB = async (req, res) => { const getListfromDB = async (req, res) => {
try { try {
const findAll = await Movie.findAll({ attributes: [ 'movieId', 'title', 'release_date' ] }) const findAll = await Movie.findAll({ attributes: ['movieId', 'title', 'release_date'] })
res.json(findAll) res.json(findAll)
} catch (error) { } catch (error) {
return res.status(500).send(error.message || "영화 목록 가져오기 중 에러 발생"); return res.status(500).send(error.message || "영화 목록 가져오기 중 에러 발생");
...@@ -58,6 +58,7 @@ const movieforAdmin = async (req, res) => { ...@@ -58,6 +58,7 @@ const movieforAdmin = async (req, res) => {
try { try {
const TMDBmovieIds = [] const TMDBmovieIds = []
const TMDBmovies = req.TMDBmovies const TMDBmovies = req.TMDBmovies
const totalPage = req.totalPage
TMDBmovies.forEach(element => { TMDBmovies.forEach(element => {
TMDBmovieIds.push(element.id) TMDBmovieIds.push(element.id)
}) })
...@@ -68,13 +69,14 @@ const movieforAdmin = async (req, res) => { ...@@ -68,13 +69,14 @@ const movieforAdmin = async (req, res) => {
if (findDirectors.length !== 0) { if (findDirectors.length !== 0) {
const name = findDirectors.reduce((acc, cur, idx) => { const name = findDirectors.reduce((acc, cur, idx) => {
if (idx !== 0) return acc + ', ' + cur.name if (idx !== 0) return acc + ', ' + cur.name
else return acc + cur.name}, '') else return acc + cur.name
}, '')
newObj.name = name newObj.name = name
} else newObj.name = "없음" } else newObj.name = "없음"
return newObj return newObj
})) }))
findDirectorResult.forEach(element => TMDBmovies.forEach(movie => { findDirectorResult.forEach(element => TMDBmovies.forEach(movie => {
if (element.id === movie.id) movie.director = element.name if (element.id === movie.id) movie.director = element.name
})) }))
const responseAfterCompare = await Movie.findAll({ const responseAfterCompare = await Movie.findAll({
...@@ -87,7 +89,7 @@ const movieforAdmin = async (req, res) => { ...@@ -87,7 +89,7 @@ const movieforAdmin = async (req, res) => {
if (movie.existed !== true && movie.id === element.movieId) movie.existed = true if (movie.existed !== true && movie.id === element.movieId) movie.existed = true
else if (movie.existed !== true) movie.existed = false else if (movie.existed !== true) movie.existed = false
})) }))
return res.json(TMDBmovies) return res.json({ TMDBmovies, totalPage })
} catch (error) { } catch (error) {
return res.status(500).send(error.message || "영화 가져오는 중 에러 발생") return res.status(500).send(error.message || "영화 가져오는 중 에러 발생")
} }
...@@ -100,16 +102,17 @@ const getAllMovie = async (req, res, next) => { ...@@ -100,16 +102,17 @@ const getAllMovie = async (req, res, next) => {
const monthAgo = new Date(now.setMonth(now.getMonth() - 1)).toJSON().split(/T/)[0] 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=${pageNum}`)
req.TMDBmovies = response.data.results req.TMDBmovies = response.data.results
req.totalPage = response.data.total_pages
next() next()
} catch (error) { } catch (error) {
return res.status(500).send(error.message || "영화 가져오는 중 에러 발생") return res.status(500).send(error.message || "영화 가져오는 중 에러 발생")
} }
} }
const getMovieList = async(req,res)=>{ const getMovieList = async (req, res) => {
try { try {
const movieList = await Movie.findAll() const movieList = await Movie.findAll()
const movieIds=[] const movieIds = []
movieList.forEach(el => { movieList.forEach(el => {
movieIds.push(el.movieId) movieIds.push(el.movieId)
}) })
...@@ -121,7 +124,7 @@ const getMovieList = async(req,res)=>{ ...@@ -121,7 +124,7 @@ const getMovieList = async(req,res)=>{
) )
res.json(elements) res.json(elements)
} catch (error) { } catch (error) {
console.log(error) return res.status(500).send(error.message || "영화 정보 가져오는 중 에러 발생")
} }
} }
...@@ -174,9 +177,10 @@ const findonlyTitle = async (req, res) => { ...@@ -174,9 +177,10 @@ const findonlyTitle = async (req, res) => {
const findaboutAll = async (req, res, next) => { const findaboutAll = async (req, res, next) => {
try { try {
const { keyword } = req.query 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`) 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}`)
req.TMDBmovies = response.data.results req.TMDBmovies = response.data.results
req.totalPage = response.data.total_pages
next() next()
} catch (error) { } catch (error) {
return res.status(500).send(error.message || "영화 검색 중 에러 발생"); return res.status(500).send(error.message || "영화 검색 중 에러 발생");
......
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