Skip to content
This repository has been archived by the owner on Oct 31, 2022. It is now read-only.

Commit

Permalink
Fix: 이모티콘 업로드 api 리팩토링
Browse files Browse the repository at this point in the history
  • Loading branch information
leehj050211 committed Mar 19, 2022
1 parent 8723795 commit cd7375b
Show file tree
Hide file tree
Showing 4 changed files with 145 additions and 108 deletions.
6 changes: 3 additions & 3 deletions src/api/api.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,8 +96,8 @@ router.post('/like/:boardType/:postNo', likeController.like)

router.post('/imageUpload', loginCheck, imageUpload.single('file'), imageUploadController.upload)

router.get('/emoticon/:id', loginCheck, emoticonController.getemoticon)
router.get('/emoticon', loginCheck, emoticonController.getemoticons)
router.post('/emoticon', loginCheck, emoticonController.uploadProcessing.fields([{name:'file'},{name:'files'}]), emoticonController.uploadCheck)
router.get('/emoticon/:id', emoticonController.getemoticon)
router.get('/emoticon', emoticonController.getemoticons)
router.post('/emoticon', emoticonController.uploadProcessing.fields([{name:'file'},{name:'files'}]), emoticonController.uploadEmoticon)

module.exports = router
86 changes: 20 additions & 66 deletions src/api/board/emoticon.controller.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
const jwt = require('../../util/jwt')
const service = require('./emoticon.service')
const multer = require('multer')
const fs = require('fs');
const jwt = require('../../util/jwt');
const service = require('./emoticon.service');
const multer = require('multer');

