Commit 1bd65831 authored by baesangjune's avatar baesangjune
Browse files

Merge remote-tracking branch 'origin/cherry' into BAE

parents 1b46e125 e08aede8
...@@ -2,7 +2,8 @@ const config = { ...@@ -2,7 +2,8 @@ const config = {
env: process.env.NODE_ENV || 'development', env: process.env.NODE_ENV || 'development',
port: process.env.PORT || 3001, port: process.env.PORT || 3001,
jwtSecret: process.env.JWT_SECRET || 'My_Secret_Key', jwtSecret: process.env.JWT_SECRET || 'My_Secret_Key',
mongoDbUri: process.env.MONGODB_URI || 'mongodb://localhost/search_page' mongoDbUri: process.env.MONGODB_URI || 'mongodb://localhost/search_page',
cookieMaxAge: 60 * 60 * 24 * 7 * 1000
} }
export default config export default config
\ No newline at end of file
import User from "../models/User.js"
import bcrypt from "bcryptjs"
import jwt from "jsonwebtoken"
import config from "../config.js"
const login = async (req, res) => {
const { email, password } = req.body //구조분해해서 하나씩
console.log( email, password)
try {
const user = await User.findOne({email}).select('+password')
if (!user) {
return res.status(404).send(`${email}이 없습니다`)
}
const passwordMatch = await bcrypt.compare(password, user.password)
if (passwordMatch) {
const token = jwt.sign({userId: user._id}, config.jwtSecret,{
expiresIn: '7d'
})
res.cookie('token', token, {
maxAge: config.cookieMaxAge,
httpOnly: true,
secure: config.env === 'production'
})
res.json({userId: user._id})
} else {
res.status(401).send('비밀번호가 일치하지 않습니다')
}
} catch (error) {
console.log(error)
res.status(500).send('로그인 에러')
}
}
const logout = (req, res) => {
res.clearCookie('token')
res.send('Logout Successful')
}
export default { login, logout}
\ No newline at end of file
import Places from '../models/Place.js' import Places from '../models/Place.js'
import cheerio from 'cheerio' import cheerio from 'cheerio'
import fs from 'fs'
import axios from 'axios'; import axios from 'axios';
import { nextTick } from 'process';
const searchPlace = async (req, res, next,) => { const searchPlace = async (req, res, next,) => {
...@@ -25,9 +23,7 @@ const searchPlace = async (req, res, next,) => { ...@@ -25,9 +23,7 @@ const searchPlace = async (req, res, next,) => {
}) })
req.places = places req.places = places
} }
next() next()
} }
const searchImg = async (req, res, next) => { const searchImg = async (req, res, next) => {
...@@ -47,24 +43,31 @@ const searchImg = async (req, res, next) => { ...@@ -47,24 +43,31 @@ const searchImg = async (req, res, next) => {
let $1 = cheerio.load(html); let $1 = cheerio.load(html);
let images = $1('.RAyV4b').find('img').attr('src') let images = $1('.RAyV4b').find('img').attr('src')
req.places.img = images req.places.img = images
<<<<<<< HEAD
=======
console.log("4141414141414141", req.places)
//사진만 업데이트
// let Place2 = await Places.findOne({ name: req.query.keyword })
>>>>>>> origin/cherry
req.places.times.push(new Date().toLocaleString()) req.places.times.push(new Date().toLocaleString())
const newPlaces = await new Places(req.places).save() const newPlaces = await new Places(req.places).save()
next() next()
}) })
} else { } else {
console.log("이미지 생성 오류발생!!") console.log("이미지 생성 오류발생!!")
} }
} }
const searchAssociation = async (req, res) => { const searchAssociation = async (req, res) => {
let Place3 = req.places.address let Place3 = req.places.address
if (!Place3) { if (!Place3) {
<<<<<<< HEAD
=======
console.log("asdfasdfasdf222222222222222222dsaf2222222222214123q5", Place3)
>>>>>>> origin/cherry
res.send({ error: "Place.address is null" }) res.send({ error: "Place.address is null" })
} }
else { else {
let addresse = Place3.split(' ')[0] let addresse = Place3.split(' ')[0]
let AssociationsId = [] let AssociationsId = []
let addressPlaces = new RegExp(`${addresse}`) let addressPlaces = new RegExp(`${addresse}`)
let responsePlaces = await Places.find({ address: addressPlaces }).sort({ updatedAt: -1 }) let responsePlaces = await Places.find({ address: addressPlaces }).sort({ updatedAt: -1 })
...@@ -73,4 +76,4 @@ const searchAssociation = async (req, res) => { ...@@ -73,4 +76,4 @@ const searchAssociation = async (req, res) => {
} }
export default { searchImg, searchPlace, searchAssociation } export default { searchImg, searchPlace, searchAssociation }
...@@ -2,97 +2,66 @@ import Review from '../models/Review.js' ...@@ -2,97 +2,66 @@ import Review from '../models/Review.js'
import cheerio from "cheerio"; import cheerio from "cheerio";
import axios from 'axios'; import axios from 'axios';
const search = async (req, res, next) => { const search = async (req, res) => {
console.log("1") try {
for (let i = 1; (req.reviews).length > 10; i++) { let reviews = []
try { console.log(req.reviews, "제발")
console.log("2")
let reviews = []
let content = []
const url = "https://www.google.com/search?q=" + encodeURI(req.query.keyword) + "+site%3Atistory.com&page_no=" + i
const response1 = await axios.get(url)
// console.log(response1.data)
const $1 = cheerio.load(response1.data);
$1('.kCrYT').each(async function (i) {
console.log("3")
const title = $1(this).find('h3').text()
const searchParams = new URLSearchParams($1(this).find('a').attr('href'));
const link = searchParams.get("/url?q")
const summary = $1(this).find('.s3v9rd').find('.s3v9rd').text()
Review.find({ link: link }, function (err, review) {
if (!review) {
content.push(getReview(link))
if (title) {
reviews[i] = { title: title, link: link }
} else if (summary) {
reviews[i - 1] = { ...reviews[i - 1], summary: summary }
reviews = reviews.filter(e => e)
}
}
})
})
let promiseReview = await Promise.all(content)
promiseReview = promiseReview.filter(e => typeof (e) === 'string')
reviews.forEach(async (review, i) => {
console.log("4")
review["content"] = promiseReview[i]
const reviews = new Review(review).save()
reviews.keyword.push(req.query.keyword)
req.reviews.push(reviews)
})
console.log("5")
res.send(reviews)
} catch (error) {
console.log("6")
console.log(error)
res.send(error)
}
}
}
//***************네이버 크롤링 할 때 ********************* */
// try {
// let reviews = []
// let content = []
// const url = "https://search.naver.com/search.naver?where=view&sm=tab_jum&query=" + encodeURI('한라산')
// const response1 = await axios.get(url)
// // console.log(response1.data)
// const $1 = cheerio.load(response1.data);
// $1('._list').find('.total_wrap').each(async function (i) {
// reviews[i] = { name: $1(this).find('.total_tit').text(), summery: $1(this).find('.dsc_txt').text(), link: $1(this).find('.total_tit').attr('href') }
// })
// res.send(reviews)
// } catch (error) {
// console.log(error)
// res.send(error)
// }
// }
const getReview = async (link) => { let url = "https://www.google.com/search?q=" + encodeURI(req.query.keyword) + `+site%3Atistory.com&start=${Number(req.query.index) * 10}`
if (link) { console.log(url)
let content = '없음' let response1 = await axios.get(url)
const res = await axios.get(link) let $1 = cheerio.load(response1.data);
const $2 = cheerio.load(res.data); $1('.kCrYT').each(async function (i) {
if ($2('.tt_article_useless_p_margin').text()) { console.log("3")
content = $2('.tt_article_useless_p_margin').text() let title = $1(this).find('h3').text()
} let searchParams = new URLSearchParams($1(this).find('a').attr('href'));
return content let link = searchParams.get("/url?q")
let summary = $1(this).find('.s3v9rd').find('.s3v9rd').text()
if (title) {
reviews[i] = { title: title, link: link }
} else if (summary) {
reviews[i - 1] = { ...reviews[i - 1], summary: summary }
reviews = reviews.filter(e => e)
}
})
// reviews.forEach(async (review, i) => {
// await Review.updateOne({ link: review.link }, { $push: { bookmark: req.query.keyword } })
// const reviewss = await Review.findOne({ link: review.link })
// if (!reviewss) {
// // reviews["keyword"] = [req.query.keyword]
let newReviews = []
newReviews = [...newReviews, ...reviews]
// await new Review(review).save()
// }
// })
// console.log(req.reviews, "걸러낸 리뷰즈입니다")
// const a = await Promise.all(newReviews)
// console.log(a, "2")
console.log(req.query.index, "인덱스ㅡㅡ")
res.status(200).send({ review: newReviews, db: true, index: Number(req.query.index) + 1 })
} catch (error) {
console.log("6")
console.log(error)
} }
} }
const find = (req, res, next) => {
res.send("안녕") const find = async(req, res, next) => {
// console.log("7", req.body) console.log("7", req.query)
// if (req.body.db) { const keyword = req.query.keyword
// next() if (req.body.db) {
// } next()
// Review.find({ keyword:{ $elemMatch: res.query.keyword } }, function (err, reviews) { }
// if (reviews) { await Review.find({ keyword: keyword }, function (err, reviews) {
// if (reviews.length > 10) req.reviews = []
// res.send(reviews, { db: true }) if (reviews) {
// req.reviews = reviews if (reviews.length > 5) {
// } res.status(200).send({ review: reviews, db: true, message: "제발용" })
// next() }
// }) req.reviews = reviews
}
next()
})
} }
export default { search, find } export default { search, find }
import User from "../models/User.js"
import isLength from 'validator/lib/isLength.js'
import isEmail from "validator/lib/isEmail.js"
import bcrypt from "bcryptjs";
const signup = async (req, res) => {
const { name, email, password } = req.body //구조분해해서 하나씩
console.log(name, email, password)
try {
if (!isLength(name, { min: 3, max: 10 })) {
return res.status(422).send('이름은 3-10자 사이입니다')
} else if (!isLength(password, { min: 6 })) {
return res.status(422).send('비밀번호는 6자 이상입니다')
} else if (!isEmail(email)) {
return res.status(422).send('유효하지 않은 이메일 형식입니다')
}
const user = await User.findOne({ email })
if (user) {
return res.status(422).send(`${email}이 이미 사용중입니다`)
}
const hash = await bcrypt.hash(password, 10)
const newUser = await new User({
name,
email,
password: hash
}).save() //save하면 몽고 db에 들어간다 save method가 promise
console.log(newUser)
res.json(newUser) //json형식으로 바꿔서 문자열로 보낸다 client쪽으로
} catch (error) { //다른 과정에서 에러가 나면 실행
console.log(error)
res.status(500).send('회원가입 에러')
}
}
const userById = async (req, res, next, id) => {
try {
const user = await User.findById(id)
if (!user) {
res.status(404).send('사용자를 찾을 수 없습니다')
}
req.profile = user
next()
} catch (error) {
console.log(error)
res.status(500).send('사용자 아이디 검색 실패')
}
}
const getBookmark = async (req, res) => {
await User.findOne({ _id: req.query.ID }).populate('bookmark').exec((err, bookmark) => {
console.log(bookmark, "dkssud")
res.send(bookmark)
})
}
const setBookmark = async (req, res) => {
console.log(req.query.ID, req.query.place, "여기에요 여기!!!!")
await User.updateOne({ _id: req.query.ID }, { $push: { bookmark: req.query.place } })
res.send("추가완료")
}
const deleteBookmark = async (req, res) => {
console.log(req.query.ID, req.query.place)
await User.updateOne({ _id: req.query.ID }, { $pull: { bookmark: req.query.place } })
res.send("삭제완료")
}
export default { signup, userById, getBookmark, setBookmark, deleteBookmark }
\ No newline at end of file
...@@ -15,9 +15,6 @@ const ReviewSchema = new mongoose.Schema({ ...@@ -15,9 +15,6 @@ const ReviewSchema = new mongoose.Schema({
type: String, type: String,
// required: true, // required: true,
}, },
content: {
type: String,
},
keyword: { keyword: {
type: Array, type: Array,
// required: true, // required: true,
......
import mongoose from "mongoose";
const { String, Array, ObjectId } = mongoose.Schema.Types
const UserSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
select: false,
},
role: {
type: String,
required: true,
default: 'user',
enum: ['user', 'admin', 'root']
},
bookmark: [{
type: ObjectId,
ref: 'Place'
}]
}, {
timestamps: true
})
export default mongoose.models.User || mongoose.model('User', UserSchema)
import express from "express"
import authCtrl from "../controllers/auth.controller.js"
const router = express.Router()
router.route('/api/auth/login')
.post(authCtrl.login)
router.route('/api/auth/logout')
.get(authCtrl.logout)
export default router
\ No newline at end of file
import express from "express"
import userCtrl from '../controllers/user.controller.js'
const router = express.Router()
router.route('/api/users/signup')
.post(userCtrl.signup)
router.route('/api/users/bookmark')
.get(userCtrl.getBookmark)
.put(userCtrl.setBookmark)
.delete(userCtrl.deleteBookmark)
router.param('userId', userCtrl.userById)
export default router
\ No newline at end of file
...@@ -3,6 +3,8 @@ import connectDb from './utils/connectDb.js' ...@@ -3,6 +3,8 @@ import connectDb from './utils/connectDb.js'
import placeRouter from './routes/place.routes.js' import placeRouter from './routes/place.routes.js'
import reviewRouter from './routes/review.routes.js' import reviewRouter from './routes/review.routes.js'
import appRouter from './routes/app.router.js' import appRouter from './routes/app.router.js'
import userRouter from "./routes/user.routes.js"
import authRouter from "./routes/auth.routes.js"
connectDb() connectDb()
...@@ -14,11 +16,14 @@ app.use(placeRouter) ...@@ -14,11 +16,14 @@ app.use(placeRouter)
app.use(reviewRouter) app.use(reviewRouter)
app.use(appRouter) app.use(appRouter)
app.use(userRouter)
app.use(authRouter)
app.get('/', (req, res) => { app.get('/', (req, res) => {
console.log("/ req.body", req.body) console.log("/ req.body", req.body)
res.json({ message: "http://localhost3001/ 에 연결됨" }) res.json({ message: "http://localhost3001/ 에 연결됨" })
}) })
app.listen(3001, () => { app.listen(3001, () => {
console.log('Server is listening on port 3001') console.log('Listening on port 3001')
}) })
\ 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