Skip to content

Commit

Permalink
Merge pull request #332 from chsch911028/develop
Browse files Browse the repository at this point in the history
Fix issue and Refactor
  • Loading branch information
chsch911028 authored Dec 20, 2019
2 parents 0841c70 + 597ab36 commit 05fda8f
Show file tree
Hide file tree
Showing 16 changed files with 201 additions and 121 deletions.
10 changes: 0 additions & 10 deletions auction-server/.env-example

This file was deleted.

12 changes: 12 additions & 0 deletions auction-server/.env.example
Original file line number Diff line number Diff line change
@@ -1,3 +1,15 @@
DB_TYPE=
DB_HOST=
DB_DOCKER_COMPOSE_SERVICE_HOST=
DB_PORT=
DB_USER=
DB_PASSWORD=
DB_NAME=

CHAT_SERVER=
CHAT_DEV_SERVER=


### Mail
MAIL_ID=
MAIL_PASSWORD=
Expand Down
4 changes: 2 additions & 2 deletions auction-server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ let queue = [];

//1분 반복 예시 "*/1 * * * *"
//[작업 할당 클론]
cron.schedule("*/10 * * * * *", () => {
cron.schedule("*/2 * * * * *", () => {
const now = moment().format("YYYY-MM-DD HH:mm:ss");
console.log(now);
pool.query(
Expand Down Expand Up @@ -87,7 +87,7 @@ cron.schedule("*/10 * * * * *", () => {
});

// [작업 처리 클론]
cron.schedule("*/10 * * * * *", () => {
cron.schedule("*/2 * * * * *", () => {
if (queue.length === 0) return console.log("QUEUE IS EMPTY");
console.dir(queue);
console.dir(queue.length);
Expand Down
74 changes: 44 additions & 30 deletions auction-server/mailService.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,26 @@
const axios = require("axios")
const axios = require("axios");

const mailTemplate = (isSeller, isSold, content) => `
<div>
<h3>세상의 모든 중고 경매 팔다 알림메일 입니다.</h3>
<span>${isSeller ? "등록하신" : "입찰하신"} ${content}
${
isSeller ? (isSold ? "판매되었" : "유찰되었") : isSold ? "낙찰되었" : "유찰되었"
}습니다.</span>
isSeller
? isSold
? "판매되었"
: "유찰되었"
: isSold
? "낙찰되었"
: "유찰되었"
}습니다.</span>
<div>팔다에 접속해 확인하시기 바랍니다.</div>
</div>
`
`;

const mailTitleTemplate = (isSeller, isSold) => {
if (isSeller) return `${isSold ? "판매" : "유찰"} 되었습니다.`
return `${isSold ? "낙찰" : "유찰"} 되었습니다.`
}
if (isSeller) return `${isSold ? "판매" : "유찰"} 되었습니다.`;
return `${isSold ? "낙찰" : "유찰"} 되었습니다.`;
};

const mailFooter = `
<a href="http://palda.shop" style="
Expand All @@ -33,66 +39,74 @@ const mailFooter = `
">중고 물건은 이곳 팔다에서!</h3>
<span>http://palda.shop</span>
</div>
</a>`
</a>`;

const user = {
id: process.env.MAIL_ID,
password: process.env.MAIL_PASSWORD
}
};

const mailService = (toEmail, content, isSeller, isSold) => {
if (!toEmail) return;
// text html 택1 (html이 우선순위 높음)
const mail = {
to: toEmail,
subject: `[팔다] 상품 ${content}이(가) ${mailTitleTemplate(isSeller, isSold)}`,
subject: `[팔다] 상품 ${content}이(가) ${mailTitleTemplate(
isSeller,
isSold
)}`,
html: mailTemplate(isSeller, isSold, content) + mailFooter
}
};

const instance = axios.create({
baseURL: process.env.MAIL_BASE,
headers: {
"content-type": "application/json",
Accept: "application/json"
}
})
});

let cookie = ""
let cookie = "";

const getCookie = async () => {
const response = await instance.post("/auth/login", user)
cookie = response.headers["set-cookie"][0]
}
const response = await instance.post("/auth/login", user);
cookie = response.headers["set-cookie"][0];
};

const sendMail = () =>
instance.post("/mail", mail, {
headers: {
Cookie: cookie
}
})
});

const run = async () => {
try {
await sendMail()
return true
await sendMail();
return true;
} catch (error) {
if (error.response.status !== 401) {
return error
return error;
}
}
await getCookie()
const result = await sendMail()
}
await getCookie();
const result = await sendMail();
};

run()
}
run();
};

const sendMail = (pool, userid, title, isSeller, isSold) => {
pool.query('select email from users where id = ?', [userid],
pool.query(
"select email from users where id = ?",
[userid],
(err, row, field) => {
if (!row) return;
mailService(row[0].email, title, isSeller, isSold)
})
}
if (!row[0]) return;
if (!row[0].email) return;
mailService(row[0].email, title, isSeller, isSold);
}
);
};

module.exports = { sendMail }
module.exports = { sendMail };
8 changes: 6 additions & 2 deletions chat-server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,13 +70,17 @@ io.on("connection", function(socket) {
userMapper[userId] = sessionId;
});

socket.on("leaveRoom", (roomId, sessionId, userId) => {
socket.on("leaveRoom", ({ roomId, sessionId, user }) => {
console.log(
`##### USER(${sessionId}, ${userId})가 ${roomId}방에서 나감 #####`
`##### USER(${sessionId}, ${user.id})가 ${roomId}방에서 나감 #####`
);
socket.leave(roomId, () => {
//rooms 정보에서 삭제한다.
delete rooms[roomId][sessionId];
});
});

socket.on("disconnect", () => {
console.log("DISCONNECTED");
});
});
21 changes: 13 additions & 8 deletions client/src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import ModalContext from "./context/ModalContext";
import { Modal } from "../src/components/Molecules/CustomModal/Modal";
import NotificationContext from "./context/NotificationContext";
import MessengerContext from "./context/MessengerContext";
import SocketContext from "./context/SocketContext";
import { useSocket } from "./hooks/useSocket";

function App() {
const [user, setUser] = useState({});
Expand All @@ -17,20 +19,23 @@ function App() {
});
const [notifications, setNotifications] = useState([]);
const [messengerOpen, setMessengerOpen] = useState(false);
const { socket } = useSocket(user, setNotifications);

return (
<BrowserRouter>
<MessengerContext.Provider value={[messengerOpen, setMessengerOpen]}>
<ModalContext.Provider value={[modal, setModal]}>
<UserContext.Provider value={[user, setUser]}>
<NotificationContext.Provider
value={[notifications, setNotifications]}
>
{modal.isOpen ? <Modal /> : null}
<div className="App">
<Router />
</div>
</NotificationContext.Provider>
<SocketContext.Provider value={{ socket }}>
<NotificationContext.Provider
value={[notifications, setNotifications]}
>
{modal.isOpen ? <Modal /> : null}
<div className="App">
<Router />
</div>
</NotificationContext.Provider>
</SocketContext.Provider>
</UserContext.Provider>
</ModalContext.Provider>
</MessengerContext.Provider>
Expand Down
2 changes: 1 addition & 1 deletion client/src/components/Molecules/CustomModal/Modal.jsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useContext } from "react";
import React, { useEffect, useContext } from "react";
import styled from "styled-components";
import ModalContext from "../../../context/ModalContext";

Expand Down
11 changes: 7 additions & 4 deletions client/src/components/Molecules/NotifyList/NotifyItem.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ const NotifyItemStyle = styled.div`

const NotifyBadge = styled.div`
width: 52px;
background: ${props => (props.success ? "var(--color-success)" : "var(--color-primary)")};
background: ${props =>
props.success ? "var(--color-success)" : "var(--color-primary)"};
padding: var(--padding-sm);
color: white;
font-weight: bold;
Expand All @@ -22,7 +23,9 @@ const NotifyContent = styled.div`
width: 100%;
display: flex;
border: 1px solid var(--color-gray);
/* border-color: ${props => (props.success ? "var(--color-success)" : "var(--color-primary)")}; */
background-color:white;
/* border-color: ${props =>
props.success ? "var(--color-success)" : "var(--color-primary)"}; */
`;

const NotifyLeftContent = styled.div`
Expand Down Expand Up @@ -84,9 +87,9 @@ export const NotifyItem = props => {
return (
<NotifyItemStyle>
{isSuccess(type) ? (
<NotifyBadge success>구매 성공</NotifyBadge>
<NotifyBadge success>성공</NotifyBadge>
) : (
<NotifyBadge>구매 실패</NotifyBadge>
<NotifyBadge>실패</NotifyBadge>
)}
<NotifyContent success>
<NotifyLeftContent>
Expand Down
2 changes: 1 addition & 1 deletion client/src/components/Molecules/NotifyList/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ function Component() {
{notifications.map(noti => {
return (
<NotifyItem
key={`${noti.product.id}${noti.product.title}`}
key={`${noti.type}${noti.product.id}${noti.product.title}`}
{...noti}
/>
);
Expand Down
2 changes: 1 addition & 1 deletion client/src/components/Molecules/ShareBox/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ const Component = ({ url, object, width }) => {
</Wrapper>
<CopyToClipboard text={url}>
<Wrapper>
<Logo src={URLLogo} />
<Logo src={URLLogo} onClick={() => alert("URL이 복사되었습니다.")} />
<Title>URL</Title>
</Wrapper>
</CopyToClipboard>
Expand Down
2 changes: 1 addition & 1 deletion client/src/components/Organism/Chat/Chat.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ const SellerIdText = styled.div`
`;
const MessageText = styled.div`
font-size: 0.8rem;
word-break: break-all;
word-break: break-word;
`;

const Chat = ({ chat, isSeller }) => {
Expand Down
20 changes: 15 additions & 5 deletions client/src/components/Organism/Chat/ChatBox.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import ChatSend from "./ChatSend";
import ModalContext from "../../../context/ModalContext";
import FailModal from "../../Molecules/CustomModal/FailModal";
import ProductPageContext from "../../../context/ProductPageContext";
import SocketContext from "../../../context/SocketContext";

const ChatBoxStyle = styled.div`
display: flex;
Expand Down Expand Up @@ -61,8 +62,9 @@ const ChatAlertWithPurchase = styled(ChatAlertWithBid)`

const ChatBox = ({ productId, sellerId, user }) => {
const chatBodyRef = useRef();
const { socket } = useContext(SocketContext);
const [productPageState] = useContext(ProductPageContext);
const { socketClient, chats } = productPageState;
const { chats } = productPageState;

const [modal, setModal] = useContext(ModalContext);

Expand All @@ -73,18 +75,22 @@ const ChatBox = ({ productId, sellerId, user }) => {
const onSubmit = e => {
e.preventDefault();

const text = e.target.message.value;

if (text === "" || text.trim() === "") return;

if (Object.keys(user).length === 0) {
return setModal({
isOpen: true,
component: FailModal,
props: { message: "로그인이 필요합니다." }
});
}
socketClient.emit("message", {
socket.emit("message", {
roomId: productId,
sender: { ...user, sessionId: socketClient.id },
sender: { ...user, sessionId: socket.id },
type: "message",
text: e.target.message.value,
text,
createdAt: Date.now()
});

Expand All @@ -98,7 +104,11 @@ const ChatBox = ({ productId, sellerId, user }) => {
<ChatBody ref={chatBodyRef}>
{chats.map(chat => {
return chat.type === "message" ? (
<Chat key={chat.key} chat={chat} isSeller={sellerId === chat.senderId} />
<Chat
key={chat.key}
chat={chat}
isSeller={sellerId === chat.senderId}
/>
) : (
<ChatAlert key={chat.key}>
{chat.type === "bid" ? (
Expand Down
Loading

0 comments on commit 05fda8f

Please sign in to comment.