let result, dbResult;
const getemoticon = async (req, res, next) => {
try{
res.send(JSON.stringify(
Expand All @@ -13,6 +11,7 @@ const getemoticon = async (req, res, next) => {
next(err);
}
}

const getemoticons = async (req, res, next) => {
try{
res.send(JSON.stringify(
Expand All @@ -22,6 +21,7 @@ const getemoticons = async (req, res, next) => {
next(err);
}
}

const uploadProcessing = multer({
fileFilter:(req, file, cb) => {
// 파일 확장자 체크
Expand Down Expand Up @@ -56,72 +56,26 @@ const uploadProcessing = multer({
}
})
})
const uploadCheck = async (req, res) => {
const uploadEmoticon = async (req, res, next) => {
const jwtValue = jwt.check(req.cookies.token);
if(!jwtValue.isLogin){res.send(JSON.stringify(jwtValue.msg));return;}

// 업로드 데이터 체크
if(!req.body.name || !req.body.description || !req.files.file || !req.files.files || !req.body.emoticons){res.send(JSON.stringify({status:3,subStatus:0}));return;}
if(req.body.name.length<2){res.send(JSON.stringify({status:3,subStatus:0}));return;}
if(req.body.description.length<2){res.send(JSON.stringify({status:3,subStatus:0}));return;}
if(req.files.files.length<4){res.send(JSON.stringify({status:3,subStatus:0}));return;}
req.body.emoticons = JSON.parse(req.body.emoticons)
if(req.files.files.length != (Object.keys(req.body.emoticons).length)){res.send(JSON.stringify({status:3,subStatus:0}));return;}
let emoticonList = []
for(let i=0;i<req.files.files.length;i++){
const e = req.files.files[i];
if(!req.body.emoticons[e.name]){res.send(JSON.stringify({status:3,subStatus:0}));return;}
// 같은 확장자인지, 번호가 숫자가 맞는지 체크
if(e.ext != req.body.emoticons[e.name].type || !(/^\d+$/.test(req.body.emoticons[e.name].idx))){
res.send(JSON.stringify({status:3,subStatus:0}));
return;
}
emoticonList.push({
idx:req.body.emoticons[e.name].idx,
type:req.body.emoticons[e.name].type
});
}

// 이모티콘 정보 db에 저장
dbResult = await service.uploadEmoticonInfo(req.body.name, req.body.description, jwtValue.memberCode)
if(!dbResult){
res.send(JSON.stringify({status:2,subStatus:0}));return;
}else{
req.body.id=dbResult;
}
// 폴더 생성
try{
await fs.promises.mkdir(`public/resource/board/emoticon/${req.body.id}`)
}catch(err){
console.error(err)
res.send(JSON.stringify({status:2,subStatus:0}));return;
}
try{
// 복사할 파일 리스트 생성
let copyList = []
copyList = req.files.files.map(e=>{
return fs.promises.copyFile(e.path, `public/resource/board/emoticon/${req.body.id}/${req.body.emoticons[e.name].idx}.${req.body.emoticons[e.name].type}`)
})
copyList.push(fs.promises.copyFile(req.files.file[0].path, `public/resource/board/emoticon/${req.body.id}.png`))
// 파일 복사 프로미스
await Promise.all(copyList);
}catch(err){
console.error(err)
res.send(JSON.stringify({status:2,subStatus:0}));return;
}
try{
// 이모티콘들 db에 저장
await service.uploadEmoticons(req.body.id, emoticonList);
res.send(JSON.stringify(
await service.uploadEmoticon(
jwtValue.isLogin? jwtValue.memberCode: null,
req.body.name,
req.body.description,
JSON.parse(req.body.emoticons),
req.files
)
));
}catch(err){
console.error(err)
res.send(JSON.stringify({status:2,subStatus:0}));return;
next(err);
}
res.send(JSON.stringify({status:1,subStatus:0}));return;
}

module.exports = {
getemoticon:getemoticon,
getemoticons:getemoticons,
uploadProcessing:uploadProcessing,
uploadCheck:uploadCheck
getemoticon,
getemoticons,
uploadProcessing,
uploadEmoticon
}
106 changes: 68 additions & 38 deletions src/api/board/emoticon.service.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const { NotFoundException } = require('../../util/exceptions');
const { NotFoundException, InternalServerException, UnAuthorizedException, BadRequestException } = require('../../util/exceptions');
const emoticonRepository = require('./repository/emoticon.repository');
const fs = require('fs');

const getemoticon = async (id) => {
const emoticonInfo = await emoticonRepository.getEmoticonById(id);
Expand Down Expand Up @@ -62,48 +63,77 @@ const getemoticons = async () => {
}
}

const uploadEmoticonInfo = async (name, description, memberCode) => {
let rows
const getIndexQuery = `
SELECT AUTO_INCREMENT
FROM information_schema.tables
WHERE table_name = 'emoticon'
AND table_schema = DATABASE()`
try{
[rows] = await pool.query(getIndexQuery)
}catch(err) {
console.error(err)
return null;
const uploadEmoticon = async (memberCode, name, description, emoticons, files) => {
if (memberCode === null) {
throw new UnAuthorizedException();
}
const insertEmoticonsQuery = "INSERT INTO emoticon values(?, ?, ?, now(), ?)"
try{
pool.query(insertEmoticonsQuery, [rows[0].AUTO_INCREMENT, name, description, memberCode])
}catch(err) {
console.error(err)
return null;
// 업로드 데이터 체크
if (!name || !description || !files.file || !files.files || !emoticons) {
throw new BadRequestException();
}
return rows[0].AUTO_INCREMENT
}
const uploadEmoticons = (id, emoticonList) => {
let temp = []
let params = []
// 한 번에 insert 하기 위해
emoticonList.forEach(e => {
params.push(id, e.idx, e.type);
temp.push('(?,?,?)')
});
const insertEmoticonsQuery = `INSERT INTO emoticons values ${temp.join(',')}`;
if (name.length < 2) {
throw new BadRequestException();
}
if (description.length < 2) {
throw new BadRequestException();
}
if (files.files.length < 4) {
throw new BadRequestException();
}

if (files.files.length !== (Object.keys(emoticons).length)) {
throw new BadRequestException();
}
let emoticonList = [];
for (let i=0; i<files.files.length; i++){
const e = files.files[i];
if (!emoticons[e.name]) {
throw new BadRequestException();
}
// 같은 확장자인지, 번호가 숫자가 맞는지 체크
if (e.ext != emoticons[e.name].type || !(/^\d+$/.test(emoticons[e.name].idx))) {
throw new BadRequestException();
}
emoticonList.push({
idx:emoticons[e.name].idx,
type:emoticons[e.name].type
});
}

const emoticonId = await emoticonRepository.getAutoIncrement();
if (emoticonId === null) {
console.error('Emoticon get AUTO_INCREMENT error');
throw new InternalServerException();
}

// 이모티콘 정보 저장 및 폴더 생성
try {
await Promise.all([
emoticonRepository.insertEmoticonInfo(emoticonId, name, description, memberCode),
emoticonRepository.insertEmoticons(emoticonId, emoticonList),
fs.promises.mkdir(`public/resource/board/emoticon/${emoticonId}`)
])
} catch (err) {
console.error(err);
throw new InternalServerException();
}

try{
pool.query(insertEmoticonsQuery, params)
}catch(err) {
// 복사할 파일 리스트 생성
let copyList = [];
copyList = files.files.map(e=>{
return fs.promises.copyFile(e.path, `public/resource/board/emoticon/${emoticonId}/${emoticons[e.name].idx}.${emoticons[e.name].type}`)
})
copyList.push(fs.promises.copyFile(files.file[0].path, `public/resource/board/emoticon/${emoticonId}.png`))
// 파일 복사 프로미스
await Promise.all(copyList);
}catch(err){
console.error(err)
return null;
throw new InternalServerException();
}
return true
}
module.exports = {
getemoticon:getemoticon,
getemoticons:getemoticons,
uploadEmoticonInfo:uploadEmoticonInfo,
uploadEmoticons:uploadEmoticons
getemoticon,
getemoticons,
uploadEmoticon
}
55 changes: 54 additions & 1 deletion src/api/board/repository/emoticon.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,62 @@ const getEmoticonsById = async (id: number) => {
}
}

const getAutoIncrement = async () => {
const getAutoIncrementQuery=`
SELECT AUTO_INCREMENT
FROM information_schema.tables
WHERE table_name = 'emoticon'
AND table_schema = DATABASE()`;
try{
const [rows] = await pool.query(getAutoIncrementQuery);
if(rows.length)
return rows[0].AUTO_INCREMENT;
else
return null;
}catch(err){
console.error(err);
throw new InternalServerException();
}
}

const insertEmoticonInfo = async (id: number, name: string, description: string, memberCode: number) => {
const insertInfoQuery="INSERT INTO emoticon values(?, ?, ?, now(), ?)";
try{
await pool.query(insertInfoQuery, [id, name, description, memberCode]);
}catch(err){
console.error(err);
throw new InternalServerException();
}
}

const insertEmoticons = async (
id: number,
emoticonList: {
idx: number,
type: string
}[]
) => {
let temp: string[] = [];
let params: (number | string)[] = [];
// 한 번에 insert 하기 위해
emoticonList.forEach(e => {
params.push(id, e.idx, e.type);
temp.push('(?,?,?)');
});
const insertEmoticonsQuery = `INSERT INTO emoticons VALUES ${temp.join(',')}`;
try{
await pool.query(insertEmoticonsQuery, params);
}catch(err) {
console.error(err)
throw new InternalServerException();
}
}
export {
getEmoticon,
getEmoticonById,
getEmoticons,
getEmoticonsById
getEmoticonsById,
getAutoIncrement,
insertEmoticonInfo,
insertEmoticons
}

0 comments on commit cd7375b

Please sign in to comment.