diff --git a/src/DTO/adminDTO.ts b/src/DTO/adminDTO.ts index 3e78a34..94e5428 100644 --- a/src/DTO/adminDTO.ts +++ b/src/DTO/adminDTO.ts @@ -1,31 +1,18 @@ namespace adminDTO { - export interface IAdmin { - title: String; - registerStartDT: Date; - registerEndDT: Date; - challengeStartDT: Date; - challengeEndDT: Date; - generation: Number; - limitNum: Number; - img: string; - createdDT: Date; - applyNum: Number; - } - - interface Admin { + export interface adminResDetailDTO { registerStartDT: Date; registerEndDT: Date; challengeStartDT: Date; challengeEndDT: Date; generation: number; - createdDT: Date; + createdAT?: Date; applyNum: number; - participants: number; - postNum: number; - img: string; + participants?: number; + postNum?: number; + img?: string; } export interface adminResDTO { - offsetAdmin: Admin[]; + offsetAdmin: adminResDetailDTO[]; totalAdminNum?: number; } diff --git a/src/controller/admin.ts b/src/controller/admin.ts index ba375b6..4fbb54f 100644 --- a/src/controller/admin.ts +++ b/src/controller/admin.ts @@ -1,176 +1,198 @@ -import { Router, Request, Response } from "express"; +import { Request, Response } from "express"; // libraries -import { returnCode } from "../library/returnCode"; -import { response, dataResponse } from "../library/response"; -//middlewares -import auth from "../middleware/auth"; -const upload = require("../modules/upload"); -// interfaces -// import { IAdmin } from "../interfaces/IAdmin"; -// import { IConcert } from "../interfaces/IConcert"; -//services -import { - postAdminList, - postAdminChallenge, - postAdminConcert, - postAdminNotice, - getAdminRegist, -} from "../service/adminService"; - +import { response, returnCode } from "../library"; +// services +import { adminService } from "../service"; // DTO -import { - adminResDTO, - adminRegistReqDTO, - adminWriteReqDTO, - adminRegistResDTO, -} from "../DTO/adminDTO"; - -const router = Router(); +import { adminDTO, commentDTO } from "../DTO"; /** * @관리자_페이지_조회 - * @route Get admin + * @route Get /admin?offset=&limit= * @access private */ -router.get("/", auth, async (req: Request, res: Response) => { +const getAdminListController = async (req: Request, res: Response) => { try { - const data: adminResDTO | -1 | -2 = await postAdminList( - req.body.userID.id, - req.query.offset, - req.query.limit - ); + const resData: adminDTO.adminResDTO | -1 | -2 = + await adminService.getAdminList( + Number(req.body.userID.id), + Number(req.query.offset), + Number(req.query.limit) + ); // limit 없을 때 - if (data === -1) { - response(res, returnCode.BAD_REQUEST, "요청 값이 올바르지 않습니다"); + if (resData === -1) { + response.basicResponse( + res, + returnCode.BAD_REQUEST, + "요청 값이 올바르지 않습니다" + ); } // 유저 id가 관리자가 아님 - if (data === -2) { - response(res, returnCode.NOT_FOUND, "관리자 아이디가 아닙니다"); + else if (resData === -2) { + response.basicResponse( + res, + returnCode.NOT_FOUND, + "관리자 아이디가 아닙니다" + ); } // 관리자 챌린지 조회 성공 else { - dataResponse(res, returnCode.OK, "관리자 페이지 조회 성공", data); + response.dataResponse( + res, + returnCode.OK, + "관리자 페이지 조회 성공", + resData + ); } } catch (err) { console.error(err.message); - response(res, returnCode.INTERNAL_SERVER_ERROR, "서버 오류"); + response.basicResponse(res, returnCode.INTERNAL_SERVER_ERROR, "서버 오류"); } -}); +}; /** * @관리자_챌린지_등록 * @route Post admin/challenge * @access private */ -router.post( - "/challenge", - upload.fields([{ name: "img", maxCount: 1 }]), - auth, - - async (req: Request, res: Response) => { - try { - const url = { - img: (req as any).files.img - ? (req as any).files.img[0].location - : "https://o2-server.s3.ap-northeast-2.amazonaws.com/origin/default_img_100%403x.jpg", - }; - const reqData: adminRegistReqDTO = req.body; - const data = await postAdminChallenge(req.body.userID.id, reqData, url); - - // 요청 바디가 부족할 경우 - if (data === -1) { - response(res, returnCode.BAD_REQUEST, "요청 값이 올바르지 않습니다"); - } - // 유저 id가 관리자가 아님 - else if (data === -2) { - response(res, returnCode.NOT_FOUND, "관리자 아이디가 아닙니다"); - } - // 챌린지 기간이 신청 기간보다 빠른 경우 or 기간 입력이 잘못된 경우 - else if (data === -3) { - response(res, returnCode.BAD_REQUEST, "잘못된 기간을 입력하셨습니다"); - } - - // 관리자 챌린지 등록 성공 - else { - response(res, returnCode.OK, "관리자 챌린지 등록 성공"); - } - } catch (err) { - console.error(err.message); - response(res, returnCode.INTERNAL_SERVER_ERROR, "서버 오류"); + +const postAdminChallengeController = async (req: Request, res: Response) => { + try { + const url = { + img: (req as any).files.img + ? (req as any).files.img[0].location + : "https://o2-server.s3.ap-northeast-2.amazonaws.com/origin/default_img_100%403x.jpg", + }; + const reqData: adminDTO.adminRegistReqDTO = req.body; + const data = await adminService.postAdminChallenge( + req.body.userID.id, + reqData, + url + ); + + // 요청 바디가 부족할 경우 + if (data === -1) { + response.basicResponse( + res, + returnCode.BAD_REQUEST, + "요청 값이 올바르지 않습니다" + ); + } + // 유저 id가 관리자가 아님 + else if (data === -2) { + response.basicResponse( + res, + returnCode.NOT_FOUND, + "관리자 아이디가 아닙니다" + ); + } + // 챌린지 기간이 신청 기간보다 빠른 경우 or 기간 입력이 잘못된 경우 + else if (data === -3) { + response.basicResponse( + res, + returnCode.BAD_REQUEST, + "잘못된 기간을 입력하셨습니다" + ); } + + // 관리자 챌린지 등록 성공 + else { + response.basicResponse(res, returnCode.OK, "관리자 챌린지 등록 성공"); + } + } catch (err) { + console.error(err.message); + response.basicResponse(res, returnCode.INTERNAL_SERVER_ERROR, "서버 오류"); } -); +}; /** * @관리자_챌린지_신청페이지 * @route Get admin/regist - * @access private + * @access public */ -router.get("/regist", async (req: Request, res: Response) => { +const getAdminRegistController = async (req: Request, res: Response) => { try { - const data: adminRegistResDTO | -1 | -2 = await getAdminRegist(); + const resData: adminDTO.adminRegistResDTO | -1 | -2 = + await adminService.getAdminRegist(); // 현재 진행중인 기수가 없음 - if (data === -1) { - response(res, returnCode.BAD_REQUEST, "현재 신청 기간인 기수가 없습니다"); + if (resData === -1) { + response.basicResponse( + res, + returnCode.BAD_REQUEST, + "현재 신청 기간인 기수가 없습니다" + ); } // 챌린지 신청 페이지 조회 성공 else { - dataResponse(res, returnCode.OK, "신청 페이지 조회 성공", data); + response.dataResponse( + res, + returnCode.OK, + "신청 페이지 조회 성공", + resData + ); } } catch (err) { console.error(err.message); - response(res, returnCode.INTERNAL_SERVER_ERROR, "서버 오류"); + response.basicResponse(res, returnCode.INTERNAL_SERVER_ERROR, "서버 오류"); } -}); +}; /** - * @관리자_오픈콘서트_등록 + * @관리자_콘서트_등록 * @route Post admin/concert * @access private */ -router.post( - "/concert", - upload.fields([ - { name: "videoLink", maxCount: 1 }, - { name: "imgThumbnail", maxCount: 1 }, - ]), - auth, - async (req: Request, res: Response) => { - try { - const url = { - videoLink: (req as any).files.videoLink - ? (req as any).files.videoLink[0].location - : "", - imgThumbnail: (req as any).files.imgThumbnail - ? (req as any).files.imgThumbnail[0].location - : "https://o2-server.s3.ap-northeast-2.amazonaws.com/origin/default_img_100%403x.jpg", - }; - const reqData: adminWriteReqDTO = req.body; - const data = await postAdminConcert(req.body.userID.id, reqData, url); - - // 요청 바디가 부족할 경우 - if (data === -1) { - response(res, returnCode.BAD_REQUEST, "요청 값이 올바르지 않습니다"); - } - // 유저 id가 관리자가 아님 - else if (data === -2) { - response(res, returnCode.BAD_REQUEST, "관리자 아이디가 아닙니다"); - } - - // 관리자 챌린지 등록 성공 - else { - response(res, returnCode.OK, "관리자 오투콘서트 등록 성공"); - } - } catch (err) { - console.error(err.message); - response(res, returnCode.INTERNAL_SERVER_ERROR, "서버 오류"); +const postAdminConcertController = async (req: Request, res: Response) => { + try { + const url = { + videoLink: (req as any).files.videoLink + ? (req as any).files.videoLink[0].location + : "", + imgThumbnail: (req as any).files.imgThumbnail + ? (req as any).files.imgThumbnail[0].location + : "https://o2-server.s3.ap-northeast-2.amazonaws.com/origin/default_img_100%403x.jpg", + }; + const reqData: adminDTO.adminWriteReqDTO = req.body; + const resData = await adminService.postAdminConcert( + Number(req.body.userID.id), + reqData, + url + ); + + // 요청 바디가 부족할 경우 + if (resData === -1) { + response.basicResponse( + res, + returnCode.BAD_REQUEST, + "요청 값이 올바르지 않습니다" + ); + } + // 유저 id가 관리자가 아님 + else if (resData === -2) { + response.basicResponse( + res, + returnCode.BAD_REQUEST, + "관리자 아이디가 아닙니다" + ); + } + + // 관리자 챌린지 등록 성공 + else { + response.basicResponse( + res, + returnCode.CREATED, + "관리자 오투콘서트 등록 성공" + ); } + } catch (err) { + console.error(err.message); + response.basicResponse(res, returnCode.INTERNAL_SERVER_ERROR, "서버 오류"); } -); +}; /** * @관리자_공지사항_등록 @@ -178,50 +200,60 @@ router.post( * @access private */ -router.post( - "/notice", - upload.fields([ - { name: "videoLink", maxCount: 1 }, - { name: "imgThumbnail", maxCount: 1 }, - ]), - auth, - async (req: Request, res: Response) => { - try { - const url = { - videoLink: (req as any).files.videoLink - ? (req as any).files.videoLink[0].location - : "", - imgThumbnail: (req as any).files.imgThumbnail - ? (req as any).files.imgThumbnail[0].location - : "https://o2-server.s3.ap-northeast-2.amazonaws.com/origin/default_img_100%403x.jpg", - }; - - const reqData: adminWriteReqDTO = req.body; - const data = await postAdminNotice( - req.body.userID.id, - reqData, - // JSON.parse(req.body.json), - url +const postAdminNoticeController = async (req: Request, res: Response) => { + try { + const url = { + videoLink: (req as any).files.videoLink + ? (req as any).files.videoLink[0].location + : "", + imgThumbnail: (req as any).files.imgThumbnail + ? (req as any).files.imgThumbnail[0].location + : "https://o2-server.s3.ap-northeast-2.amazonaws.com/origin/default_img_100%403x.jpg", + }; + + const reqData: adminDTO.adminWriteReqDTO = req.body; + const data = await adminService.postAdminNotice( + Number(req.body.userID.id), + reqData, + url + ); + + // 요청 바디가 부족할 경우 + if (data === -1) { + response.basicResponse( + res, + returnCode.BAD_REQUEST, + "요청 값이 올바르지 않습니다" + ); + } + // 유저 id가 관리자가 아님 + else if (data === -2) { + response.basicResponse( + res, + returnCode.BAD_REQUEST, + "관리자 아이디가 아닙니다" ); + } - // 요청 바디가 부족할 경우 - if (data === -1) { - response(res, returnCode.BAD_REQUEST, "요청 값이 올바르지 않습니다"); - } - // 유저 id가 관리자가 아님 - else if (data === -2) { - response(res, returnCode.BAD_REQUEST, "관리자 아이디가 아닙니다"); - } - - // 관리자 공지사항 등록 성공 - else { - response(res, returnCode.OK, "관리자 공지사항 등록 성공"); - } - } catch (err) { - console.error(err.message); - response(res, returnCode.INTERNAL_SERVER_ERROR, "서버 오류"); + // 관리자 공지사항 등록 성공 + else { + response.basicResponse( + res, + returnCode.CREATED, + "관리자 공지사항 등록 성공" + ); } + } catch (err) { + console.error(err.message); + response.basicResponse(res, returnCode.INTERNAL_SERVER_ERROR, "서버 오류"); } -); +}; -module.exports = router; +const adminController = { + getAdminListController, + getAdminRegistController, + postAdminConcertController, + postAdminNoticeController, + postAdminChallengeController, +}; +export default adminController; diff --git a/src/controller/index.ts b/src/controller/index.ts index 15fb849..2e50384 100644 --- a/src/controller/index.ts +++ b/src/controller/index.ts @@ -2,3 +2,4 @@ export { default as authController } from "./auth"; export { default as userController } from "./user"; export { default as challengeController } from "./challenge"; export { default as concertController } from "./concert"; +export { default as adminController } from "./admin"; diff --git a/src/library/array.ts b/src/library/array.ts index a23d2fc..c833e41 100644 --- a/src/library/array.ts +++ b/src/library/array.ts @@ -22,9 +22,23 @@ function stringToArray(str: String) { return resultArr; } +function stringToHashtag(str: String) { + let arrayStr = str + .replace("[", "#") + .replace("]", "") + .replace(/,/gi, ",#") + .replace(/"/gi, ""); + return arrayStr; +} +function stringToInterest(str: String) { + let arrayStr = str.replace("[", "").replace("]", "").replace(/"/gi, ""); + return arrayStr; +} const array = { stringToArray, + stringToHashtag, + stringToInterest, }; export default array; diff --git a/src/models/Concert.ts b/src/models/Concert.ts index f59cd6e..d86d09e 100644 --- a/src/models/Concert.ts +++ b/src/models/Concert.ts @@ -46,7 +46,6 @@ export default class Concert extends Model { @Column text!: string; - @Unique @Column authorNickname: string; diff --git a/src/router/admin.ts b/src/router/admin.ts index e69de29..a72b453 100644 --- a/src/router/admin.ts +++ b/src/router/admin.ts @@ -0,0 +1,43 @@ +import { Router } from "express"; +// controller +import { adminController } from "../controller"; +// middleware +import { authMiddleware, publicAuthMiddleware } from "../middleware"; +const upload = require("../modules/upload"); + +const router = Router(); + +router.get("/", authMiddleware, adminController.getAdminListController); +router.get( + "/regist", + publicAuthMiddleware, + adminController.getAdminRegistController +); + +router.post( + "/concert", + upload.fields([ + { name: "videoLink", maxCount: 1 }, + { name: "imgThumbnail", maxCount: 1 }, + ]), + authMiddleware, + adminController.postAdminConcertController +); + +router.post( + "/notice", + upload.fields([ + { name: "videoLink", maxCount: 1 }, + { name: "imgThumbnail", maxCount: 1 }, + ]), + authMiddleware, + adminController.postAdminNoticeController +); +router.post( + "/challenge", + upload.fields([{ name: "img", maxCount: 1 }]), + authMiddleware, + adminController.postAdminChallengeController +); + +export default router; diff --git a/src/router/concert.ts b/src/router/concert.ts index e7c1304..2827ecb 100644 --- a/src/router/concert.ts +++ b/src/router/concert.ts @@ -1,6 +1,6 @@ import { Router } from "express"; // controller -import { challengeController, concertController } from "../controller"; +import { concertController } from "../controller"; // middleware import { authMiddleware, publicAuthMiddleware } from "../middleware"; diff --git a/src/router/index.ts b/src/router/index.ts index 8acec8b..2c1a42d 100644 --- a/src/router/index.ts +++ b/src/router/index.ts @@ -4,6 +4,7 @@ import authRouter from "./auth"; import userRouter from "./user"; import challengeRouter from "./challenge"; import concertRouter from "./concert"; +import adminRouter from "./admin"; const router = express.Router(); @@ -11,5 +12,6 @@ router.use("/auth", authRouter); router.use("/user", userRouter); router.use("/challenge", challengeRouter); router.use("/concert", concertRouter); +router.use("/admin", adminRouter); export default router; diff --git a/src/service/adminService.ts b/src/service/adminService.ts index 5c75587..eea232a 100644 --- a/src/service/adminService.ts +++ b/src/service/adminService.ts @@ -1,98 +1,111 @@ -// models -import Admin from "../models/Admin"; -import User from "../models/User"; -import Concert from "../models/Concert"; +import sequelize, { Op } from "sequelize"; -// library -import { stringToDate, stringToEndDate } from "../library/date"; -import Challenge from "../models/Challenge"; -import { stringToArray } from "../library/array"; +// models +import { + Badge, + Concert, + Comment, + Like, + Post, + Challenge, + User, + Admin, +} from "../models"; // DTO -import { - adminResDTO, - adminRegistReqDTO, - adminWriteReqDTO, - adminRegistResDTO, -} from "../DTO/adminDTO"; +import { adminDTO } from "../DTO"; + +// library +import { array, date } from "../library"; /** * @관리자_페이지_조회 - * @route Get admin + * @route Get /admin?offset=&limit= * @body * @error * 1. 유저 id가 관리자가 아님 */ -export const postAdminList = async (userID, offset, limit) => { +export const getAdminList = async ( + userID: number, + offset: number, + limit: number +) => { + // isDelete = true 인 애들만 가져오기 + // offset 뒤에서 부터 가져오기 + // 최신순으로 정렬 + // 댓글, 답글 최신순으로 정렬 if (!offset) { offset = 0; } + // 1. 요청 부족 if (!limit) { return -1; } - // 1. 유저 id가 관리자가 아님 - let user = await User.findById(userID); - if (!(user.userType === 1)) { + // 2. 유저 id가 관리자가 아님 + const user = await User.findOne({ + where: { id: userID }, + attributes: ["isAdmin", "nickName"], + }); + if (user.isAdmin === false) { return -2; } - const admins = await Admin.find( - {}, - { - _id: false, - title: false, - limitNum: false, - __v: false, - } - ).sort({ generation: -1 }); + const admins: adminDTO.adminResDetailDTO[] = await Admin.findAll({ + order: [["generation", "DESC"]], + limit, + offset, + }); const adminList = await Promise.all( - admins.map(async function (admin) { - let totalNum = await Challenge.aggregate([ - { - $match: { generation: admin.generation }, - }, - { - $group: { - _id: "$user", - // 참여 인원 - total: { $sum: 1 }, + admins.map(async (admin) => { + // 해당 기수 글 작성자 + const participantList = await Post.findAll({ + where: { generation: admin.generation }, + include: [ + { + model: Challenge, + required: true, + }, + ], + attributes: [[sequelize.fn("count", sequelize.col("userID")), "count"]], + }); + + // 해당 기수 글 개수 + const postNum = await Post.findAll({ + where: { generation: admin.generation }, + include: [ + { + model: Challenge, + required: true, }, - }, - { $project: { _id: 0 } }, - ]); - let participants = 0; - if (totalNum[0]) { - participants = totalNum[0]["total"]; - } - const admintemp = { + ], + }); + + let returnData: adminDTO.adminResDetailDTO = { registerStartDT: admin.registerStartDT, registerEndDT: admin.registerEndDT, challengeStartDT: admin.challengeStartDT, challengeEndDT: admin.challengeEndDT, generation: admin.generation, - createdDT: admin.createdDT, - // 신청 인원 + createdAT: admin.createdAT, applyNum: admin.applyNum, - // 참여 인원 - participants, - postNum: await Challenge.find({ generation: admin.generation }).count(), + participants: participantList.length, + postNum: postNum.length, img: admin.img, }; - return admintemp; + + return returnData; }) ); - var offsetAdmin = []; - for (var i = Number(offset); i < Number(offset) + Number(limit); i++) { - offsetAdmin.push(adminList[i]); - } - const resData: adminResDTO = { - offsetAdmin, - totalAdminNum: adminList.length, + const totalAdmin = await Admin.findAll(); + + const resData: adminDTO.adminResDTO = { + offsetAdmin: adminList, + totalAdminNum: totalAdmin.length, }; return resData; @@ -102,14 +115,15 @@ export const postAdminList = async (userID, offset, limit) => { * @관리자_챌린지_등록 * @route Post admin/challenge * @body registerStartDT, registerEndDT, challengeStartDT, challengeEndDT, limitNum, img + * @access private * @error * 1. 요청 바디 부족 * 2. 유저 id가 관리자가 아님 * 3. 챌린지 기간이 잘못됨 */ export const postAdminChallenge = async ( - userID, - reqData: adminRegistReqDTO, + userID: number, + reqData: adminDTO.adminRegistReqDTO, url ) => { const img = url.img; @@ -135,30 +149,25 @@ export const postAdminChallenge = async ( } // 2. 유저 id가 관리자가 아님 - let user = await User.findById(userID); - if (!(user.userType === 1)) { + const user = await User.findOne({ + where: { id: userID }, + attributes: ["isAdmin", "nickName"], + }); + if (user.isAdmin === false) { return -2; } - /* - var = new Date('2020-10-23'); - var date2 = new Date('2020-10-22'); - - console.log(date1 > date2); // true - */ - //기수 증가 - const changeGen = (await Admin.find().count()) + 1; - const admin = new Admin({ + const changeGen = (await (await Admin.findAll()).length) + 1; + await Admin.create({ title, - registerStartDT: stringToDate(registerStartDT), - registerEndDT: stringToEndDate(registerEndDT), - challengeStartDT: stringToDate(challengeStartDT), - challengeEndDT: stringToEndDate(challengeEndDT), + registerStartDT: date.stringToDate(registerStartDT), + registerEndDT: date.stringToEndDate(registerEndDT), + challengeStartDT: date.stringToDate(challengeStartDT), + challengeEndDT: date.stringToEndDate(challengeEndDT), generation: changeGen, limitNum, img, - createdAt: new Date(), }); // 3. 챌린지 기간이 잘못됨 // 신청 마감날짜가 신청 시작 날짜보다 빠름 @@ -173,23 +182,24 @@ export const postAdminChallenge = async ( else if (challengeStartDT < registerEndDT) { return -3; } - await admin.save(); - return; + return 1; }; /** * @관리자_챌린지_신청페이지 * @route Get admin/regist - * @access private + * @access public */ export const getAdminRegist = async () => { // 신청 기간을 확인 현재 진행중인 기수를 가져옴 let dateNow = new Date(); const admin = await Admin.findOne({ - $and: [ - { registerStartDT: { $lte: dateNow } }, - { registerEndDT: { $gte: dateNow } }, - ], + where: { + [sequelize.Op.and]: { + registerStartDT: { [sequelize.Op.lte]: dateNow }, + registerEndDT: { [sequelize.Op.gte]: dateNow }, + }, + }, }); // 현재 진행중인 기수가 없음 @@ -197,7 +207,7 @@ export const getAdminRegist = async () => { return -1; } - const resData: adminRegistResDTO = { + const resData: adminDTO.adminRegistResDTO = { img: admin.img, title: admin.title, registerStartDT: admin.registerStartDT, @@ -211,9 +221,9 @@ export const getAdminRegist = async () => { }; /** - * @관리자_오투콘서트_등록 + * @관리자_콘서트_등록 * @route Post admin/concert - * @body createdAt, title, videoLink, text, interest, hashtag, authorNickname + * @access private * @error * 1. 요청 바디 부족 * 2. 유저 id가 관리자가 아님 @@ -221,21 +231,13 @@ export const getAdminRegist = async () => { */ export const postAdminConcert = async ( - userID, - reqData: adminWriteReqDTO, - url + userID: number, + reqData: adminDTO.adminWriteReqDTO, + url: any ) => { const { title, text, authorNickname } = reqData; - let interest = stringToArray(reqData.interest); - // .toLowerCase() - // .slice(1, -1) - // .replace(/"/gi, "") - // .split(/,\s?/); - let hashtag = stringToArray(reqData.hashtag); - // .toLowerCase() - // .slice(1, -1) - // .replace(/"/gi, "") - // .split(/,\s?/); + let interest = array.stringToInterest(reqData.interest); + let hashtag = array.stringToHashtag(reqData.hashtag); // 1. 요청 바디 부족 if (!title || !text || !interest || !hashtag || !authorNickname) { @@ -243,33 +245,51 @@ export const postAdminConcert = async ( } // 2. 유저 id가 관리자가 아님 - let user = await User.findById(userID); - if (!(user.userType === 1)) { + const user = await User.findOne({ + where: { id: userID }, + attributes: ["isAdmin", "nickName"], + }); + if (user.isAdmin === false) { return -2; } - const authorUser = await User.findOne({ nickname: authorNickname }); - var authorID; + // 해당 닉네임을 가진 유저를 찾음 + const authorUser = await User.findOne({ + where: { nickname: authorNickname }, + }); + + // 원글 작성자 아이디 + let authorID; + + // 해당 닉네임을 가진 유저가 있음 if (authorUser) { - authorID = authorUser._id; + // 해당 닉네임을 가진 유저의 id를 넣음 + authorID = authorUser.id; } else { + // 해당 닉네임을 가진 유저가 없음 + // 아이디는 관리자 아이디를 사용, 닉네임은 그 자체(authorNickname)를 사용 authorID = userID; } - const concert = new Concert({ - title: title.toLowerCase(), - user: authorID, - createdAt: new Date(), + + // Concert 등록 + const newPost = await Post.create({ + userID, + interest, + }); + + await Concert.create({ + id: newPost.id, + userID: authorID, + title, videoLink: url.videoLink, imgThumbnail: url.imgThumbnail, - text: text.toLowerCase(), - interest, - hashtag, + text, + isNotice: false, authorNickname, + hashtag, }); - await concert.save(); - - return; + return 1; }; /** @@ -281,26 +301,15 @@ export const postAdminConcert = async ( * 2. 유저 id가 관리자가 아님 */ -export const postAdminNotice = async (userID, reqData, url) => { +export const postAdminNotice = async ( + userID: number, + reqData: adminDTO.adminWriteReqDTO, + url: any +) => { const { title, text } = reqData; - let interest; - if (reqData.interest) { - interest = stringToArray(reqData.interest); - // .toLowerCase() - // .slice(1, -1) - // .replace(/"/gi, "") - // .split(/,\s?/); - } - - let hashtag; - if (reqData.hashtag) { - hashtag = stringToArray(reqData.hashtag); - // .toLowerCase() - // .slice(1, -1) - // .replace(/"/gi, "") - // .split(/,\s?/); - } + let interest = array.stringToInterest(reqData.interest); + let hashtag = array.stringToHashtag(reqData.hashtag); // 1. 요청 바디 부족 if (!title || !text) { @@ -308,23 +317,39 @@ export const postAdminNotice = async (userID, reqData, url) => { } // 2. 유저 id가 관리자가 아님 - let user = await User.findById(userID); - if (!(user.userType === 1)) { + const user = await User.findOne({ + where: { id: userID }, + attributes: ["isAdmin", "nickName"], + }); + if (user.isAdmin === false) { return -2; } - const notice = new Concert({ - title: title.toLowerCase(), + // Notice 등록 + const newPost = await Post.create({ + userID, interest, - user: userID, - isNotice: true, + }); + + await Concert.create({ + id: newPost.id, + userID, + title, videoLink: url.videoLink, imgThumbnail: url.imgThumbnail, - text: text.toLowerCase(), + text, + isNotice: true, hashtag, }); - await notice.save(); + return 1; +}; - return; +const adminService = { + getAdminList, + getAdminRegist, + postAdminConcert, + postAdminNotice, + postAdminChallenge, }; +export default adminService; diff --git a/src/service/authService.ts b/src/service/authService.ts index 146772e..664d36e 100644 --- a/src/service/authService.ts +++ b/src/service/authService.ts @@ -1,5 +1,5 @@ // models -import { User, UserInterest, Badge, Admin } from "../models"; +import { User, Badge, Admin } from "../models"; // DTO import { authDTO } from "../DTO"; // library diff --git a/src/service/concertService.ts b/src/service/concertService.ts index 25c55bd..4915828 100644 --- a/src/service/concertService.ts +++ b/src/service/concertService.ts @@ -135,7 +135,13 @@ export const getConcertAll = async ( return returnData; }); - const totalConcertNum = concertList.length; + + const totalConcertNum = await Post.count({ + where: { + isDeleted: false, + }, + include: [{ model: Concert, required: true, where: { isNotice: false } }], + }); const resData: concertDTO.concertAllResDTO = { concerts, totalConcertNum, @@ -403,7 +409,10 @@ export const getConcertSearch = async ( return returnData; }); - const totalConcertNum = concertList.length; + const totalConcertNum = await Post.count({ + where, + include: [{ model: Concert, required: true, where: { isNotice: false } }], + }); const resData: concertDTO.concertAllResDTO = { concerts, totalConcertNum, @@ -576,7 +585,7 @@ export const deleteConcertLike = async (concertID: number, userID: number) => { }, include: [ { model: Concert, required: true, where: { isNotice: false } }, - Like, + { model: Like, as: "likes", required: false }, ], }); @@ -599,7 +608,7 @@ export const deleteConcertLike = async (concertID: number, userID: number) => { /** * @오투콘서트_스크랩하기 - * @route Post /user/concert/:concertID + * @route Post /concert/:concertID/scrap * @access private * @error * 1. 콘서트 id 잘못됨 diff --git a/src/service/index.ts b/src/service/index.ts index d87acdb..e797658 100644 --- a/src/service/index.ts +++ b/src/service/index.ts @@ -2,3 +2,4 @@ export { default as authService } from "./authService"; export { default as userService } from "./userService"; export { default as challengeService } from "./challengeService"; export { default as concertService } from "./concertService"; +export { default as adminService } from "./adminService";