user.controller.js 2.28 KB
Newer Older
Lee SeoYeon's avatar
0111    
Lee SeoYeon committed
1
2
3
4
5
6
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) => {
Lee SeoYeon's avatar
.    
Lee SeoYeon committed
7
    const { name, email, password } = req.body //구조분해해서 하나씩
Lee SeoYeon's avatar
.    
Lee SeoYeon committed
8
    console.log(name, email, password)  
Lee SeoYeon's avatar
.    
Lee SeoYeon committed
9
    try {             //적어도 3개 맥시멈 10개 가 아니면 
Lee SeoYeon's avatar
0111    
Lee SeoYeon committed
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
        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
Lee SeoYeon's avatar
.    
Lee SeoYeon committed
26
        }).save() //save하면 몽고 db에 들어간다 save method가 promise
Lee SeoYeon's avatar
0111    
Lee SeoYeon committed
27
        console.log(newUser)
Lee SeoYeon's avatar
.    
Lee SeoYeon committed
28
29
        res.json(newUser) //json형식으로 바꿔서 문자열로 보낸다 client쪽으로
    } catch (error) { //다른 과정에서 에러가 나면 실행 
Lee SeoYeon's avatar
0111    
Lee SeoYeon committed
30
31
32
33
        console.log(error)
        res.status(500).send('회원가입 에러')
    }
}
Lee SeoYeon's avatar
.    
Lee SeoYeon committed
34
                              
Lee SeoYeon's avatar
0111    
Lee SeoYeon committed
35
36
37
38
39
40
41
const userById = async (req, res, next, id) => {
    try {
        const user = await User.findById(id)
        if (!user) {
            res.status(404).send('사용자를 찾을 수 없습니다')
        }
        req.profile = user
Lee SeoYeon's avatar
.    
Lee SeoYeon committed
42
        next() //만나는 순간 다음 미들웨어로 진행 없으면 가만히 있는다
Lee SeoYeon's avatar
0111    
Lee SeoYeon committed
43
44
45
46
47
48
    } catch (error) {
        console.log(error)
        res.status(500).send('사용자 아이디 검색 실패')
    }
}

Lee SeoYeon's avatar
.    
Lee SeoYeon committed
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
const bookMark = async (req, res) => {
    const {title, url} = req.body
    console.log(title, url)
    try {
        let bookmark = []
        const newBookmark = await new User ({
            bookmark,
        }).save() 
    } catch (error) {
        console.log(error)
        res.status(500).send('사용자 아이디 검색 실패')
    } 
}

export default { signup, userById }