Skip to content
Snippets Groups Projects
Commit 86cfc717 authored by Hyun Woo Jeong's avatar Hyun Woo Jeong
Browse files

정렬, 검색 구현

parent db607f2b
No related branches found
No related tags found
No related merge requests found
......@@ -6,8 +6,6 @@ import moment from 'moment'
import userService from '../user/userService.js';
import articleService from './articleService.js';
const __dirname = path.resolve();
export const router = express.Router();
......@@ -116,4 +114,28 @@ router.put("/:id/like", async (req, res) => {
res.send(JSON.stringify(articles));
});
router.get("/search/:keyword", async (req, res) => {
if(req.session.sessionid){
console.log("세션 O")
}
else {
console.log("세션 X")
}
console.log(req.params.keyword)
const articles = await articleService.findArticlesByKeyword(req.params.keyword);
res.send(JSON.stringify(articles));
});
router.get("/sort/:crit", async (req, res) => {
if(req.session.sessionid){
console.log("세션 O")
}
else {
console.log("세션 X")
}
console.log(req.params.crit)
const articles = await articleService.findAllAndSortArticle(req.params.crit);
res.send(JSON.stringify(articles));
});
export default router;
......@@ -23,6 +23,63 @@ const articleService = {
}
},
async findAllAndSortArticle(criteria) {
if (criteria==="time"){
try {
const articles = await Article
.find({})
.populate('author')
.populate('likes')
.sort({"createdAt": -1});
return articles;
} catch (err) {
throw err;
}
}
else if (criteria==="like") {
try {
const agg =
await Article.aggregate(
[
{ "$project":
{
"title": 1,
"content": 1,
"imageUrls": 1,
"author": 1,
"keyword": 1,
"latitude": 1,
"longitude": 1,
"comments": 1,
"likes": 1,
"createdAt": 1,
"length": { "$size": "$likes" }
}
},
{ "$sort": { "length": -1 } },
]
)
let articles = null;
const result = await Article.populate(agg, {path: "author"}).then(
(res)=>{return Article.populate(res, {path: "likes"})}
).then(
(res)=>{articles = res;}
);
return articles;
} catch (err) {
throw err;
}
}
else {
console.log("invalid criteria.");
return;
}
},
async findArticleById(articleId) {
try {
const article = await Article
......@@ -47,6 +104,18 @@ const articleService = {
throw err;
}
},
async findArticlesByKeyword(keyword) {
try {
const articles = await Article
.find({ keyword: keyword })
.populate('author')
.populate('likes');
return articles;
} catch (err) {
throw err;
}
},
async deleteArticle(articleId) {
try {
......
......@@ -38,7 +38,7 @@ app.use(
); //cors 설정을 한다..
// app.use(express.static(path.join(process.cwd(), '../public')));
app.use(express.static('files'));
app.use(express.static('public'));
app.use(cookieParser());
app.use(express.json());
......
......@@ -20,8 +20,8 @@ function Article({ data }) {
// http://localhost:8080/uploads/21701487062905.png
return (
<img
src={`http://localhost:8080/${el.replaceAll("\\", "/").substring(5)}`}
alt={`http://localhost:8080/${el.replaceAll("\\", "/").substring(5)}`}
src={`http://localhost:8080/${el.replaceAll("\\", "/").substring(7)}`}
alt={`http://localhost:8080/${el.replaceAll("\\", "/").substring(7)}`}
style={{ width: "100px", height: "100px" }} />
)
});
......
......@@ -38,13 +38,29 @@ function Main() {
})
}, []);
const handleSortChange = (event) => {
console.log(event.target.value)
requestSortArticle(event.target.value)
.then((response) => {
console.log(response)
setArticleList(response.data)
})
};
return(
<div className="App">
<h1>메인 페이지 입니다.</h1>
<div className="introduction">
소개 내용을 담을 공간
</div>
<Button>검색</Button>
<div style={{display: 'flex'}}>
<Button>검색</Button>
<select id="addInputPrior" onChange={handleSortChange}>
<option value="time">최신순</option>
<option value="like">인기순</option>
</select>
</div>
{listItem}
</div>)
;
......@@ -58,4 +74,12 @@ async function requestLoadArticle() {
return response;
}
async function requestSortArticle(crit) {
const response = await axios({
url: `http://localhost:8080/article/sort/${crit}`, // 통신할 웹문서
method: 'get', // 통신할 방식
});
return response;
}
export default Main;
......@@ -3,10 +3,13 @@ import React, { useState, useEffect, useContext } from 'react';
import {Routes, Route, Link, useNavigate, Navigate } from 'react-router-dom';
import SearchMap from '../components/SearchMapByKeyword.js'
import { UserContext } from '../Context.js';
import Article from '../components/Article.js';
import axios from 'axios';
axios.defaults.withCredentials = true;
const {kakao} = window;
function Search(props) {
const [articleList, setArticleList] = useState([])
const userContext = useContext(UserContext);
const navigate = useNavigate();
function MoveTo(link){
......@@ -24,21 +27,79 @@ function Search(props) {
if (!response.data) {
alert("세션이 만료되었습니다. 다시 로그인 바랍니다.")
MoveTo('/login')
}
}
else {
requestLoadArticle()
.then((response) => {
console.log(response)
setArticleList(response.data)
})
}
})
.catch((response)=>{
console.log("error!:LogOut")
console.log(response)
})
});
}, []);
let listItem = [];
listItem = articleList.map((article)=>{
return(
<Article
key={article._id}
data={article}
></Article>
)
})
const onSubmit = e => {
e.preventDefault();
if (!location.keyword){
alert("검색대상을지정해주세요");
return
}
requestLoadArticleByKeyword(location.keyword)
.then((response) => {
console.log(response)
setArticleList(response.data)
})
};
return (
<div style={{display: 'flex'}}>
<div className="search">
<h1>검색페이지입니다.</h1>
<SearchMap loc={location} setLoc={setLocation}></SearchMap>
<form onSubmit={onSubmit} style={{display: 'flex'}}>
<input readonly value={location.keyword} type="text"></input>
<input type="submit"></input>
</form>
</div>
<div className="searchresult">
<h1>검색결과 {listItem.length} 확인</h1>
{listItem}
</div>
</div>
return (
<div className="search">
<h1>검색페이지입니다.</h1>
<SearchMap loc={location} setLoc={setLocation}></SearchMap>
</div>
);
}
async function requestLoadArticle() {
const response = await axios({
url: 'http://localhost:8080/article', // 통신할 웹문서
method: 'get', // 통신할 방식
});
return response;
}
async function requestLoadArticleByKeyword(keyword) {
const response = await axios({
url: `http://localhost:8080/article/search/${keyword}`, // 통신할 웹문서
method: 'get', // 통신할 방식
});
return response;
}
export default Search;
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment