user.controller.js 2.42 KB
Newer Older
Lee SeoYeon's avatar
0111    
Lee SeoYeon committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import User from "../models/User.js"
import isLength from 'validator/lib/isLength.js'
import isEmail from "validator/lib/isEmail.js"
import bcrypt from "bcryptjs";
import multer from "multer";

const upload = multer({ dest: 'uploads/' })

const profileUpload = upload.fields([
    {name: 'avatar', maxCount: 1},
    {name: 'gallery', maxCount: 10},
])

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()
        console.log(newUser)
        res.json(newUser)
    } catch (error) { 
        console.log(error)
        res.status(500).send('회원가입 에러')
    }
}

const update = async (req, res) => {
    try {
        const {name} = req.body
        console.log(req.files)
        const avatar = req.files['avatar'][0]
        const gallery = req.files['gallery']
        const user = req.profile
        user.avatarUrl = avatar.filename
        gallery.forEach(file => {
            user.galleryUrls.push(file.filename)
        });
        const updatedUser = await user.save()
        res.json(updatedUser)
    } catch (error) {
        console.log(error)
        res.status(500).send('프로파일 업데이트 실패')
    }
}

const getProfile = (req, res) => {
    res.json(req.profile)
}

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('사용자 아이디 검색 실패')
    }
}

export default { signup, profileUpload, update, getProfile, userById }