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 }