code stringlengths 41 34.3k | lang stringclasses 8
values | review stringlengths 1 4.74k |
|---|---|---|
@@ -0,0 +1,13 @@
+const express = require('express');
+const router = express.Router();
+const middleware = require('../middlewares');
+const { userController } = require('../controllers');
+// Route ๋ ์ค์ง Controller ์๋ง ์์กด ํฉ๋๋ค.
+
+router.post(
+ '/signup',
+ [middleware.validateSignUpUserData, middleware.hashPassword],
+ userController.signUp,
+);
+
+module.exports = router; | JavaScript | convention ์์ ํ๋ ค๋ค๊ฐ ๋์น๊ฒ ๊ฐ์ต๋๋ค... ๊ด๋ จ๋ ๋ถ๋ถ ๋ชจ๋ ์์ ํ๊ณ ํ์๊ฐ์
๋ ํ์ธํ์ต๋๋ค! |
@@ -0,0 +1,40 @@
+// Controller๋ ์ค์ง Service ๋ ์ด์ด์๋ง ์์กดํฉ๋๋ค.
+const { userService } = require('../services');
+const { errorGenerator } = require('../erros');
+
+const signUp = async (req, res, next) => {
+ try {
+ const {
+ email,
+ hashedPassword,
+ phoneNumber,
+ profileImageUrl,
+ introduction,
+ } = req.body;
+
+ /*
+ middleware์์ email, hashedPassword, phoneNumber์
+ ์กด์ฌ์ ๋ํ ์๋ฌ ์ฒ๋ฆฌ ํ๋๋ฐ,
+ ์ฌ๊ธฐ์๋ ๋ ์๋ฌ ์ฒ๋ฆฌ๋ฅผ ํด์ผํ ๊น์?
+ */
+
+ const createdUser = await userService.createUser({
+ email,
+ password: hashedPassword,
+ phoneNumber,
+ profileImageUrl,
+ introduction,
+ });
+
+ res.status(201).json({
+ message: 'user created',
+ userId: createdUser.id,
+ });
+ } catch (err) {
+ next(err);
+ }
+};
+
+module.exports = {
+ signUp,
+}; | JavaScript | dao์ services๋ก ๋ถ๋ฆฌํ๊ธฐ๋ก ๊ฒฐ์ ํ์ต๋๋ค. |
@@ -0,0 +1,40 @@
+// Controller๋ ์ค์ง Service ๋ ์ด์ด์๋ง ์์กดํฉ๋๋ค.
+const { userService } = require('../services');
+const { errorGenerator } = require('../erros');
+
+const signUp = async (req, res, next) => {
+ try {
+ const {
+ email,
+ hashedPassword,
+ phoneNumber,
+ profileImageUrl,
+ introduction,
+ } = req.body;
+
+ /*
+ middleware์์ email, hashedPassword, phoneNumber์
+ ์กด์ฌ์ ๋ํ ์๋ฌ ์ฒ๋ฆฌ ํ๋๋ฐ,
+ ์ฌ๊ธฐ์๋ ๋ ์๋ฌ ์ฒ๋ฆฌ๋ฅผ ํด์ผํ ๊น์?
+ */
+
+ const createdUser = await userService.createUser({
+ email,
+ password: hashedPassword,
+ phoneNumber,
+ profileImageUrl,
+ introduction,
+ });
+
+ res.status(201).json({
+ message: 'user created',
+ userId: createdUser.id,
+ });
+ } catch (err) {
+ next(err);
+ }
+};
+
+module.exports = {
+ signUp,
+}; | JavaScript | ์ ๊ฐ ์ฐฉ๊ฐํ๋ค์! ๊ฐ์ฌํฉ๋๋ค :) |
@@ -0,0 +1,20 @@
+const { errorGenerator } = require('../erros');
+const { userService } = require('../services');
+
+const hashPassword = async (req, res, next) => {
+ try {
+ const { password } = req.body;
+
+ !password && errorGenerator(400);
+
+ req.body.hashedPassword = await userService.hashPassword(password);
+
+ next();
+ } catch (err) {
+ next(err);
+ }
+};
+
+module.exports = {
+ hashPassword,
+}; | JavaScript | ๋ฏธ๋ค์จ์ด์์ ๋น๋ฐ๋ฒํธ ์ํธํ๋ฅผ ํ๋ ๊ฑด๊ฐ์? ์ด ๋ฐฉ๋ฒ๋ ๊ต์ฅํ ์ฐธ์ ํ ๊ฒ ๊ฐ์ต๋๋ค.
๋ง์ฝ ์๋น์ค๊ฐ ์ปค์ง๊ฒ ๋๊ฑฐ๋, ๋ชจ๋
ธ๋ฆฌํฌ๋ฅผ ์ ์ฉํ๋ค๊ฑฐ๋, ๊ธฐํ ๋ค์ํ ๋ฐฉ์์ผ๋ก ๋น๋ฐ๋ฒํธ ์ํธํ๋ฅผ ํ์ฉํ๊ฒ ๋ ๊ฒฝ์ฐ๊ฐ ์๊ธฐ ๋๋ฌธ์ ๋ณดํต util ํจ์๋ก ๋นผ๋ด์ด ๋ค๋ฅธ ๊ณณ์์๋ ์ฌ์ฉํ ์ ์๋๋ก ๊ณตํต ํจ์๋ก ๋ง๋๋ ๊ฒ์ด ์กฐ๊ธ ๋ ๋ณดํธ์ ์ด๊ธฐ๋ ํ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,31 @@
+const { errorGenerator } = require('../erros');
+const { userService } = require('../services');
+
+const validateSignUpUserData = async (req, res, next) => {
+ try {
+ const { email, password, phoneNumber, profileImageUrl, introduction } =
+ req.body;
+
+ const REQUIRED_INFO = { email, password, phoneNumber };
+
+ for (const info in REQUIRED_INFO) {
+ !REQUIRED_INFO[info] && errorGenerator(400, `MISSING ${info}`);
+ }
+
+ !userService.validateEmail(email) && errorGenerator(400, 'INVALID EMAIL');
+
+ const foundUser = await userService.findUser({ email });
+ foundUser && errorGenerator(409);
+
+ !userService.validatePw(password) &&
+ errorGenerator(400, 'INVALID PASSWORD');
+
+ next();
+ } catch (err) {
+ next(err);
+ }
+};
+
+module.exports = {
+ validateSignUpUserData,
+}; | JavaScript | ๋ค๋ฅธ POST ์์๋ ํ์์ ์ธ ํค๊ฐ๋ค์ ํ์ธํ ์ผ์ด ๋ง์ง ์์๊น์?
๋ฒ์ฉ์ ์ผ๋ก ํ์ฉํ ์ ์๋ + ํ์ body ํค ๊ฐ์ ํ์ธํ๋ ๊ณตํต ํจ์๊ฐ ์์ด๋ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,48 @@
+const bcrypt = require('bcrypt');
+const { userDao } = require('../dao');
+
+const validateEmail = (email) => {
+ const validEmailRegExp = /\w@\w+\.\w/i;
+ return validEmailRegExp.test(email);
+};
+
+const validatePw = (pw) => {
+ const pwValidation = {
+ regexUppercase: /[A-Z]/g,
+ regexLowercase: /[a-z]/g,
+ regexSpecialCharacter: /[!|@|#|$|%|^|&|*]/g,
+ regexDigit: /[0-9]/g,
+ };
+ const MIN_PW_LENGTH = 8;
+ const pwLength = pw.length;
+
+ if (pwLength < MIN_PW_LENGTH) return false;
+
+ for (const validType in pwValidation) {
+ if (!pwValidation[validType].test(pw)) {
+ return false;
+ }
+ }
+
+ return true;
+};
+
+const hashPassword = async (password) => {
+ return await bcrypt.hash(password, 10);
+};
+
+const findUser = async (fields) => {
+ return await userDao.findUser(fields);
+};
+
+const createUser = async (userData) => {
+ return await userDao.createUser(userData);
+};
+
+module.exports = {
+ validateEmail,
+ validatePw,
+ hashPassword,
+ findUser,
+ createUser,
+}; | JavaScript | Regex ๊ฐ์ฒด๋ฅผ ํ์ฉํด์ ์กฐ๊ธ ๋ ๊ฐ๋จํ๊ฒ ์์ฑํ๋ ๊ฒ์ ์ด๋ค๊ฐ์? Regex.prototype.test ์์ฒด๊ฐ boolean ์ ๋ฐํํ๊ฒ ๋๋๊น์!
+test ๋ฉ์๋๊ฐ match ๋ณด๋ค ์ฑ๋ฅ์ ์ฐ์์ ์๊ธฐ๋ ํฉ๋๋ค! |
@@ -0,0 +1,20 @@
+const { errorGenerator } = require('../erros');
+const { userService } = require('../services');
+
+const hashPassword = async (req, res, next) => {
+ try {
+ const { password } = req.body;
+
+ !password && errorGenerator(400);
+
+ req.body.hashedPassword = await userService.hashPassword(password);
+
+ next();
+ } catch (err) {
+ next(err);
+ }
+};
+
+module.exports = {
+ hashPassword,
+}; | JavaScript | ๊ฐ์ฌํฉ๋๋ค! |
@@ -0,0 +1,31 @@
+const { errorGenerator } = require('../erros');
+const { userService } = require('../services');
+
+const validateSignUpUserData = async (req, res, next) => {
+ try {
+ const { email, password, phoneNumber, profileImageUrl, introduction } =
+ req.body;
+
+ const REQUIRED_INFO = { email, password, phoneNumber };
+
+ for (const info in REQUIRED_INFO) {
+ !REQUIRED_INFO[info] && errorGenerator(400, `MISSING ${info}`);
+ }
+
+ !userService.validateEmail(email) && errorGenerator(400, 'INVALID EMAIL');
+
+ const foundUser = await userService.findUser({ email });
+ foundUser && errorGenerator(409);
+
+ !userService.validatePw(password) &&
+ errorGenerator(400, 'INVALID PASSWORD');
+
+ next();
+ } catch (err) {
+ next(err);
+ }
+};
+
+module.exports = {
+ validateSignUpUserData,
+}; | JavaScript | ์ค...! ๋งค์ฐ ์ ์ฉํ ํจ์๊ฐ ๋ ๊ฒ ๊ฐ์ต๋๋ค! |
@@ -0,0 +1,31 @@
+const { errorGenerator } = require('../erros');
+const { userService } = require('../services');
+
+const validateSignUpUserData = async (req, res, next) => {
+ try {
+ const { email, password, phoneNumber, profileImageUrl, introduction } =
+ req.body;
+
+ const REQUIRED_INFO = { email, password, phoneNumber };
+
+ for (const info in REQUIRED_INFO) {
+ !REQUIRED_INFO[info] && errorGenerator(400, `MISSING ${info}`);
+ }
+
+ !userService.validateEmail(email) && errorGenerator(400, 'INVALID EMAIL');
+
+ const foundUser = await userService.findUser({ email });
+ foundUser && errorGenerator(409);
+
+ !userService.validatePw(password) &&
+ errorGenerator(400, 'INVALID PASSWORD');
+
+ next();
+ } catch (err) {
+ next(err);
+ }
+};
+
+module.exports = {
+ validateSignUpUserData,
+}; | JavaScript | ์๊ฒฌ ๊ฐ์ฌํฉ๋๋ค :) |
@@ -0,0 +1,93 @@
+const context = describe;
+
+describe('์ํ๋ชฉ๋ก API ํ
์คํธ', () => {
+ context('์ธ๊ธฐ ์ํ๋ชฉ๋ก 1ํ์ด์ง๋ฅผ ์กฐํํ๋ฉด', () => {
+ it('20๊ฐ์ ๋ชฉ๋ก์ ๋ฐํํ๋ค.', () => {
+ const baseUrl = 'https://api.themoviedb.org/3/movie/popular';
+ const param = new URLSearchParams({
+ api_key: Cypress.env('API_KEY'),
+ language: 'ko-KR',
+ page: 1,
+ });
+
+ cy.request('GET', `${baseUrl}?${param}`).as('popularMovies');
+
+ cy.get('@popularMovies').its('status').should('eq', 200);
+ cy.get('@popularMovies').its('body.results').should('have.length', 20);
+ });
+ });
+});
+
+describe('์ํ๋ชฉ๋ก e2e ํ
์คํธ', () => {
+ beforeEach(() => {
+ const baseUrl = 'https://api.themoviedb.org/3/movie/popular';
+ const param = new URLSearchParams({
+ api_key: Cypress.env('API_KEY'),
+ language: 'ko-KR',
+ page: 1,
+ });
+
+ cy.intercept(
+ {
+ method: 'GET',
+ url: `${baseUrl}?${param}`,
+ },
+ { fixture: 'movie-popular.json' }
+ ).as('popularMovies');
+
+ cy.visit('http://localhost:8080');
+ });
+
+ context('์ํ ๋ชฉ๋ก ์กฐํ ์', () => {
+ it('800ms ๋์ Skeleton UI๊ฐ ๋
ธ์ถ๋์๋ค๊ฐ ์ฌ๋ผ์ง๋ค.', () => {
+ cy.wait('@popularMovies');
+ cy.get('.skeleton').should('have.length', 60);
+ cy.wait(800);
+ cy.get('.skeleton').should('have.length', 0);
+ });
+ });
+
+ context('ํ์ด์ง ์ง์
์ ์ธ๊ธฐ์ํ ๋ชฉ๋ก 1ํ์ด์ง๋ฅผ ์กฐํํ๋ฉด', () => {
+ it('20๊ฐ์ .item-card๊ฐ ๋
ธ์ถ๋๋ค.', () => {
+ cy.get('.item-card').should('have.length', 20);
+ });
+ });
+
+ context('๋๋ณด๊ธฐ ๋ฒํผ์ ํด๋ฆญํ๋ฉด', () => {
+ it('40๊ฐ์ item-card ๋
ธ์ถ๋๋ค.', () => {
+ cy.get('.btn').click();
+ cy.get('.item-card').should('have.length', 40);
+ });
+ });
+});
+
+describe('์งง์ ์ํ๋ชฉ๋ก e2e ํ
์คํธ', () => {
+ beforeEach(() => {
+ const baseUrl = 'https://api.themoviedb.org/3/movie/popular';
+ const param = new URLSearchParams({
+ api_key: Cypress.env('API_KEY'),
+ language: 'ko-KR',
+ page: 1,
+ });
+
+ cy.intercept(
+ {
+ method: 'GET',
+ url: `${baseUrl}?${param}`,
+ },
+ { fixture: 'movie-popular-short.json' }
+ ).as('popularMovies');
+
+ cy.visit('http://localhost:8080');
+ });
+
+ context('total_pages ๊ฐ 1์ธ ์ธ๊ธฐ์ํ ๋ชฉ๋ก 1ํ์ด์ง๋ฅผ ์กฐํํ๋ฉด', () => {
+ it('18๊ฐ์ .item-card๊ฐ ๋
ธ์ถ๋๋ค.', () => {
+ cy.get('.item-card').should('have.length', 18);
+ });
+
+ it('๋ ๋ณด๊ธฐ ๋ฒํผ์ด ๋
ธ์ถ๋์ง ์๋๋ค.', () => {
+ cy.contains('๋๋ณด๊ธฐ').should('not.exist');
+ });
+ });
+}); | JavaScript | ํน์ 18๊ฐ์ธ ์ด์ ๊ฐ ์์๊น์? |
@@ -0,0 +1,10 @@
+์ํ ๋ชฉ๋ก API
+- ์ธ๊ธฐ ์ํ๋ชฉ๋ก 1ํ์ด์ง๋ฅผ ์กฐํํ๋ฉด 20๊ฐ์ ๋ชฉ๋ก์ ๋ฐํํ๋ค.
+
+ํ์ด์ง
+- ํ์ด์ง๋ฅผ ์ฆ๊ฐํ ์ ์๋ค.
+
+UI
+- ๋๋ณด๊ธฐ ๋ฒํผ์ ๋๋ฅด๋ฉด ๋ค์ ์ํ ๋ชฉ๋ก์ ๋ถ๋ฌ์จ๋ค.
+- ์ํ ๋ชฉ๋ก์ ํ์ด์ง ๋์ ๋๋ฌํ ๊ฒฝ์ฐ์๋ ๋๋ณด๊ธฐ ๋ฒํผ์ ํ๋ฉด์ ์ถ๋ ฅํ์ง ์๋๋ค.
+- ์ํ ๋ชฉ๋ก ์์ดํ
์ Skeleton UI๋ฅผ ๊ฐ์ง๋ค. | Unknown | ํ์ด์ง๋ฅผ ์ด๊ธฐํํ ์ ์๋ ๊ธฐ๋ฅ์ด ์์๊น์?
โ ์๋์ ์ฝ๋ฉํธ๋ค๊ณผ ๋ชฉ์ ์ ์ด์ด์ง๋๋ค! |
@@ -0,0 +1,18 @@
+const DEFAULT_SEARCH_PARAMS = {
+ api_key: process.env.API_KEY,
+ language: 'ko-KR',
+};
+const MOVIE_BASE_URL = 'https://api.themoviedb.org/3/movie';
+
+export async function getPopularMovie(page) {
+ const param = new URLSearchParams({
+ ...DEFAULT_SEARCH_PARAMS,
+ page,
+ });
+
+ const response = await fetch(`${MOVIE_BASE_URL}/popular?${param}`);
+ if (response.ok) {
+ return response.json();
+ }
+ return { results: [] };
+} | JavaScript | ์กฐ๊ธ ํน์ดํ ๋ฐฉ์์ธ ๊ฒ ๊ฐ๊ธดํ๋ฐ์! ์ด๋ ๊ฒ ๊ฐ์ฒด๋ก ๋ฌถ์ด์ export ํ์ ์ด์ ๊ฐ ์์ผ์ ๊ฐ์? |
@@ -0,0 +1,12 @@
+import PageHandler from './PageHandler';
+import { getPopularMovie } from '../api/movie';
+
+export async function getNextPopularMovieList() {
+ const { page, done } = PageHandler.next();
+ const { results } = await getPopularMovie(page);
+ return {
+ page,
+ done,
+ nextMovieList: results,
+ };
+} | JavaScript | ์์ง ๊ตฌํ๋์ง ์์ ๊ธฐ๋ฅ์ ๋ํ ํจ์๋ฅผ ๋จผ์ ์์ฑํด๋์ ์ด์ ๊ฐ ์์๊น์?! |
@@ -0,0 +1,12 @@
+import PageHandler from './PageHandler';
+import { getPopularMovie } from '../api/movie';
+
+export async function getNextPopularMovieList() {
+ const { page, done } = PageHandler.next();
+ const { results } = await getPopularMovie(page);
+ return {
+ page,
+ done,
+ nextMovieList: results,
+ };
+} | JavaScript | ํธ๋ค๋ฌ ํจ์์์ UI๋ฅผ ์กฐ์ํด์ฃผ๊ณ ์๋ค์! ์ฒ์์ `if (PageHandler.getCurrentPage() !== total_pages)` ์กฐ๊ฑด์ด UI ์ ๊ด๋ จ์ด ์๋ค๊ณ ์๊ฐํ๋๋ฐ ๊ฐ๊ฐ ๋ชฉ์ ์ด ๋ค๋ฅด๋ค์.
์ฌ๊ธฐ์ ์ด ํธ๋ค๋ฌ ํจ์์ ๋ํด์ ๋ ๊ฐ์ง๋ฅผ ๊ณ ๋ฏผํด๋ณด๋ฉด ์ข์ ๊ฒ ๊ฐ์์!
1. `onClickMoreButton` ๋ผ๋ ์ด๋ฆ์ด ํด๋น ํจ์๊ฐ ๋ฌด์์ ํ๋์ง ๋๋ฌ๋ผ ์ ์๋๊ฐ?
2. UI ์กฐ์๊ณผ ๋๋ฉ์ธ ๋ก์ง์ ํจ๊ป ๋๋ ๊ฒ ๋ง์๊น? |
@@ -0,0 +1,42 @@
+const MOVIE_TOTAL_PAGE_LIMIT = 500;
+
+const INITIAL_VALUE = {
+ page: 1,
+ totalPages: MOVIE_TOTAL_PAGE_LIMIT,
+};
+
+function PageEventHandler() {
+ let attr = { ...INITIAL_VALUE };
+
+ return {
+ next() {
+ if (!this.hasNextPage()) {
+ return {
+ page: attr.page,
+ done: true,
+ };
+ }
+ attr.page = attr.page + 1;
+
+ return {
+ page: attr.page,
+ done: !this.hasNextPage(),
+ };
+ },
+ getCurrentPage() {
+ return attr.page;
+ },
+ setTotalPages(totalPages) {
+ if (totalPages > MOVIE_TOTAL_PAGE_LIMIT) {
+ return;
+ }
+ attr.totalPages = totalPages;
+ },
+ hasNextPage() {
+ return attr.page < attr.totalPages;
+ },
+ };
+}
+
+const PageHandler = PageEventHandler();
+export default PageHandler; | JavaScript | ๋ง์ฐฌ๊ฐ์ง๋ก ์ฌ์ฉํ์ง ์๋ ๊ธฐ๋ฅ๋ค์ ๋ํ ๊ตฌํ๋ค์ด ์๋ ๊ฒ ๊ฐ์๋ฐ์!
์ ๊ฑฐํ์ง ์๊ณ ๋จ๊ฒจ ๋์ผ์ ์ด์ ๊ฐ ์์ผ์ค๊น์? |
@@ -0,0 +1,12 @@
+import PageHandler from './PageHandler';
+import { getPopularMovie } from '../api/movie';
+
+export async function getNextPopularMovieList() {
+ const { page, done } = PageHandler.next();
+ const { results } = await getPopularMovie(page);
+ return {
+ page,
+ done,
+ nextMovieList: results,
+ };
+} | JavaScript | ์กฐ๊ธ ๋ ์๋๋ฅผ ์ ๋ฌ๋๋ฆฌ์๋ฉด!
`onClickMoreButton`์ ํด๋ฆญ + ํน์ ๋ฒํผ + ํธ๋ค๋ฌ๋ผ๋ ๊ฒ๋ง ๋๋ฌ๋์ง,
์ด ํจ์๊ฐ ์ค์ ๋ก ์ด๋ค ํ๋์ ํ๋ ์ง๋ ์ ํ ์๋ ค ์ฃผ์ง ๋ชปํ๊ณ ์์ต๋๋ค! |
@@ -0,0 +1,93 @@
+const context = describe;
+
+describe('์ํ๋ชฉ๋ก API ํ
์คํธ', () => {
+ context('์ธ๊ธฐ ์ํ๋ชฉ๋ก 1ํ์ด์ง๋ฅผ ์กฐํํ๋ฉด', () => {
+ it('20๊ฐ์ ๋ชฉ๋ก์ ๋ฐํํ๋ค.', () => {
+ const baseUrl = 'https://api.themoviedb.org/3/movie/popular';
+ const param = new URLSearchParams({
+ api_key: Cypress.env('API_KEY'),
+ language: 'ko-KR',
+ page: 1,
+ });
+
+ cy.request('GET', `${baseUrl}?${param}`).as('popularMovies');
+
+ cy.get('@popularMovies').its('status').should('eq', 200);
+ cy.get('@popularMovies').its('body.results').should('have.length', 20);
+ });
+ });
+});
+
+describe('์ํ๋ชฉ๋ก e2e ํ
์คํธ', () => {
+ beforeEach(() => {
+ const baseUrl = 'https://api.themoviedb.org/3/movie/popular';
+ const param = new URLSearchParams({
+ api_key: Cypress.env('API_KEY'),
+ language: 'ko-KR',
+ page: 1,
+ });
+
+ cy.intercept(
+ {
+ method: 'GET',
+ url: `${baseUrl}?${param}`,
+ },
+ { fixture: 'movie-popular.json' }
+ ).as('popularMovies');
+
+ cy.visit('http://localhost:8080');
+ });
+
+ context('์ํ ๋ชฉ๋ก ์กฐํ ์', () => {
+ it('800ms ๋์ Skeleton UI๊ฐ ๋
ธ์ถ๋์๋ค๊ฐ ์ฌ๋ผ์ง๋ค.', () => {
+ cy.wait('@popularMovies');
+ cy.get('.skeleton').should('have.length', 60);
+ cy.wait(800);
+ cy.get('.skeleton').should('have.length', 0);
+ });
+ });
+
+ context('ํ์ด์ง ์ง์
์ ์ธ๊ธฐ์ํ ๋ชฉ๋ก 1ํ์ด์ง๋ฅผ ์กฐํํ๋ฉด', () => {
+ it('20๊ฐ์ .item-card๊ฐ ๋
ธ์ถ๋๋ค.', () => {
+ cy.get('.item-card').should('have.length', 20);
+ });
+ });
+
+ context('๋๋ณด๊ธฐ ๋ฒํผ์ ํด๋ฆญํ๋ฉด', () => {
+ it('40๊ฐ์ item-card ๋
ธ์ถ๋๋ค.', () => {
+ cy.get('.btn').click();
+ cy.get('.item-card').should('have.length', 40);
+ });
+ });
+});
+
+describe('์งง์ ์ํ๋ชฉ๋ก e2e ํ
์คํธ', () => {
+ beforeEach(() => {
+ const baseUrl = 'https://api.themoviedb.org/3/movie/popular';
+ const param = new URLSearchParams({
+ api_key: Cypress.env('API_KEY'),
+ language: 'ko-KR',
+ page: 1,
+ });
+
+ cy.intercept(
+ {
+ method: 'GET',
+ url: `${baseUrl}?${param}`,
+ },
+ { fixture: 'movie-popular-short.json' }
+ ).as('popularMovies');
+
+ cy.visit('http://localhost:8080');
+ });
+
+ context('total_pages ๊ฐ 1์ธ ์ธ๊ธฐ์ํ ๋ชฉ๋ก 1ํ์ด์ง๋ฅผ ์กฐํํ๋ฉด', () => {
+ it('18๊ฐ์ .item-card๊ฐ ๋
ธ์ถ๋๋ค.', () => {
+ cy.get('.item-card').should('have.length', 18);
+ });
+
+ it('๋ ๋ณด๊ธฐ ๋ฒํผ์ด ๋
ธ์ถ๋์ง ์๋๋ค.', () => {
+ cy.contains('๋๋ณด๊ธฐ').should('not.exist');
+ });
+ });
+}); | JavaScript | ์ธ๊ธฐ ์ํ๋ชฉ๋ก ๋ฐ์ดํฐ๊ฐ 18๊ฐ๋ฐ์ ์์ ๋ 20๊ฐ๋ฅผ ๊ทธ๋ฆฌ์ง ์๊ณ ๊ฐ์๋ฅผ ์ฌ๋ฐ๋ฅด๊ฒ ํ์ํ๋์ง ํ
์คํธํ๊ธฐ ์ํด ์ถ๊ฐํด๋ณด์์ต๋๋ค! |
@@ -0,0 +1,18 @@
+const DEFAULT_SEARCH_PARAMS = {
+ api_key: process.env.API_KEY,
+ language: 'ko-KR',
+};
+const MOVIE_BASE_URL = 'https://api.themoviedb.org/3/movie';
+
+export async function getPopularMovie(page) {
+ const param = new URLSearchParams({
+ ...DEFAULT_SEARCH_PARAMS,
+ page,
+ });
+
+ const response = await fetch(`${MOVIE_BASE_URL}/popular?${param}`);
+ if (response.ok) {
+ return response.json();
+ }
+ return { results: [] };
+} | JavaScript | ์ฌ๋ฌ๊ฐ์ ํจ์๋ฅผ ๋ฌถ์ด์ ๋ด๋ณด๋ด๊ธฐ ์ํด์ ์์๊ฐ์ ์ข
์ข
์ฌ์ฉํด์์๋๋ฐ์!
์ฌ๊ธฐ์๋ ํ๋์ ํจ์๋ง ๋ด๋ณด๋ด๊ธฐ์ ์ ๊ฑฐํด๋ณด์์ต๋๋ค..!
ํน์ ์ฌ๋ฌ๊ฐ์ ํจ์๋ฅผ export ํด์ผํ ๋ ์ด๋ค ๋ฐฉ์์ ์ฌ์ฉํ์๊ณ ์ ํธํ์๋์ง ์ฌ์ญ์ด๋ด๋ ๋ ๊น์? |
@@ -0,0 +1,12 @@
+import PageHandler from './PageHandler';
+import { getPopularMovie } from '../api/movie';
+
+export async function getNextPopularMovieList() {
+ const { page, done } = PageHandler.next();
+ const { results } = await getPopularMovie(page);
+ return {
+ page,
+ done,
+ nextMovieList: results,
+ };
+} | JavaScript | figma๋ฅผ ๋ณด๊ณ modal ์ฌ์ฉ๋ถ๋ถ์ด ์์ด ๋ฏธ๋ฆฌ ์์ฑํด๋ ๊ฒ์ธ๋ฐ ๋ง์ํด์ฃผ์ ๊ฒ์ฒ๋ผ ์ ์ง๋ณด์์ ์ด๋ ค์์ ์ค ์ ์๊ฒ ๋ค์..!
๋ช
์ฌํ๋๋ก ํ๊ฒ ์ต๋๋ค! ํด๋น ๋ถ๋ถ์ ์ ๊ฑฐํ์์ต๋๋ค. ๊ฐ์ฌํฉ๋๋ค! ๐ |
@@ -0,0 +1,12 @@
+import PageHandler from './PageHandler';
+import { getPopularMovie } from '../api/movie';
+
+export async function getNextPopularMovieList() {
+ const { page, done } = PageHandler.next();
+ const { results } = await getPopularMovie(page);
+ return {
+ page,
+ done,
+ nextMovieList: results,
+ };
+} | JavaScript | `onClickMoreButton`์ `getNextPopularMovieList`๋ก ๋ณ๊ฒฝํ๋ฉด์ ์ญํ ์ ๋ถ๋ฆฌํด๋ณด์์ต๋๋ค! |
@@ -0,0 +1,42 @@
+const MOVIE_TOTAL_PAGE_LIMIT = 500;
+
+const INITIAL_VALUE = {
+ page: 1,
+ totalPages: MOVIE_TOTAL_PAGE_LIMIT,
+};
+
+function PageEventHandler() {
+ let attr = { ...INITIAL_VALUE };
+
+ return {
+ next() {
+ if (!this.hasNextPage()) {
+ return {
+ page: attr.page,
+ done: true,
+ };
+ }
+ attr.page = attr.page + 1;
+
+ return {
+ page: attr.page,
+ done: !this.hasNextPage(),
+ };
+ },
+ getCurrentPage() {
+ return attr.page;
+ },
+ setTotalPages(totalPages) {
+ if (totalPages > MOVIE_TOTAL_PAGE_LIMIT) {
+ return;
+ }
+ attr.totalPages = totalPages;
+ },
+ hasNextPage() {
+ return attr.page < attr.totalPages;
+ },
+ };
+}
+
+const PageHandler = PageEventHandler();
+export default PageHandler; | JavaScript | ์ ๊ฑฐํ์์ต๋๋ค! ์ด์ ๋ ์์ ๋ง์๋๋ฆฐ ์ด์ ์ ๋์ผํฉ๋๋ค!
๊ผผ๊ผผํ ๋ฆฌ๋ทฐํด์ฃผ์
์ ๊ฐ์ฌ๋๋ฆฝ๋๋ค ๐ |
@@ -0,0 +1,12 @@
+import PageHandler from './PageHandler';
+import { getPopularMovie } from '../api/movie';
+
+export async function getNextPopularMovieList() {
+ const { page, done } = PageHandler.next();
+ const { results } = await getPopularMovie(page);
+ return {
+ page,
+ done,
+ nextMovieList: results,
+ };
+} | JavaScript | ์... ์ด ๋ถ๋ถ์ ์ ๊ฐ ์๋ํ ๋ฐ์๋ ์กฐ๊ธ ๋ค๋ฅด๊ฒ ๋ณ๊ฒฝ๋ ๊ฒ ๊ฐ์ต๋๋ค!
์ ๊ฐ ์์ฌ ์ฝ๋๋ฅผ ์์ด๊ฐ๋ฉฐ ์ด๋ ์ ๋ ๋ณ๊ฒฝํด๋ณผ๊ฒ์! |
@@ -0,0 +1,18 @@
+export class LoadingHandler {
+ #loading;
+ constructor(initialValue) {
+ this.#loading = initialValue;
+ }
+
+ start() {
+ this.#loading = true;
+ }
+
+ end() {
+ this.#loading = false;
+ }
+
+ isLoading() {
+ return this.#loading;
+ }
+} | JavaScript | ์ฌ์ฉ์ฒ๋ฅผ ๋ณด๋ฉด, ๋ก๋ฉ ์ํ ์์ฒด๋ฅผ ํ์ฉํ๋ ๊ฒฝ์ฐ๊ฐ ํ ๋ฒ ๋ฐ์ ์๊ณ ,
start(), end() ์คํ๊ณผ ํจ๊ป DOM ์กฐ์ ๋ก์ง์ด ํจ๊ป ์ค๋ ๊ฒ ๊ฐ์์!
์ฌ๊ธฐ์ DOM ์กฐ์๋ ๊ฐ์ด ํด์ฃผ๊ณ , ์
๋ ฅ์ผ๋ก ์กฐ์ํ ์์๋ฅผ ๊ฐ์ด ๋ฐ์ผ๋ฉด ๋ ์์ง์ฑ์ด ๋์ ์ฝ๋๊ฐ ๋ ๊ฒ ๊ฐ์์! |
@@ -0,0 +1,18 @@
+const DEFAULT_SEARCH_PARAMS = {
+ api_key: process.env.API_KEY,
+ language: 'ko-KR',
+};
+const MOVIE_BASE_URL = 'https://api.themoviedb.org/3/movie';
+
+export async function getPopularMovie(page) {
+ const param = new URLSearchParams({
+ ...DEFAULT_SEARCH_PARAMS,
+ page,
+ });
+
+ const response = await fetch(`${MOVIE_BASE_URL}/popular?${param}`);
+ if (response.ok) {
+ return response.json();
+ }
+ return { results: [] };
+} | JavaScript | ์ฌ๋ฌ๊ฐ์ ํจ์๋ฅผ ๋ฌถ์ด์ ๋ด๋ณด๋ด๊ธฐ ์ํจ์ด๋ค
-> ์ปจ๋ฒค์
๋ง ๋ง๋ค๋ฉด ์ด๋ค ๋ฐฉํฅ์ด๋ ์๊ด ์๋ค๊ณ ์๊ฐํฉ๋๋ค!
๋ค๋ง, ์ ๋ ํ๋์ ํจ์์ธ ์ํฉ์์ ํจ์๊ฐ ๋ ์ถ๊ฐ๋์ง ์์๋๋ฐ, ๋ ์ถ๊ฐ๋ ์์ ์ธ๋ฐ ์ด๋ ๊ฒ ํ์ ๊ฒ ๊ฐ์์
๋จ๊ธด ์ฝ๋ฉํธ์ด๊ธดํฉ๋๋ค! (๋ณธ๋ฌธ์ ์ฝ๋ฉํธ์ ๋์ผํ ๋ด์ฉ์
๋๋ค ใ
ใ
) |
@@ -1,7 +1,128 @@
+import { useNavigate } from 'react-router-dom';
+import { useState } from 'react';
import './Login.scss';
function Login() {
- return <></>;
+ // const [idState, setIdState] = useState('');
+ // const [passwordValue, setPasswordValue] = useState('');
+ // const [disabled, setDisabled] = useState(true);
+ // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' });
+
+ const navigate = useNavigate();
+ const [loginValues, setLoginValues] = useState({
+ id: '',
+ password: '',
+ });
+
+ const handleInputValue = e => {
+ const { name, value } = e.target;
+ setLoginValues({ ...loginValues, [name]: value });
+ };
+
+ // const { type, value } = event.target;
+
+ // function handleLogin(event) {
+ // if (type === 'text') {
+ // setIdState(value);
+ // } else if (type === 'password') {
+ // setPasswordValue(value);
+ // }
+ // handleButton();
+ // }
+
+ // const checkId = idValue => {
+ // return idValue.includes('@') ? true : false;
+ // };
+
+ // const checkPw = pwValue => {
+ // return pwValue.length >= 5 ? true : false;
+ // };
+
+ // const handleButton = () => {
+ // const isValidId = checkId(state);
+ // const isValidPw = checkPw(passwordValue);
+
+ // if (isValidId && isValidPw) {
+ // buttonColor(true);
+ // } else {
+ // buttonColor(false);
+ // }
+ // };
+
+ // const buttonColor = btnValid => {
+ // setDisabled(!btnValid);
+ // setStyle({
+ // opacity: btnValid ? 1 : 0.5,
+ // cursor: btnValid ? 'pointer' : 'default',
+ // });
+ // };
+
+ const goToMain = () => {
+ fetch('http://10.58.4.238:8000/users/login', {
+ method: 'POST',
+ body: JSON.stringify({
+ email: loginValues.id,
+ password: loginValues.password,
+ // name: '๋์',
+ // phone_number: '010-1111-111',
+ }),
+ })
+ .then(response => response.json())
+ .then(result => {
+ // console.log(result);
+ if (result.token) {
+ //localStorage.setItem('token', result.token);
+ alert('ํ์ํฉ๋๋ค!');
+ navigate('/main-han');
+ } else if (result.message === 'INVALID_USER') {
+ alert('ID์ PW๋ฅผ ํ์ธํด์ฃผ์ธ์.');
+ }
+ });
+ };
+
+ const isInputValid =
+ loginValues.id.includes('@') &&
+ loginValues.id.length >= 6 &&
+ loginValues.password.length >= 6;
+ // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6);
+ // console.log(loginValues.password.length >= 6);
+ // console.log(isInputValid);
+
+ return (
+ <div className="login">
+ <form className="loginBox">
+ <h1>Westagram</h1>
+ <input
+ id="id"
+ name="id"
+ className="userId"
+ type="text"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ onChange={handleInputValue}
+ />
+ <input
+ id="password"
+ name="password"
+ className="userPassword"
+ type="password"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ onChange={handleInputValue}
+ />
+ <button
+ type="button"
+ className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`}
+ onClick={goToMain}
+ disabled={!isInputValid}
+ //style={style}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <div className="findPassword">
+ <a href="#">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</a>
+ </div>
+ </form>
+ </div>
+ );
}
export default Login; | JavaScript | ```suggestion
className={`loginBtn ${
idValue.indexOf('@') > -1 && pwValue.length >= 5
? 'loginBtnLive'
: ''
}`}
```
className์ ๋์ ์ฌ์ฉ์ ์ ์ฉํ๋ฉด ์ข์ ๊ฒ ๊ฐ์์
์ธ๋ผ์ธ ์คํ์ผ์ ์ฐ์ ์์๊ฐ ๋์์, ํ์์ด class๋ฅผ ์์ ํ์ ๋
class๊ฐ ์ ์ฉ์ด ์๋๋ ๋ฌธ์ ๊ฐ ์๋ค๊ณ ํด์.
์กฐ๊ฑด ์ฐ์ฐ์๋ฅผ ํ์ฉํด์ className์ ๋์ ์ผ๋ก ์ธ ์ ์์
className={์๋ ํด๋์ค +ํ์ฑํ ํด๋์ค <-- ์กฐ๊ฑด ์ฐ์ฐ์๋ก ํด๋์ค ์ถ๊ฐ ์ฌ๋ถ ๊ฒฐ์ } |
@@ -1,7 +1,128 @@
+import { useNavigate } from 'react-router-dom';
+import { useState } from 'react';
import './Login.scss';
function Login() {
- return <></>;
+ // const [idState, setIdState] = useState('');
+ // const [passwordValue, setPasswordValue] = useState('');
+ // const [disabled, setDisabled] = useState(true);
+ // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' });
+
+ const navigate = useNavigate();
+ const [loginValues, setLoginValues] = useState({
+ id: '',
+ password: '',
+ });
+
+ const handleInputValue = e => {
+ const { name, value } = e.target;
+ setLoginValues({ ...loginValues, [name]: value });
+ };
+
+ // const { type, value } = event.target;
+
+ // function handleLogin(event) {
+ // if (type === 'text') {
+ // setIdState(value);
+ // } else if (type === 'password') {
+ // setPasswordValue(value);
+ // }
+ // handleButton();
+ // }
+
+ // const checkId = idValue => {
+ // return idValue.includes('@') ? true : false;
+ // };
+
+ // const checkPw = pwValue => {
+ // return pwValue.length >= 5 ? true : false;
+ // };
+
+ // const handleButton = () => {
+ // const isValidId = checkId(state);
+ // const isValidPw = checkPw(passwordValue);
+
+ // if (isValidId && isValidPw) {
+ // buttonColor(true);
+ // } else {
+ // buttonColor(false);
+ // }
+ // };
+
+ // const buttonColor = btnValid => {
+ // setDisabled(!btnValid);
+ // setStyle({
+ // opacity: btnValid ? 1 : 0.5,
+ // cursor: btnValid ? 'pointer' : 'default',
+ // });
+ // };
+
+ const goToMain = () => {
+ fetch('http://10.58.4.238:8000/users/login', {
+ method: 'POST',
+ body: JSON.stringify({
+ email: loginValues.id,
+ password: loginValues.password,
+ // name: '๋์',
+ // phone_number: '010-1111-111',
+ }),
+ })
+ .then(response => response.json())
+ .then(result => {
+ // console.log(result);
+ if (result.token) {
+ //localStorage.setItem('token', result.token);
+ alert('ํ์ํฉ๋๋ค!');
+ navigate('/main-han');
+ } else if (result.message === 'INVALID_USER') {
+ alert('ID์ PW๋ฅผ ํ์ธํด์ฃผ์ธ์.');
+ }
+ });
+ };
+
+ const isInputValid =
+ loginValues.id.includes('@') &&
+ loginValues.id.length >= 6 &&
+ loginValues.password.length >= 6;
+ // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6);
+ // console.log(loginValues.password.length >= 6);
+ // console.log(isInputValid);
+
+ return (
+ <div className="login">
+ <form className="loginBox">
+ <h1>Westagram</h1>
+ <input
+ id="id"
+ name="id"
+ className="userId"
+ type="text"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ onChange={handleInputValue}
+ />
+ <input
+ id="password"
+ name="password"
+ className="userPassword"
+ type="password"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ onChange={handleInputValue}
+ />
+ <button
+ type="button"
+ className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`}
+ onClick={goToMain}
+ disabled={!isInputValid}
+ //style={style}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <div className="findPassword">
+ <a href="#">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</a>
+ </div>
+ </form>
+ </div>
+ );
}
export default Login; | JavaScript | className ๋์ ์ฌ์ฉ์ ํ๊ฒ ๋๋ฉด
style ์คํ
์ดํธ๊ฐ ํ์์๊ฒ ๋๋ค๊ณ ํด์!
disabled๋ state๋ก ๋จ๊ฒจ๋์ง ๊ณ ๋ฏผํด๋ณด๋ผ๊ณ ํ์ญ๋๋ค (from ๋ฉํ ๋..) |
@@ -1,7 +1,128 @@
+import { useNavigate } from 'react-router-dom';
+import { useState } from 'react';
import './Login.scss';
function Login() {
- return <></>;
+ // const [idState, setIdState] = useState('');
+ // const [passwordValue, setPasswordValue] = useState('');
+ // const [disabled, setDisabled] = useState(true);
+ // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' });
+
+ const navigate = useNavigate();
+ const [loginValues, setLoginValues] = useState({
+ id: '',
+ password: '',
+ });
+
+ const handleInputValue = e => {
+ const { name, value } = e.target;
+ setLoginValues({ ...loginValues, [name]: value });
+ };
+
+ // const { type, value } = event.target;
+
+ // function handleLogin(event) {
+ // if (type === 'text') {
+ // setIdState(value);
+ // } else if (type === 'password') {
+ // setPasswordValue(value);
+ // }
+ // handleButton();
+ // }
+
+ // const checkId = idValue => {
+ // return idValue.includes('@') ? true : false;
+ // };
+
+ // const checkPw = pwValue => {
+ // return pwValue.length >= 5 ? true : false;
+ // };
+
+ // const handleButton = () => {
+ // const isValidId = checkId(state);
+ // const isValidPw = checkPw(passwordValue);
+
+ // if (isValidId && isValidPw) {
+ // buttonColor(true);
+ // } else {
+ // buttonColor(false);
+ // }
+ // };
+
+ // const buttonColor = btnValid => {
+ // setDisabled(!btnValid);
+ // setStyle({
+ // opacity: btnValid ? 1 : 0.5,
+ // cursor: btnValid ? 'pointer' : 'default',
+ // });
+ // };
+
+ const goToMain = () => {
+ fetch('http://10.58.4.238:8000/users/login', {
+ method: 'POST',
+ body: JSON.stringify({
+ email: loginValues.id,
+ password: loginValues.password,
+ // name: '๋์',
+ // phone_number: '010-1111-111',
+ }),
+ })
+ .then(response => response.json())
+ .then(result => {
+ // console.log(result);
+ if (result.token) {
+ //localStorage.setItem('token', result.token);
+ alert('ํ์ํฉ๋๋ค!');
+ navigate('/main-han');
+ } else if (result.message === 'INVALID_USER') {
+ alert('ID์ PW๋ฅผ ํ์ธํด์ฃผ์ธ์.');
+ }
+ });
+ };
+
+ const isInputValid =
+ loginValues.id.includes('@') &&
+ loginValues.id.length >= 6 &&
+ loginValues.password.length >= 6;
+ // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6);
+ // console.log(loginValues.password.length >= 6);
+ // console.log(isInputValid);
+
+ return (
+ <div className="login">
+ <form className="loginBox">
+ <h1>Westagram</h1>
+ <input
+ id="id"
+ name="id"
+ className="userId"
+ type="text"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ onChange={handleInputValue}
+ />
+ <input
+ id="password"
+ name="password"
+ className="userPassword"
+ type="password"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ onChange={handleInputValue}
+ />
+ <button
+ type="button"
+ className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`}
+ onClick={goToMain}
+ disabled={!isInputValid}
+ //style={style}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <div className="findPassword">
+ <a href="#">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</a>
+ </div>
+ </form>
+ </div>
+ );
}
export default Login; | JavaScript | className ๋์ ์ฌ์ฉ์ ํ๊ฒ ๋๋ฉด
์ ํจ์ฑ ๊ฒ์ฌ ๊ด๋ จ ํจ์๋ฅผ ๋ค ์ง์๋ ๋ ๊ฒ ๊ฐ์ต๋๋ค! |
@@ -1,7 +1,128 @@
+import { useNavigate } from 'react-router-dom';
+import { useState } from 'react';
import './Login.scss';
function Login() {
- return <></>;
+ // const [idState, setIdState] = useState('');
+ // const [passwordValue, setPasswordValue] = useState('');
+ // const [disabled, setDisabled] = useState(true);
+ // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' });
+
+ const navigate = useNavigate();
+ const [loginValues, setLoginValues] = useState({
+ id: '',
+ password: '',
+ });
+
+ const handleInputValue = e => {
+ const { name, value } = e.target;
+ setLoginValues({ ...loginValues, [name]: value });
+ };
+
+ // const { type, value } = event.target;
+
+ // function handleLogin(event) {
+ // if (type === 'text') {
+ // setIdState(value);
+ // } else if (type === 'password') {
+ // setPasswordValue(value);
+ // }
+ // handleButton();
+ // }
+
+ // const checkId = idValue => {
+ // return idValue.includes('@') ? true : false;
+ // };
+
+ // const checkPw = pwValue => {
+ // return pwValue.length >= 5 ? true : false;
+ // };
+
+ // const handleButton = () => {
+ // const isValidId = checkId(state);
+ // const isValidPw = checkPw(passwordValue);
+
+ // if (isValidId && isValidPw) {
+ // buttonColor(true);
+ // } else {
+ // buttonColor(false);
+ // }
+ // };
+
+ // const buttonColor = btnValid => {
+ // setDisabled(!btnValid);
+ // setStyle({
+ // opacity: btnValid ? 1 : 0.5,
+ // cursor: btnValid ? 'pointer' : 'default',
+ // });
+ // };
+
+ const goToMain = () => {
+ fetch('http://10.58.4.238:8000/users/login', {
+ method: 'POST',
+ body: JSON.stringify({
+ email: loginValues.id,
+ password: loginValues.password,
+ // name: '๋์',
+ // phone_number: '010-1111-111',
+ }),
+ })
+ .then(response => response.json())
+ .then(result => {
+ // console.log(result);
+ if (result.token) {
+ //localStorage.setItem('token', result.token);
+ alert('ํ์ํฉ๋๋ค!');
+ navigate('/main-han');
+ } else if (result.message === 'INVALID_USER') {
+ alert('ID์ PW๋ฅผ ํ์ธํด์ฃผ์ธ์.');
+ }
+ });
+ };
+
+ const isInputValid =
+ loginValues.id.includes('@') &&
+ loginValues.id.length >= 6 &&
+ loginValues.password.length >= 6;
+ // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6);
+ // console.log(loginValues.password.length >= 6);
+ // console.log(isInputValid);
+
+ return (
+ <div className="login">
+ <form className="loginBox">
+ <h1>Westagram</h1>
+ <input
+ id="id"
+ name="id"
+ className="userId"
+ type="text"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ onChange={handleInputValue}
+ />
+ <input
+ id="password"
+ name="password"
+ className="userPassword"
+ type="password"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ onChange={handleInputValue}
+ />
+ <button
+ type="button"
+ className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`}
+ onClick={goToMain}
+ disabled={!isInputValid}
+ //style={style}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <div className="findPassword">
+ <a href="#">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</a>
+ </div>
+ </form>
+ </div>
+ );
}
export default Login; | JavaScript | ```suggestion
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import './Login.scss';
```
scss๋ฅผ ๋ฐ์ผ๋ก ๋ด๋ ค์ฃผ๋ฉด ์ข์๊ฑฐ๊ฐ๋ค์ |
@@ -1,7 +1,128 @@
+import { useNavigate } from 'react-router-dom';
+import { useState } from 'react';
import './Login.scss';
function Login() {
- return <></>;
+ // const [idState, setIdState] = useState('');
+ // const [passwordValue, setPasswordValue] = useState('');
+ // const [disabled, setDisabled] = useState(true);
+ // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' });
+
+ const navigate = useNavigate();
+ const [loginValues, setLoginValues] = useState({
+ id: '',
+ password: '',
+ });
+
+ const handleInputValue = e => {
+ const { name, value } = e.target;
+ setLoginValues({ ...loginValues, [name]: value });
+ };
+
+ // const { type, value } = event.target;
+
+ // function handleLogin(event) {
+ // if (type === 'text') {
+ // setIdState(value);
+ // } else if (type === 'password') {
+ // setPasswordValue(value);
+ // }
+ // handleButton();
+ // }
+
+ // const checkId = idValue => {
+ // return idValue.includes('@') ? true : false;
+ // };
+
+ // const checkPw = pwValue => {
+ // return pwValue.length >= 5 ? true : false;
+ // };
+
+ // const handleButton = () => {
+ // const isValidId = checkId(state);
+ // const isValidPw = checkPw(passwordValue);
+
+ // if (isValidId && isValidPw) {
+ // buttonColor(true);
+ // } else {
+ // buttonColor(false);
+ // }
+ // };
+
+ // const buttonColor = btnValid => {
+ // setDisabled(!btnValid);
+ // setStyle({
+ // opacity: btnValid ? 1 : 0.5,
+ // cursor: btnValid ? 'pointer' : 'default',
+ // });
+ // };
+
+ const goToMain = () => {
+ fetch('http://10.58.4.238:8000/users/login', {
+ method: 'POST',
+ body: JSON.stringify({
+ email: loginValues.id,
+ password: loginValues.password,
+ // name: '๋์',
+ // phone_number: '010-1111-111',
+ }),
+ })
+ .then(response => response.json())
+ .then(result => {
+ // console.log(result);
+ if (result.token) {
+ //localStorage.setItem('token', result.token);
+ alert('ํ์ํฉ๋๋ค!');
+ navigate('/main-han');
+ } else if (result.message === 'INVALID_USER') {
+ alert('ID์ PW๋ฅผ ํ์ธํด์ฃผ์ธ์.');
+ }
+ });
+ };
+
+ const isInputValid =
+ loginValues.id.includes('@') &&
+ loginValues.id.length >= 6 &&
+ loginValues.password.length >= 6;
+ // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6);
+ // console.log(loginValues.password.length >= 6);
+ // console.log(isInputValid);
+
+ return (
+ <div className="login">
+ <form className="loginBox">
+ <h1>Westagram</h1>
+ <input
+ id="id"
+ name="id"
+ className="userId"
+ type="text"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ onChange={handleInputValue}
+ />
+ <input
+ id="password"
+ name="password"
+ className="userPassword"
+ type="password"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ onChange={handleInputValue}
+ />
+ <button
+ type="button"
+ className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`}
+ onClick={goToMain}
+ disabled={!isInputValid}
+ //style={style}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <div className="findPassword">
+ <a href="#">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</a>
+ </div>
+ </form>
+ </div>
+ );
}
export default Login; | JavaScript | ํ
๋ฐ์ผ๋ก ๋ถ์ฌ์ฃผ๋๊ฒ ์ข์ง ์์๊น์? |
@@ -1,8 +1,43 @@
-import './Main.scss';
+import { useState, useEffect } from 'react';
+import Nav from '../../../components/Nav/Nav';
+import Feed from './Feed';
+import MainRight from './MainRight';
import '../../../styles/variables.scss';
+import './Main.scss';
function Main() {
- return <></>;
+ const [articles, setArticles] = useState([]);
+
+ useEffect(() => {
+ fetch('http://localhost:3000/data/younghyunHan/feedData.json')
+ .then(res => res.json())
+ .then(data => {
+ setArticles(data);
+ });
+ }, []);
+
+ return (
+ <div className="main">
+ <Nav />
+ <main>
+ <div className="feeds">
+ {articles.map((content, index) => {
+ return (
+ <div key={index}>
+ <Feed
+ userName={content.userName}
+ feedImg={content.feedImg}
+ userMan={content.userMan}
+ profileLogo={content.profileLogo}
+ />
+ </div>
+ );
+ })}
+ </div>
+ <MainRight />
+ </main>
+ </div>
+ );
}
export default Main; | JavaScript | ์ปดํฌ๋ํธ ์ด๋ฆ์ Feed ๋ก ๋ฐ๊ฟ๋ณด๋ฉด ์ข์ ๊ฒ ๊ฐ์์!!
์ด๋ฆ์ ์๋ฏธ๋ฅผ ๋ ๋ด์์ฃผ๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค |
@@ -1,8 +1,43 @@
-import './Main.scss';
+import { useState, useEffect } from 'react';
+import Nav from '../../../components/Nav/Nav';
+import Feed from './Feed';
+import MainRight from './MainRight';
import '../../../styles/variables.scss';
+import './Main.scss';
function Main() {
- return <></>;
+ const [articles, setArticles] = useState([]);
+
+ useEffect(() => {
+ fetch('http://localhost:3000/data/younghyunHan/feedData.json')
+ .then(res => res.json())
+ .then(data => {
+ setArticles(data);
+ });
+ }, []);
+
+ return (
+ <div className="main">
+ <Nav />
+ <main>
+ <div className="feeds">
+ {articles.map((content, index) => {
+ return (
+ <div key={index}>
+ <Feed
+ userName={content.userName}
+ feedImg={content.feedImg}
+ userMan={content.userMan}
+ profileLogo={content.profileLogo}
+ />
+ </div>
+ );
+ })}
+ </div>
+ <MainRight />
+ </main>
+ </div>
+ );
}
export default Main; | JavaScript | mainRight๋ ์ปดํฌ๋ํธ๋ก ๋ง๋ค์ด์ฃผ๋ฉด ์ข์ ๊ฒ ๊ฐ์์
์ด๋ ๊ฒ ํด์ฃผ๋ฉด main.js ๋ด์ฉ, scss ๋ด์ฉ๋ ๋ ๊ฐ๋จํด์ง ๊ฒ ๊ฐ์!
```suggestion
<MainRight />
``` |
@@ -1,8 +1,43 @@
-import './Main.scss';
+import { useState, useEffect } from 'react';
+import Nav from '../../../components/Nav/Nav';
+import Feed from './Feed';
+import MainRight from './MainRight';
import '../../../styles/variables.scss';
+import './Main.scss';
function Main() {
- return <></>;
+ const [articles, setArticles] = useState([]);
+
+ useEffect(() => {
+ fetch('http://localhost:3000/data/younghyunHan/feedData.json')
+ .then(res => res.json())
+ .then(data => {
+ setArticles(data);
+ });
+ }, []);
+
+ return (
+ <div className="main">
+ <Nav />
+ <main>
+ <div className="feeds">
+ {articles.map((content, index) => {
+ return (
+ <div key={index}>
+ <Feed
+ userName={content.userName}
+ feedImg={content.feedImg}
+ userMan={content.userMan}
+ profileLogo={content.profileLogo}
+ />
+ </div>
+ );
+ })}
+ </div>
+ <MainRight />
+ </main>
+ </div>
+ );
}
export default Main; | JavaScript | ```suggestion
<Footer />
```
์ปดํฌ๋ํธ๋ก ๋ถ๋ฆฌํด์ฃผ๊ณ , footer ์๋ฉํฑ ํ๊ทธ๋ฅผ ์ฌ์ฉํด๋ณด๋ฉด ์ข์ ๋ฏ! |
@@ -1,8 +1,43 @@
-import './Main.scss';
+import { useState, useEffect } from 'react';
+import Nav from '../../../components/Nav/Nav';
+import Feed from './Feed';
+import MainRight from './MainRight';
import '../../../styles/variables.scss';
+import './Main.scss';
function Main() {
- return <></>;
+ const [articles, setArticles] = useState([]);
+
+ useEffect(() => {
+ fetch('http://localhost:3000/data/younghyunHan/feedData.json')
+ .then(res => res.json())
+ .then(data => {
+ setArticles(data);
+ });
+ }, []);
+
+ return (
+ <div className="main">
+ <Nav />
+ <main>
+ <div className="feeds">
+ {articles.map((content, index) => {
+ return (
+ <div key={index}>
+ <Feed
+ userName={content.userName}
+ feedImg={content.feedImg}
+ userMan={content.userMan}
+ profileLogo={content.profileLogo}
+ />
+ </div>
+ );
+ })}
+ </div>
+ <MainRight />
+ </main>
+ </div>
+ );
}
export default Main; | JavaScript | ๊ฐ ๋ฉ๋ด๋ฅผ JS ํ์ผ์ ์ ์ฅํ๊ณ ,
map ๋ฉ์๋๋ก ์ถ๋ ฅํด์ฃผ๋ ๋ฐฉ์์ผ๋ก ์์ ํด๋ณด๋ฉด ์ข์ ๋ฏํด์ฉ |
@@ -0,0 +1,16 @@
+.main {
+ background-color: #fafafa;
+
+ main {
+ display: flex;
+ justify-content: center;
+ align-items: flex-start;
+ margin: 0px 8px 8px 8px;
+
+ .feeds {
+ width: 750px;
+ padding-top: 80px;
+ padding-bottom: 30px;
+ }
+ }
+} | Unknown | ์ด๋ฐ ์ ํ์ ํ์ฉ์ผ๋ก ์คํฌ๋กค ๊ฐ์ถ์ ๋ถ๋ถ ์ข๋ค์.. |
@@ -1,8 +1,43 @@
-import './Main.scss';
+import { useState, useEffect } from 'react';
+import Nav from '../../../components/Nav/Nav';
+import Feed from './Feed';
+import MainRight from './MainRight';
import '../../../styles/variables.scss';
+import './Main.scss';
function Main() {
- return <></>;
+ const [articles, setArticles] = useState([]);
+
+ useEffect(() => {
+ fetch('http://localhost:3000/data/younghyunHan/feedData.json')
+ .then(res => res.json())
+ .then(data => {
+ setArticles(data);
+ });
+ }, []);
+
+ return (
+ <div className="main">
+ <Nav />
+ <main>
+ <div className="feeds">
+ {articles.map((content, index) => {
+ return (
+ <div key={index}>
+ <Feed
+ userName={content.userName}
+ feedImg={content.feedImg}
+ userMan={content.userMan}
+ profileLogo={content.profileLogo}
+ />
+ </div>
+ );
+ })}
+ </div>
+ <MainRight />
+ </main>
+ </div>
+ );
}
export default Main; | JavaScript | feedcontainer ์ feed |
@@ -1,7 +1,49 @@
import './Nav.scss';
+import '../../styles/variables.scss';
+import { Link } from 'react-router-dom';
function Nav() {
- return <></>;
+ return (
+ <div className="nav">
+ <nav className="navbar">
+ <div className="navbarLeft1">
+ <div className="navbarLeft1Inner">
+ <Link to="/" className="navbarItem logoImg">
+ <img alt="logoIcon" className="navIcon" src="/images/logo.png" />
+ </Link>
+ <Link to="/" className="navbarItem logoFont">
+ Westagram
+ </Link>
+ </div>
+ </div>
+ <div className="navbarLeft2">
+ <div className="searchWrapper navbarItem">
+ <img alt="searchIcon" src="/images/search.png" />
+ <input placeholder="๊ฒ์" />
+ </div>
+ </div>
+ <div className="navbarRight">
+ <Link to="/" className="navbarItem">
+ <img
+ alt="exploreIcon"
+ className="navIcon"
+ src="/images/explore.png"
+ />
+ </Link>
+ <Link to="/" className="navbarItem">
+ <img alt="heartIcon" className="navIcon" src="/images/heart.png" />
+ </Link>
+ <Link to="/" className="navbarItem">
+ <img
+ alt="profileIcon"
+ className="navIcon"
+ src="/images/profile.png"
+ />
+ </Link>
+ </div>
+ </nav>
+ </div>
+ );
}
export default Nav; | JavaScript | ๊ณตํต ํ์ผ |
@@ -1,7 +1,128 @@
+import { useNavigate } from 'react-router-dom';
+import { useState } from 'react';
import './Login.scss';
function Login() {
- return <></>;
+ // const [idState, setIdState] = useState('');
+ // const [passwordValue, setPasswordValue] = useState('');
+ // const [disabled, setDisabled] = useState(true);
+ // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' });
+
+ const navigate = useNavigate();
+ const [loginValues, setLoginValues] = useState({
+ id: '',
+ password: '',
+ });
+
+ const handleInputValue = e => {
+ const { name, value } = e.target;
+ setLoginValues({ ...loginValues, [name]: value });
+ };
+
+ // const { type, value } = event.target;
+
+ // function handleLogin(event) {
+ // if (type === 'text') {
+ // setIdState(value);
+ // } else if (type === 'password') {
+ // setPasswordValue(value);
+ // }
+ // handleButton();
+ // }
+
+ // const checkId = idValue => {
+ // return idValue.includes('@') ? true : false;
+ // };
+
+ // const checkPw = pwValue => {
+ // return pwValue.length >= 5 ? true : false;
+ // };
+
+ // const handleButton = () => {
+ // const isValidId = checkId(state);
+ // const isValidPw = checkPw(passwordValue);
+
+ // if (isValidId && isValidPw) {
+ // buttonColor(true);
+ // } else {
+ // buttonColor(false);
+ // }
+ // };
+
+ // const buttonColor = btnValid => {
+ // setDisabled(!btnValid);
+ // setStyle({
+ // opacity: btnValid ? 1 : 0.5,
+ // cursor: btnValid ? 'pointer' : 'default',
+ // });
+ // };
+
+ const goToMain = () => {
+ fetch('http://10.58.4.238:8000/users/login', {
+ method: 'POST',
+ body: JSON.stringify({
+ email: loginValues.id,
+ password: loginValues.password,
+ // name: '๋์',
+ // phone_number: '010-1111-111',
+ }),
+ })
+ .then(response => response.json())
+ .then(result => {
+ // console.log(result);
+ if (result.token) {
+ //localStorage.setItem('token', result.token);
+ alert('ํ์ํฉ๋๋ค!');
+ navigate('/main-han');
+ } else if (result.message === 'INVALID_USER') {
+ alert('ID์ PW๋ฅผ ํ์ธํด์ฃผ์ธ์.');
+ }
+ });
+ };
+
+ const isInputValid =
+ loginValues.id.includes('@') &&
+ loginValues.id.length >= 6 &&
+ loginValues.password.length >= 6;
+ // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6);
+ // console.log(loginValues.password.length >= 6);
+ // console.log(isInputValid);
+
+ return (
+ <div className="login">
+ <form className="loginBox">
+ <h1>Westagram</h1>
+ <input
+ id="id"
+ name="id"
+ className="userId"
+ type="text"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ onChange={handleInputValue}
+ />
+ <input
+ id="password"
+ name="password"
+ className="userPassword"
+ type="password"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ onChange={handleInputValue}
+ />
+ <button
+ type="button"
+ className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`}
+ onClick={goToMain}
+ disabled={!isInputValid}
+ //style={style}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <div className="findPassword">
+ <a href="#">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</a>
+ </div>
+ </form>
+ </div>
+ );
}
export default Login; | JavaScript | state๋ผ๋ ๋ช
์นญ์ด ๋ฌด์จ ๋ฐ์ดํฐ๋ฅผ ๊ด๋ฆฌํ๋์ง ์ ์ ์์. ๋ช
ํํ ๋ช
์นญ์ผ๋ก ์์ |
@@ -1,7 +1,128 @@
+import { useNavigate } from 'react-router-dom';
+import { useState } from 'react';
import './Login.scss';
function Login() {
- return <></>;
+ // const [idState, setIdState] = useState('');
+ // const [passwordValue, setPasswordValue] = useState('');
+ // const [disabled, setDisabled] = useState(true);
+ // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' });
+
+ const navigate = useNavigate();
+ const [loginValues, setLoginValues] = useState({
+ id: '',
+ password: '',
+ });
+
+ const handleInputValue = e => {
+ const { name, value } = e.target;
+ setLoginValues({ ...loginValues, [name]: value });
+ };
+
+ // const { type, value } = event.target;
+
+ // function handleLogin(event) {
+ // if (type === 'text') {
+ // setIdState(value);
+ // } else if (type === 'password') {
+ // setPasswordValue(value);
+ // }
+ // handleButton();
+ // }
+
+ // const checkId = idValue => {
+ // return idValue.includes('@') ? true : false;
+ // };
+
+ // const checkPw = pwValue => {
+ // return pwValue.length >= 5 ? true : false;
+ // };
+
+ // const handleButton = () => {
+ // const isValidId = checkId(state);
+ // const isValidPw = checkPw(passwordValue);
+
+ // if (isValidId && isValidPw) {
+ // buttonColor(true);
+ // } else {
+ // buttonColor(false);
+ // }
+ // };
+
+ // const buttonColor = btnValid => {
+ // setDisabled(!btnValid);
+ // setStyle({
+ // opacity: btnValid ? 1 : 0.5,
+ // cursor: btnValid ? 'pointer' : 'default',
+ // });
+ // };
+
+ const goToMain = () => {
+ fetch('http://10.58.4.238:8000/users/login', {
+ method: 'POST',
+ body: JSON.stringify({
+ email: loginValues.id,
+ password: loginValues.password,
+ // name: '๋์',
+ // phone_number: '010-1111-111',
+ }),
+ })
+ .then(response => response.json())
+ .then(result => {
+ // console.log(result);
+ if (result.token) {
+ //localStorage.setItem('token', result.token);
+ alert('ํ์ํฉ๋๋ค!');
+ navigate('/main-han');
+ } else if (result.message === 'INVALID_USER') {
+ alert('ID์ PW๋ฅผ ํ์ธํด์ฃผ์ธ์.');
+ }
+ });
+ };
+
+ const isInputValid =
+ loginValues.id.includes('@') &&
+ loginValues.id.length >= 6 &&
+ loginValues.password.length >= 6;
+ // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6);
+ // console.log(loginValues.password.length >= 6);
+ // console.log(isInputValid);
+
+ return (
+ <div className="login">
+ <form className="loginBox">
+ <h1>Westagram</h1>
+ <input
+ id="id"
+ name="id"
+ className="userId"
+ type="text"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ onChange={handleInputValue}
+ />
+ <input
+ id="password"
+ name="password"
+ className="userPassword"
+ type="password"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ onChange={handleInputValue}
+ />
+ <button
+ type="button"
+ className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`}
+ onClick={goToMain}
+ disabled={!isInputValid}
+ //style={style}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <div className="findPassword">
+ <a href="#">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</a>
+ </div>
+ </form>
+ </div>
+ );
}
export default Login; | JavaScript | disabled, style ๋ฑ์ state๋ก ๋ง๋ค ํ์ ์์.
[๋ฆฌ์กํธ๋ก ์ฌ๊ณ ํ๊ธฐ](https://ko.reactjs.org/docs/thinking-in-react.html) ์ฐธ๊ณ
1. ๋ถ๋ชจ๋ก๋ถํฐ props๋ฅผ ํตํด ์ ๋ฌ๋ฉ๋๊น? ๊ทธ๋ฌ๋ฉด ํ์คํ state๊ฐ ์๋๋๋ค.
2. ์๊ฐ์ด ์ง๋๋ ๋ณํ์ง ์๋์? ๊ทธ๋ฌ๋ฉด ํ์คํ state๊ฐ ์๋๋๋ค.
3. ์ปดํฌ๋ํธ ์์ ๋ค๋ฅธ state๋ props๋ฅผ ๊ฐ์ง๊ณ ๊ณ์ฐ ๊ฐ๋ฅํ๊ฐ์? ๊ทธ๋ ๋ค๋ฉด state๊ฐ ์๋๋๋ค. |
@@ -1,7 +1,128 @@
+import { useNavigate } from 'react-router-dom';
+import { useState } from 'react';
import './Login.scss';
function Login() {
- return <></>;
+ // const [idState, setIdState] = useState('');
+ // const [passwordValue, setPasswordValue] = useState('');
+ // const [disabled, setDisabled] = useState(true);
+ // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' });
+
+ const navigate = useNavigate();
+ const [loginValues, setLoginValues] = useState({
+ id: '',
+ password: '',
+ });
+
+ const handleInputValue = e => {
+ const { name, value } = e.target;
+ setLoginValues({ ...loginValues, [name]: value });
+ };
+
+ // const { type, value } = event.target;
+
+ // function handleLogin(event) {
+ // if (type === 'text') {
+ // setIdState(value);
+ // } else if (type === 'password') {
+ // setPasswordValue(value);
+ // }
+ // handleButton();
+ // }
+
+ // const checkId = idValue => {
+ // return idValue.includes('@') ? true : false;
+ // };
+
+ // const checkPw = pwValue => {
+ // return pwValue.length >= 5 ? true : false;
+ // };
+
+ // const handleButton = () => {
+ // const isValidId = checkId(state);
+ // const isValidPw = checkPw(passwordValue);
+
+ // if (isValidId && isValidPw) {
+ // buttonColor(true);
+ // } else {
+ // buttonColor(false);
+ // }
+ // };
+
+ // const buttonColor = btnValid => {
+ // setDisabled(!btnValid);
+ // setStyle({
+ // opacity: btnValid ? 1 : 0.5,
+ // cursor: btnValid ? 'pointer' : 'default',
+ // });
+ // };
+
+ const goToMain = () => {
+ fetch('http://10.58.4.238:8000/users/login', {
+ method: 'POST',
+ body: JSON.stringify({
+ email: loginValues.id,
+ password: loginValues.password,
+ // name: '๋์',
+ // phone_number: '010-1111-111',
+ }),
+ })
+ .then(response => response.json())
+ .then(result => {
+ // console.log(result);
+ if (result.token) {
+ //localStorage.setItem('token', result.token);
+ alert('ํ์ํฉ๋๋ค!');
+ navigate('/main-han');
+ } else if (result.message === 'INVALID_USER') {
+ alert('ID์ PW๋ฅผ ํ์ธํด์ฃผ์ธ์.');
+ }
+ });
+ };
+
+ const isInputValid =
+ loginValues.id.includes('@') &&
+ loginValues.id.length >= 6 &&
+ loginValues.password.length >= 6;
+ // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6);
+ // console.log(loginValues.password.length >= 6);
+ // console.log(isInputValid);
+
+ return (
+ <div className="login">
+ <form className="loginBox">
+ <h1>Westagram</h1>
+ <input
+ id="id"
+ name="id"
+ className="userId"
+ type="text"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ onChange={handleInputValue}
+ />
+ <input
+ id="password"
+ name="password"
+ className="userPassword"
+ type="password"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ onChange={handleInputValue}
+ />
+ <button
+ type="button"
+ className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`}
+ onClick={goToMain}
+ disabled={!isInputValid}
+ //style={style}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <div className="findPassword">
+ <a href="#">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</a>
+ </div>
+ </form>
+ </div>
+ );
}
export default Login; | JavaScript | - ๊ธฐ๋ฅ์ ํจ์๋ก ๋ถ๋ฆฌํ๋ ๋ถ๋ถ์ ์ข์
- ์ผํญ์ฐ์ฐ์๋ก ์ฌ์ฉํ ํ์ ์์ด, ์กฐ๊ฑด ์์ฒด๋ก boolean์ด ๋ ์ ์์
```suggestion
const checkId = idValue => {
return idValue.includes('@');
};
const checkPw = pwValue => {
return pwValue.length >= 5;
};
```
- ์ถ๊ฐ์ ์ผ๋ก,
```js
const isInputValid = idValue.includes('@') && pwValue.length >= 5
```
์ด๋ฐ ์์ผ๋ก ํ๊บผ๋ฒ์ ๋ณ์๋ก ๋ง๋ค์ด ์ฒ๋ฆฌํ ์๋ ์์ |
@@ -1,7 +1,128 @@
+import { useNavigate } from 'react-router-dom';
+import { useState } from 'react';
import './Login.scss';
function Login() {
- return <></>;
+ // const [idState, setIdState] = useState('');
+ // const [passwordValue, setPasswordValue] = useState('');
+ // const [disabled, setDisabled] = useState(true);
+ // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' });
+
+ const navigate = useNavigate();
+ const [loginValues, setLoginValues] = useState({
+ id: '',
+ password: '',
+ });
+
+ const handleInputValue = e => {
+ const { name, value } = e.target;
+ setLoginValues({ ...loginValues, [name]: value });
+ };
+
+ // const { type, value } = event.target;
+
+ // function handleLogin(event) {
+ // if (type === 'text') {
+ // setIdState(value);
+ // } else if (type === 'password') {
+ // setPasswordValue(value);
+ // }
+ // handleButton();
+ // }
+
+ // const checkId = idValue => {
+ // return idValue.includes('@') ? true : false;
+ // };
+
+ // const checkPw = pwValue => {
+ // return pwValue.length >= 5 ? true : false;
+ // };
+
+ // const handleButton = () => {
+ // const isValidId = checkId(state);
+ // const isValidPw = checkPw(passwordValue);
+
+ // if (isValidId && isValidPw) {
+ // buttonColor(true);
+ // } else {
+ // buttonColor(false);
+ // }
+ // };
+
+ // const buttonColor = btnValid => {
+ // setDisabled(!btnValid);
+ // setStyle({
+ // opacity: btnValid ? 1 : 0.5,
+ // cursor: btnValid ? 'pointer' : 'default',
+ // });
+ // };
+
+ const goToMain = () => {
+ fetch('http://10.58.4.238:8000/users/login', {
+ method: 'POST',
+ body: JSON.stringify({
+ email: loginValues.id,
+ password: loginValues.password,
+ // name: '๋์',
+ // phone_number: '010-1111-111',
+ }),
+ })
+ .then(response => response.json())
+ .then(result => {
+ // console.log(result);
+ if (result.token) {
+ //localStorage.setItem('token', result.token);
+ alert('ํ์ํฉ๋๋ค!');
+ navigate('/main-han');
+ } else if (result.message === 'INVALID_USER') {
+ alert('ID์ PW๋ฅผ ํ์ธํด์ฃผ์ธ์.');
+ }
+ });
+ };
+
+ const isInputValid =
+ loginValues.id.includes('@') &&
+ loginValues.id.length >= 6 &&
+ loginValues.password.length >= 6;
+ // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6);
+ // console.log(loginValues.password.length >= 6);
+ // console.log(isInputValid);
+
+ return (
+ <div className="login">
+ <form className="loginBox">
+ <h1>Westagram</h1>
+ <input
+ id="id"
+ name="id"
+ className="userId"
+ type="text"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ onChange={handleInputValue}
+ />
+ <input
+ id="password"
+ name="password"
+ className="userPassword"
+ type="password"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ onChange={handleInputValue}
+ />
+ <button
+ type="button"
+ className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`}
+ onClick={goToMain}
+ disabled={!isInputValid}
+ //style={style}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <div className="findPassword">
+ <a href="#">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</a>
+ </div>
+ </form>
+ </div>
+ );
}
export default Login; | JavaScript | ๋ช
์นญ๋ง ๋ดค์ ๋๋ id ๋ถ๋ถ๋ง ๊ด๋ฆฌํ๋ ํจ์์ธ ๊ฒ ๊ฐ์๋ฐ, ๋์์ ๋ณด๋ฉด ์๋. ์์ |
@@ -1,7 +1,128 @@
+import { useNavigate } from 'react-router-dom';
+import { useState } from 'react';
import './Login.scss';
function Login() {
- return <></>;
+ // const [idState, setIdState] = useState('');
+ // const [passwordValue, setPasswordValue] = useState('');
+ // const [disabled, setDisabled] = useState(true);
+ // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' });
+
+ const navigate = useNavigate();
+ const [loginValues, setLoginValues] = useState({
+ id: '',
+ password: '',
+ });
+
+ const handleInputValue = e => {
+ const { name, value } = e.target;
+ setLoginValues({ ...loginValues, [name]: value });
+ };
+
+ // const { type, value } = event.target;
+
+ // function handleLogin(event) {
+ // if (type === 'text') {
+ // setIdState(value);
+ // } else if (type === 'password') {
+ // setPasswordValue(value);
+ // }
+ // handleButton();
+ // }
+
+ // const checkId = idValue => {
+ // return idValue.includes('@') ? true : false;
+ // };
+
+ // const checkPw = pwValue => {
+ // return pwValue.length >= 5 ? true : false;
+ // };
+
+ // const handleButton = () => {
+ // const isValidId = checkId(state);
+ // const isValidPw = checkPw(passwordValue);
+
+ // if (isValidId && isValidPw) {
+ // buttonColor(true);
+ // } else {
+ // buttonColor(false);
+ // }
+ // };
+
+ // const buttonColor = btnValid => {
+ // setDisabled(!btnValid);
+ // setStyle({
+ // opacity: btnValid ? 1 : 0.5,
+ // cursor: btnValid ? 'pointer' : 'default',
+ // });
+ // };
+
+ const goToMain = () => {
+ fetch('http://10.58.4.238:8000/users/login', {
+ method: 'POST',
+ body: JSON.stringify({
+ email: loginValues.id,
+ password: loginValues.password,
+ // name: '๋์',
+ // phone_number: '010-1111-111',
+ }),
+ })
+ .then(response => response.json())
+ .then(result => {
+ // console.log(result);
+ if (result.token) {
+ //localStorage.setItem('token', result.token);
+ alert('ํ์ํฉ๋๋ค!');
+ navigate('/main-han');
+ } else if (result.message === 'INVALID_USER') {
+ alert('ID์ PW๋ฅผ ํ์ธํด์ฃผ์ธ์.');
+ }
+ });
+ };
+
+ const isInputValid =
+ loginValues.id.includes('@') &&
+ loginValues.id.length >= 6 &&
+ loginValues.password.length >= 6;
+ // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6);
+ // console.log(loginValues.password.length >= 6);
+ // console.log(isInputValid);
+
+ return (
+ <div className="login">
+ <form className="loginBox">
+ <h1>Westagram</h1>
+ <input
+ id="id"
+ name="id"
+ className="userId"
+ type="text"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ onChange={handleInputValue}
+ />
+ <input
+ id="password"
+ name="password"
+ className="userPassword"
+ type="password"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ onChange={handleInputValue}
+ />
+ <button
+ type="button"
+ className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`}
+ onClick={goToMain}
+ disabled={!isInputValid}
+ //style={style}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <div className="findPassword">
+ <a href="#">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</a>
+ </div>
+ </form>
+ </div>
+ );
}
export default Login; | JavaScript | ๊ตฌ์กฐ๋ถํดํ ๋น!
```suggestion
const { type, value } = event.target;
if (type === 'text') {
setState(value);
} else if (type === 'password') {
setPasswordValue(value);
}
``` |
@@ -1,7 +1,128 @@
+import { useNavigate } from 'react-router-dom';
+import { useState } from 'react';
import './Login.scss';
function Login() {
- return <></>;
+ // const [idState, setIdState] = useState('');
+ // const [passwordValue, setPasswordValue] = useState('');
+ // const [disabled, setDisabled] = useState(true);
+ // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' });
+
+ const navigate = useNavigate();
+ const [loginValues, setLoginValues] = useState({
+ id: '',
+ password: '',
+ });
+
+ const handleInputValue = e => {
+ const { name, value } = e.target;
+ setLoginValues({ ...loginValues, [name]: value });
+ };
+
+ // const { type, value } = event.target;
+
+ // function handleLogin(event) {
+ // if (type === 'text') {
+ // setIdState(value);
+ // } else if (type === 'password') {
+ // setPasswordValue(value);
+ // }
+ // handleButton();
+ // }
+
+ // const checkId = idValue => {
+ // return idValue.includes('@') ? true : false;
+ // };
+
+ // const checkPw = pwValue => {
+ // return pwValue.length >= 5 ? true : false;
+ // };
+
+ // const handleButton = () => {
+ // const isValidId = checkId(state);
+ // const isValidPw = checkPw(passwordValue);
+
+ // if (isValidId && isValidPw) {
+ // buttonColor(true);
+ // } else {
+ // buttonColor(false);
+ // }
+ // };
+
+ // const buttonColor = btnValid => {
+ // setDisabled(!btnValid);
+ // setStyle({
+ // opacity: btnValid ? 1 : 0.5,
+ // cursor: btnValid ? 'pointer' : 'default',
+ // });
+ // };
+
+ const goToMain = () => {
+ fetch('http://10.58.4.238:8000/users/login', {
+ method: 'POST',
+ body: JSON.stringify({
+ email: loginValues.id,
+ password: loginValues.password,
+ // name: '๋์',
+ // phone_number: '010-1111-111',
+ }),
+ })
+ .then(response => response.json())
+ .then(result => {
+ // console.log(result);
+ if (result.token) {
+ //localStorage.setItem('token', result.token);
+ alert('ํ์ํฉ๋๋ค!');
+ navigate('/main-han');
+ } else if (result.message === 'INVALID_USER') {
+ alert('ID์ PW๋ฅผ ํ์ธํด์ฃผ์ธ์.');
+ }
+ });
+ };
+
+ const isInputValid =
+ loginValues.id.includes('@') &&
+ loginValues.id.length >= 6 &&
+ loginValues.password.length >= 6;
+ // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6);
+ // console.log(loginValues.password.length >= 6);
+ // console.log(isInputValid);
+
+ return (
+ <div className="login">
+ <form className="loginBox">
+ <h1>Westagram</h1>
+ <input
+ id="id"
+ name="id"
+ className="userId"
+ type="text"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ onChange={handleInputValue}
+ />
+ <input
+ id="password"
+ name="password"
+ className="userPassword"
+ type="password"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ onChange={handleInputValue}
+ />
+ <button
+ type="button"
+ className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`}
+ onClick={goToMain}
+ disabled={!isInputValid}
+ //style={style}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <div className="findPassword">
+ <a href="#">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</a>
+ </div>
+ </form>
+ </div>
+ );
}
export default Login; | JavaScript | JS๋ก ๊ตฌํํ๋ ๋ฐฉ์ ๊ทธ๋๋ก ํ์
จ๋๋ฐ, ๊ธฐ์กด state๋ก ๊ณ์ฐ์ด ๊ฐ๋ฅํ๊ธฐ ๋๋ฌธ์ ๋ถํ์ํ state |
@@ -1,7 +1,128 @@
+import { useNavigate } from 'react-router-dom';
+import { useState } from 'react';
import './Login.scss';
function Login() {
- return <></>;
+ // const [idState, setIdState] = useState('');
+ // const [passwordValue, setPasswordValue] = useState('');
+ // const [disabled, setDisabled] = useState(true);
+ // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' });
+
+ const navigate = useNavigate();
+ const [loginValues, setLoginValues] = useState({
+ id: '',
+ password: '',
+ });
+
+ const handleInputValue = e => {
+ const { name, value } = e.target;
+ setLoginValues({ ...loginValues, [name]: value });
+ };
+
+ // const { type, value } = event.target;
+
+ // function handleLogin(event) {
+ // if (type === 'text') {
+ // setIdState(value);
+ // } else if (type === 'password') {
+ // setPasswordValue(value);
+ // }
+ // handleButton();
+ // }
+
+ // const checkId = idValue => {
+ // return idValue.includes('@') ? true : false;
+ // };
+
+ // const checkPw = pwValue => {
+ // return pwValue.length >= 5 ? true : false;
+ // };
+
+ // const handleButton = () => {
+ // const isValidId = checkId(state);
+ // const isValidPw = checkPw(passwordValue);
+
+ // if (isValidId && isValidPw) {
+ // buttonColor(true);
+ // } else {
+ // buttonColor(false);
+ // }
+ // };
+
+ // const buttonColor = btnValid => {
+ // setDisabled(!btnValid);
+ // setStyle({
+ // opacity: btnValid ? 1 : 0.5,
+ // cursor: btnValid ? 'pointer' : 'default',
+ // });
+ // };
+
+ const goToMain = () => {
+ fetch('http://10.58.4.238:8000/users/login', {
+ method: 'POST',
+ body: JSON.stringify({
+ email: loginValues.id,
+ password: loginValues.password,
+ // name: '๋์',
+ // phone_number: '010-1111-111',
+ }),
+ })
+ .then(response => response.json())
+ .then(result => {
+ // console.log(result);
+ if (result.token) {
+ //localStorage.setItem('token', result.token);
+ alert('ํ์ํฉ๋๋ค!');
+ navigate('/main-han');
+ } else if (result.message === 'INVALID_USER') {
+ alert('ID์ PW๋ฅผ ํ์ธํด์ฃผ์ธ์.');
+ }
+ });
+ };
+
+ const isInputValid =
+ loginValues.id.includes('@') &&
+ loginValues.id.length >= 6 &&
+ loginValues.password.length >= 6;
+ // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6);
+ // console.log(loginValues.password.length >= 6);
+ // console.log(isInputValid);
+
+ return (
+ <div className="login">
+ <form className="loginBox">
+ <h1>Westagram</h1>
+ <input
+ id="id"
+ name="id"
+ className="userId"
+ type="text"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ onChange={handleInputValue}
+ />
+ <input
+ id="password"
+ name="password"
+ className="userPassword"
+ type="password"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ onChange={handleInputValue}
+ />
+ <button
+ type="button"
+ className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`}
+ onClick={goToMain}
+ disabled={!isInputValid}
+ //style={style}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <div className="findPassword">
+ <a href="#">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</a>
+ </div>
+ </form>
+ </div>
+ );
}
export default Login; | JavaScript | ๊นํ์ง ๋ฉํ ๋ ๋ฆฌ๋ทฐ ๋ฐ์ํ๊ธฐ |
@@ -1,7 +1,128 @@
+import { useNavigate } from 'react-router-dom';
+import { useState } from 'react';
import './Login.scss';
function Login() {
- return <></>;
+ // const [idState, setIdState] = useState('');
+ // const [passwordValue, setPasswordValue] = useState('');
+ // const [disabled, setDisabled] = useState(true);
+ // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' });
+
+ const navigate = useNavigate();
+ const [loginValues, setLoginValues] = useState({
+ id: '',
+ password: '',
+ });
+
+ const handleInputValue = e => {
+ const { name, value } = e.target;
+ setLoginValues({ ...loginValues, [name]: value });
+ };
+
+ // const { type, value } = event.target;
+
+ // function handleLogin(event) {
+ // if (type === 'text') {
+ // setIdState(value);
+ // } else if (type === 'password') {
+ // setPasswordValue(value);
+ // }
+ // handleButton();
+ // }
+
+ // const checkId = idValue => {
+ // return idValue.includes('@') ? true : false;
+ // };
+
+ // const checkPw = pwValue => {
+ // return pwValue.length >= 5 ? true : false;
+ // };
+
+ // const handleButton = () => {
+ // const isValidId = checkId(state);
+ // const isValidPw = checkPw(passwordValue);
+
+ // if (isValidId && isValidPw) {
+ // buttonColor(true);
+ // } else {
+ // buttonColor(false);
+ // }
+ // };
+
+ // const buttonColor = btnValid => {
+ // setDisabled(!btnValid);
+ // setStyle({
+ // opacity: btnValid ? 1 : 0.5,
+ // cursor: btnValid ? 'pointer' : 'default',
+ // });
+ // };
+
+ const goToMain = () => {
+ fetch('http://10.58.4.238:8000/users/login', {
+ method: 'POST',
+ body: JSON.stringify({
+ email: loginValues.id,
+ password: loginValues.password,
+ // name: '๋์',
+ // phone_number: '010-1111-111',
+ }),
+ })
+ .then(response => response.json())
+ .then(result => {
+ // console.log(result);
+ if (result.token) {
+ //localStorage.setItem('token', result.token);
+ alert('ํ์ํฉ๋๋ค!');
+ navigate('/main-han');
+ } else if (result.message === 'INVALID_USER') {
+ alert('ID์ PW๋ฅผ ํ์ธํด์ฃผ์ธ์.');
+ }
+ });
+ };
+
+ const isInputValid =
+ loginValues.id.includes('@') &&
+ loginValues.id.length >= 6 &&
+ loginValues.password.length >= 6;
+ // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6);
+ // console.log(loginValues.password.length >= 6);
+ // console.log(isInputValid);
+
+ return (
+ <div className="login">
+ <form className="loginBox">
+ <h1>Westagram</h1>
+ <input
+ id="id"
+ name="id"
+ className="userId"
+ type="text"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ onChange={handleInputValue}
+ />
+ <input
+ id="password"
+ name="password"
+ className="userPassword"
+ type="password"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ onChange={handleInputValue}
+ />
+ <button
+ type="button"
+ className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`}
+ onClick={goToMain}
+ disabled={!isInputValid}
+ //style={style}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <div className="findPassword">
+ <a href="#">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</a>
+ </div>
+ </form>
+ </div>
+ );
}
export default Login; | JavaScript | +์ผํญ์ฐ์ฐ์์ ์กฐ๊ฑด์ ์ ๋ฆฌ๋ทฐ์ฒ๋ผ ๋ณ์๋ก ๋ง๋ค์ด์ ์ฌ์ฉํ๊ธฐ |
@@ -0,0 +1,14 @@
+import './Comment.scss';
+
+function Comment({ userName, content }) {
+ return (
+ <div className="comment">
+ <p>
+ <strong className="commentMan">{userName}</strong>
+ {content}
+ </p>
+ </div>
+ );
+}
+
+export default Comment; | JavaScript | ๋งค๊ฐ๋ณ์ ์๋ฆฌ์์ ๊ตฌ์กฐ๋ถํดํ ๋น ๊ตณ |
@@ -0,0 +1,102 @@
+import { useState, useEffect } from 'react';
+import './Feed.scss';
+import Comment from './Comment';
+
+function Feed(props) {
+ const [comment, setComment] = useState('');
+ const [addCommentList, setAddCommentList] = useState([]);
+ const [cmtContList, setCmtContList] = useState([]);
+ const userName = 'test01';
+
+ const onChange = event => {
+ setComment(event.target.value);
+ };
+
+ const addComment = event => {
+ event.preventDefault();
+ setAddCommentList([
+ ...addCommentList,
+ {
+ name: userName,
+ content: comment,
+ },
+ ]);
+ setComment('');
+ };
+
+ useEffect(() => {
+ fetch('http://localhost:3000/data/younghyunHan/commentData.json')
+ .then(res => res.json())
+ .then(data => {
+ setCmtContList(data);
+ });
+ }, []);
+
+ return (
+ <article className="feed">
+ <div className="feedTop">
+ <div className="feedTopOne">
+ <div className="profileLogo">
+ <img className="profileLogoImg" src={props.profileLogo} />
+ </div>
+ <div className="profileName">
+ <div className="profileNameOne">{props.userName}</div>
+ <span className="profileNameTwo">Wecode - ์์ฝ๋</span>
+ </div>
+ </div>
+ <i className="fas fa-ellipsis-h" />
+ </div>
+ <img alt="ํผ๋ ์ด๋ฏธ์ง" className="feedImg" src={props.feedImg} />
+ <div className="feedThree">
+ <div>
+ <i className="far fa-heart" />
+ <i className="far fa-comment" />
+ <i className="fas fa-upload" />
+ </div>
+ <i className="far fa-bookmark" />
+ </div>
+ <div className="feedFour">
+ <img alt="์ข์์ ๋๋ฅธ ์ฌ๋" className="man" src={props.userMan} />
+ <span className="feedFourWord">seungyoun_iain</span>
+ ์ธ
+ <span className="feedFourWordTwo">4๋ช
</span>์ด ์ข์ํฉ๋๋ค.
+ </div>
+ <div className="feedFive">
+ <span className="feedFiveWord">wecode_bootcamp</span>"์์ฝ๋๋ ๋จ์
+ ๊ต์ก์
์ฒด๊ฐ ์๋ ๊ฐ๋ฐ์ ์ปค๋ฎค๋ํฐ์
๋๋ค. Wecode์์ ๋ฐฐ์ฐ๊ณ ์ ๋ ์ด 5๊ฐ
+ ํ์ฌ์์ ์คํผ๋ฅผ ๋ฐ์์ต๋๋ค.
+ </div>
+ <div className="comment">
+ {cmtContList.map(content => {
+ return (
+ <Comment
+ key={content.id}
+ userName={content.userName}
+ content={content.content}
+ />
+ );
+ })}
+ {addCommentList.map((content, index) => {
+ return (
+ <div key={index}>
+ <Comment content={content.content} userName={content.name} />
+ </div>
+ );
+ })}
+ </div>
+ <span className="postTime">54๋ถ ์ </span>
+ <form className="commentSection" onSubmit={addComment}>
+ <input
+ type="text"
+ placeholder="๋๊ธ ๋ฌ๊ธฐ..."
+ className="comment"
+ onChange={onChange}
+ value={comment}
+ />
+ <button className="postButton">๊ฒ์</button>
+ </form>
+ </article>
+ );
+}
+
+export default Feed; | JavaScript | - ์ฌํ ๋น๋์ง ์๋ ๋ณ์๋ const๋ก ์ ์ธํ๊ธฐ
- ์ด ๋ถ๋ถ์ ๋ณ์ ์ ์ธ๋ณด๋จ ๊ตฌ์กฐ๋ถํดํ ๋น ์ ์ฉํ๊ธฐ |
@@ -0,0 +1,102 @@
+import { useState, useEffect } from 'react';
+import './Feed.scss';
+import Comment from './Comment';
+
+function Feed(props) {
+ const [comment, setComment] = useState('');
+ const [addCommentList, setAddCommentList] = useState([]);
+ const [cmtContList, setCmtContList] = useState([]);
+ const userName = 'test01';
+
+ const onChange = event => {
+ setComment(event.target.value);
+ };
+
+ const addComment = event => {
+ event.preventDefault();
+ setAddCommentList([
+ ...addCommentList,
+ {
+ name: userName,
+ content: comment,
+ },
+ ]);
+ setComment('');
+ };
+
+ useEffect(() => {
+ fetch('http://localhost:3000/data/younghyunHan/commentData.json')
+ .then(res => res.json())
+ .then(data => {
+ setCmtContList(data);
+ });
+ }, []);
+
+ return (
+ <article className="feed">
+ <div className="feedTop">
+ <div className="feedTopOne">
+ <div className="profileLogo">
+ <img className="profileLogoImg" src={props.profileLogo} />
+ </div>
+ <div className="profileName">
+ <div className="profileNameOne">{props.userName}</div>
+ <span className="profileNameTwo">Wecode - ์์ฝ๋</span>
+ </div>
+ </div>
+ <i className="fas fa-ellipsis-h" />
+ </div>
+ <img alt="ํผ๋ ์ด๋ฏธ์ง" className="feedImg" src={props.feedImg} />
+ <div className="feedThree">
+ <div>
+ <i className="far fa-heart" />
+ <i className="far fa-comment" />
+ <i className="fas fa-upload" />
+ </div>
+ <i className="far fa-bookmark" />
+ </div>
+ <div className="feedFour">
+ <img alt="์ข์์ ๋๋ฅธ ์ฌ๋" className="man" src={props.userMan} />
+ <span className="feedFourWord">seungyoun_iain</span>
+ ์ธ
+ <span className="feedFourWordTwo">4๋ช
</span>์ด ์ข์ํฉ๋๋ค.
+ </div>
+ <div className="feedFive">
+ <span className="feedFiveWord">wecode_bootcamp</span>"์์ฝ๋๋ ๋จ์
+ ๊ต์ก์
์ฒด๊ฐ ์๋ ๊ฐ๋ฐ์ ์ปค๋ฎค๋ํฐ์
๋๋ค. Wecode์์ ๋ฐฐ์ฐ๊ณ ์ ๋ ์ด 5๊ฐ
+ ํ์ฌ์์ ์คํผ๋ฅผ ๋ฐ์์ต๋๋ค.
+ </div>
+ <div className="comment">
+ {cmtContList.map(content => {
+ return (
+ <Comment
+ key={content.id}
+ userName={content.userName}
+ content={content.content}
+ />
+ );
+ })}
+ {addCommentList.map((content, index) => {
+ return (
+ <div key={index}>
+ <Comment content={content.content} userName={content.name} />
+ </div>
+ );
+ })}
+ </div>
+ <span className="postTime">54๋ถ ์ </span>
+ <form className="commentSection" onSubmit={addComment}>
+ <input
+ type="text"
+ placeholder="๋๊ธ ๋ฌ๊ธฐ..."
+ className="comment"
+ onChange={onChange}
+ value={comment}
+ />
+ <button className="postButton">๊ฒ์</button>
+ </form>
+ </article>
+ );
+}
+
+export default Feed; | JavaScript | - input์ value๊ฐ ๋ค์ด์ค๋ ๋ถ๋ถ์ธ๋ฐ, ์ด๊ธฐ๊ฐ์ด string์ด ์๋ ๋ฐฐ์ด์ด ๋ค์ด์์
- cmtContents๋ผ๋ ๋ณ์๋ช
๊ณผ ๋ฐฐ์ด์ธ ์ด๊ธฐ๊ฐ์ ์กฐํฉ์ด ๋ฐฐ์ด ๋ฐ์ดํฐ๋ฅผ ์ฐ์์ํด
- ๋ช
ํํ์ง๋ง ๊ฐ๊ฒฐํ state๋ช
์ผ๋ก ์์ . ex) `comment` / `commentList` |
@@ -0,0 +1,102 @@
+import { useState, useEffect } from 'react';
+import './Feed.scss';
+import Comment from './Comment';
+
+function Feed(props) {
+ const [comment, setComment] = useState('');
+ const [addCommentList, setAddCommentList] = useState([]);
+ const [cmtContList, setCmtContList] = useState([]);
+ const userName = 'test01';
+
+ const onChange = event => {
+ setComment(event.target.value);
+ };
+
+ const addComment = event => {
+ event.preventDefault();
+ setAddCommentList([
+ ...addCommentList,
+ {
+ name: userName,
+ content: comment,
+ },
+ ]);
+ setComment('');
+ };
+
+ useEffect(() => {
+ fetch('http://localhost:3000/data/younghyunHan/commentData.json')
+ .then(res => res.json())
+ .then(data => {
+ setCmtContList(data);
+ });
+ }, []);
+
+ return (
+ <article className="feed">
+ <div className="feedTop">
+ <div className="feedTopOne">
+ <div className="profileLogo">
+ <img className="profileLogoImg" src={props.profileLogo} />
+ </div>
+ <div className="profileName">
+ <div className="profileNameOne">{props.userName}</div>
+ <span className="profileNameTwo">Wecode - ์์ฝ๋</span>
+ </div>
+ </div>
+ <i className="fas fa-ellipsis-h" />
+ </div>
+ <img alt="ํผ๋ ์ด๋ฏธ์ง" className="feedImg" src={props.feedImg} />
+ <div className="feedThree">
+ <div>
+ <i className="far fa-heart" />
+ <i className="far fa-comment" />
+ <i className="fas fa-upload" />
+ </div>
+ <i className="far fa-bookmark" />
+ </div>
+ <div className="feedFour">
+ <img alt="์ข์์ ๋๋ฅธ ์ฌ๋" className="man" src={props.userMan} />
+ <span className="feedFourWord">seungyoun_iain</span>
+ ์ธ
+ <span className="feedFourWordTwo">4๋ช
</span>์ด ์ข์ํฉ๋๋ค.
+ </div>
+ <div className="feedFive">
+ <span className="feedFiveWord">wecode_bootcamp</span>"์์ฝ๋๋ ๋จ์
+ ๊ต์ก์
์ฒด๊ฐ ์๋ ๊ฐ๋ฐ์ ์ปค๋ฎค๋ํฐ์
๋๋ค. Wecode์์ ๋ฐฐ์ฐ๊ณ ์ ๋ ์ด 5๊ฐ
+ ํ์ฌ์์ ์คํผ๋ฅผ ๋ฐ์์ต๋๋ค.
+ </div>
+ <div className="comment">
+ {cmtContList.map(content => {
+ return (
+ <Comment
+ key={content.id}
+ userName={content.userName}
+ content={content.content}
+ />
+ );
+ })}
+ {addCommentList.map((content, index) => {
+ return (
+ <div key={index}>
+ <Comment content={content.content} userName={content.name} />
+ </div>
+ );
+ })}
+ </div>
+ <span className="postTime">54๋ถ ์ </span>
+ <form className="commentSection" onSubmit={addComment}>
+ <input
+ type="text"
+ placeholder="๋๊ธ ๋ฌ๊ธฐ..."
+ className="comment"
+ onChange={onChange}
+ value={comment}
+ />
+ <button className="postButton">๊ฒ์</button>
+ </form>
+ </article>
+ );
+}
+
+export default Feed; | JavaScript | ํจ์๋ช
์์ !
- comment๋ฅผ ์ถ๊ฐํ๋ ์ญํ ์ ํ๋ ํจ์
- ์ํฐํค๋ฅผ ์ณค์ ๋ ์ ํจ์๋ฅผ ์คํ์ํค๋ ํจ์
๋ก ๋ถํ ํ๋ฉด ์ข์ ๋ฏ |
@@ -0,0 +1,102 @@
+import { useState, useEffect } from 'react';
+import './Feed.scss';
+import Comment from './Comment';
+
+function Feed(props) {
+ const [comment, setComment] = useState('');
+ const [addCommentList, setAddCommentList] = useState([]);
+ const [cmtContList, setCmtContList] = useState([]);
+ const userName = 'test01';
+
+ const onChange = event => {
+ setComment(event.target.value);
+ };
+
+ const addComment = event => {
+ event.preventDefault();
+ setAddCommentList([
+ ...addCommentList,
+ {
+ name: userName,
+ content: comment,
+ },
+ ]);
+ setComment('');
+ };
+
+ useEffect(() => {
+ fetch('http://localhost:3000/data/younghyunHan/commentData.json')
+ .then(res => res.json())
+ .then(data => {
+ setCmtContList(data);
+ });
+ }, []);
+
+ return (
+ <article className="feed">
+ <div className="feedTop">
+ <div className="feedTopOne">
+ <div className="profileLogo">
+ <img className="profileLogoImg" src={props.profileLogo} />
+ </div>
+ <div className="profileName">
+ <div className="profileNameOne">{props.userName}</div>
+ <span className="profileNameTwo">Wecode - ์์ฝ๋</span>
+ </div>
+ </div>
+ <i className="fas fa-ellipsis-h" />
+ </div>
+ <img alt="ํผ๋ ์ด๋ฏธ์ง" className="feedImg" src={props.feedImg} />
+ <div className="feedThree">
+ <div>
+ <i className="far fa-heart" />
+ <i className="far fa-comment" />
+ <i className="fas fa-upload" />
+ </div>
+ <i className="far fa-bookmark" />
+ </div>
+ <div className="feedFour">
+ <img alt="์ข์์ ๋๋ฅธ ์ฌ๋" className="man" src={props.userMan} />
+ <span className="feedFourWord">seungyoun_iain</span>
+ ์ธ
+ <span className="feedFourWordTwo">4๋ช
</span>์ด ์ข์ํฉ๋๋ค.
+ </div>
+ <div className="feedFive">
+ <span className="feedFiveWord">wecode_bootcamp</span>"์์ฝ๋๋ ๋จ์
+ ๊ต์ก์
์ฒด๊ฐ ์๋ ๊ฐ๋ฐ์ ์ปค๋ฎค๋ํฐ์
๋๋ค. Wecode์์ ๋ฐฐ์ฐ๊ณ ์ ๋ ์ด 5๊ฐ
+ ํ์ฌ์์ ์คํผ๋ฅผ ๋ฐ์์ต๋๋ค.
+ </div>
+ <div className="comment">
+ {cmtContList.map(content => {
+ return (
+ <Comment
+ key={content.id}
+ userName={content.userName}
+ content={content.content}
+ />
+ );
+ })}
+ {addCommentList.map((content, index) => {
+ return (
+ <div key={index}>
+ <Comment content={content.content} userName={content.name} />
+ </div>
+ );
+ })}
+ </div>
+ <span className="postTime">54๋ถ ์ </span>
+ <form className="commentSection" onSubmit={addComment}>
+ <input
+ type="text"
+ placeholder="๋๊ธ ๋ฌ๊ธฐ..."
+ className="comment"
+ onChange={onChange}
+ value={comment}
+ />
+ <button className="postButton">๊ฒ์</button>
+ </form>
+ </article>
+ );
+}
+
+export default Feed; | JavaScript | ๋์ผํ ์คํ์ผ์ ๊ฐ์ง๋ ๋ถ๋ถ์ธ๋ฐ, one two three ์ด๋ฐ ์์ผ๋ก ๋ํ๋ผ ํ์ ์์ด ๋ด์ฉ์ ํฌ๊ดํ๋ ๋ช
์นญ์ ๋์ผํ className์ผ๋ก ์ฌ์ฉ |
@@ -0,0 +1,132 @@
+.feed {
+ background-color: white;
+ margin-bottom: 50px;
+
+ .feedTop {
+ display: flex;
+ justify-content: space-between;
+ position: relative;
+ padding: 10px;
+
+ .feedTopOne {
+ display: flex;
+ align-items: center;
+
+ .profileLogo {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ height: 35px;
+ width: 35px;
+ margin-right: 10px;
+ color: white;
+ background-color: black;
+ border-radius: 50%;
+ font-size: 7px;
+ font-weight: bold;
+ overflow: hidden; // ๋ถ๋ชจ div๋งํผ ์ด๋ฏธ์ง ์๋ฆ
+
+ .profileLogoImg {
+ width: 100%;
+ height: 100%;
+ object-fit: cover; // ๊ฐ๋ก, ์ธ๋ก ๋น์จ์ด ์ ๋ง์ผ๋ฉด ๋ฑ ๋ง๊ฒ ์ ์ฐ๊ทธ๋ฌ์ง๊ฒ ๋ง์ถฐ์ค.
+ }
+ }
+
+ .profileNameOne {
+ margin-bottom: 0px;
+ font-size: 15px;
+ font-weight: bold;
+ }
+
+ .profileNameTwo {
+ color: #a3a49a;
+ font-size: 12px;
+ font-weight: bold;
+ }
+ }
+
+ .fa-ellipsis-h {
+ position: absolute;
+ right: 20px;
+ top: 20px;
+ }
+ }
+
+ .feedImg {
+ width: 100%;
+ height: 500px;
+ }
+
+ .feedThree {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ padding: 10px;
+ font-size: 25px;
+
+ .fa-heart,
+ .fa-comment {
+ margin-right: 10px;
+ }
+ }
+
+ .feedFour {
+ display: flex;
+ align-items: center;
+ padding: 0px 10px 10px 10px;
+
+ .man {
+ width: 20px;
+ height: 20px;
+ margin-right: 10px;
+ border-radius: 50%;
+ } // ์ ์ฝ๋ ์ฒ๋ผ ํ๋ ค๋ฉด div๋ก ์ด๋ฏธ์ง ํ๋ฒ ๋ ๊ฐ์จ์ ๊ทธ div์ overflow:hidden ์ฃผ๊ณ
+ // imgํ์ผ์ width: 100%, height: 100%, object-fit: cover์ฃผ๋ฉด ๋จ
+
+ .feedFourWord,
+ .feedFourWordTwo {
+ font-weight: bold;
+ }
+ }
+
+ .feedFive {
+ padding: 0px 10px 3px 10px;
+
+ .feedFiveWord {
+ font-weight: bold;
+ }
+ }
+
+ .comment {
+ padding-top: 5px;
+ padding-left: 5px;
+ padding-bottom: 5px;
+ }
+
+ .postTime {
+ display: inline-block;
+ padding: 10px 10px 15px 10px;
+ color: #9c9c9c;
+ }
+
+ .commentSection {
+ position: relative;
+
+ .comment {
+ width: 100%;
+ padding: 15px 10px;
+ border: 1px solid #f3f3f3;
+ }
+
+ .postButton {
+ position: absolute;
+ bottom: 13px;
+ right: 20px;
+ color: #c5e1fc;
+ background-color: white;
+ border: 1px solid white;
+ font-size: 15px;
+ }
+ }
+} | Unknown | - article ํ๊ทธ๊ฐ ์๋๋ผ feed๋ผ๋ className์ผ๋ก nestingํ๊ธฐ
- ์ต์์ div๋ฅผ article๋ก ๋ฐ๊พธ๊ณ 1 depth ์ค์ด๋ฉด ๋ ๋ฏ |
@@ -0,0 +1,66 @@
+package blackjack.controller;
+
+import blackjack.domain.card.Deck;
+import blackjack.domain.participant.Dealer;
+import blackjack.domain.participant.Player;
+import blackjack.domain.participant.PlayersFactory;
+import blackjack.domain.result.GameResult;
+import blackjack.dto.DrawCardRequestDto;
+import blackjack.dto.PlayersNameInputDto;
+import blackjack.view.InputView;
+import blackjack.view.OutputView;
+
+import java.util.List;
+
+public class BlackJackController {
+ private final InputView inputView = new InputView();
+ private final OutputView outputView = new OutputView();
+
+ public void run() {
+ PlayersNameInputDto namesInput = inputView.getPlayersName();
+ Dealer dealer = new Dealer();
+ Deck deck = new Deck();
+ List<Player> players = PlayersFactory.createPlayers(namesInput.getPlayersName());
+
+ drawTowCards(dealer, players, deck);
+ drawCardToPlayers(players, deck);
+ drawCardToDealer(dealer, deck);
+ outputView.printCardsResult(dealer, players);
+ outputView.printGameResult(GameResult.of(dealer, players));
+ }
+
+ private void drawTowCards(Dealer dealer, List<Player> players, Deck deck) {
+ for (Player player : players) {
+ player.receiveCard(deck.drawCard());
+ player.receiveCard(deck.drawCard());
+ }
+ dealer.receiveCard(deck.drawCard());
+ dealer.receiveCard(deck.drawCard());
+ outputView.printFirstCardsGiven(players, dealer);
+ outputView.printDealerCard(dealer);
+ outputView.printPlayersCard(players);
+ }
+
+ private void drawCardToPlayers(List<Player> players, Deck deck) {
+ for (Player player : players) {
+ drawCardToPlayer(player, deck);
+ }
+ }
+
+ private void drawCardToPlayer(Player player, Deck deck) {
+ DrawCardRequestDto drawCardRequest = inputView.getPlayersResponse(player);
+ while (player.drawable() && drawCardRequest.isYes()) {
+ player.receiveCard(deck.drawCard());
+
+ outputView.printCards(player);
+ drawCardRequest = inputView.getPlayersResponse(player);
+ }
+ }
+
+ private void drawCardToDealer(Dealer dealer, Deck deck) {
+ while (dealer.drawable()) {
+ dealer.receiveCard(deck.drawCard());
+ outputView.printDealerCardGiven();
+ }
+ }
+} | Java | Controller๋ฅผ Entry-point๋ก์จ ์ฌ์ฉํ๊ณ ์๋๋ฐ, ํ์ฌ์ ๊ฐ์ด ํด๋น ๊ฐ๋ค์ ์ด๋ฅผ ๋ฉค๋ฒ๋ณ์๋ก ๊ฐ์ง๊ฒ ๋๋ฉด ํด๋น ๊ฒ์์ ์ฌ๋ฌ๋ช
์ด ๋์์ ์์ฒญํ๋ ๊ฒฝ์ฐ ๋ฐ์ดํฐ ๋ถ์ ํฉ์ด ๋ฐ์ํ ์ ์์ด์. ๋ฉค๋ฒ๋ณ์๋ฅผ ์ง์ญ๋ณ์๋ก ๊ฐ์ ธ๊ฐ๋ ๊ฒ์ด ์ข์ ๋ณด์ฌ์๐ |
@@ -0,0 +1,66 @@
+package blackjack.controller;
+
+import blackjack.domain.card.Deck;
+import blackjack.domain.participant.Dealer;
+import blackjack.domain.participant.Player;
+import blackjack.domain.participant.PlayersFactory;
+import blackjack.domain.result.GameResult;
+import blackjack.dto.DrawCardRequestDto;
+import blackjack.dto.PlayersNameInputDto;
+import blackjack.view.InputView;
+import blackjack.view.OutputView;
+
+import java.util.List;
+
+public class BlackJackController {
+ private final InputView inputView = new InputView();
+ private final OutputView outputView = new OutputView();
+
+ public void run() {
+ PlayersNameInputDto namesInput = inputView.getPlayersName();
+ Dealer dealer = new Dealer();
+ Deck deck = new Deck();
+ List<Player> players = PlayersFactory.createPlayers(namesInput.getPlayersName());
+
+ drawTowCards(dealer, players, deck);
+ drawCardToPlayers(players, deck);
+ drawCardToDealer(dealer, deck);
+ outputView.printCardsResult(dealer, players);
+ outputView.printGameResult(GameResult.of(dealer, players));
+ }
+
+ private void drawTowCards(Dealer dealer, List<Player> players, Deck deck) {
+ for (Player player : players) {
+ player.receiveCard(deck.drawCard());
+ player.receiveCard(deck.drawCard());
+ }
+ dealer.receiveCard(deck.drawCard());
+ dealer.receiveCard(deck.drawCard());
+ outputView.printFirstCardsGiven(players, dealer);
+ outputView.printDealerCard(dealer);
+ outputView.printPlayersCard(players);
+ }
+
+ private void drawCardToPlayers(List<Player> players, Deck deck) {
+ for (Player player : players) {
+ drawCardToPlayer(player, deck);
+ }
+ }
+
+ private void drawCardToPlayer(Player player, Deck deck) {
+ DrawCardRequestDto drawCardRequest = inputView.getPlayersResponse(player);
+ while (player.drawable() && drawCardRequest.isYes()) {
+ player.receiveCard(deck.drawCard());
+
+ outputView.printCards(player);
+ drawCardRequest = inputView.getPlayersResponse(player);
+ }
+ }
+
+ private void drawCardToDealer(Dealer dealer, Deck deck) {
+ while (dealer.drawable()) {
+ dealer.receiveCard(deck.drawCard());
+ outputView.printDealerCardGiven();
+ }
+ }
+} | Java | ๋ฉ์๋ ๋ถ๋ฆฌ๊ฐ ์ ๋์ด ์์ด์, ๊ฐ๋
์ฑ์ด ์ข๋ค์๐ |
@@ -0,0 +1,66 @@
+package blackjack.controller;
+
+import blackjack.domain.card.Deck;
+import blackjack.domain.participant.Dealer;
+import blackjack.domain.participant.Player;
+import blackjack.domain.participant.PlayersFactory;
+import blackjack.domain.result.GameResult;
+import blackjack.dto.DrawCardRequestDto;
+import blackjack.dto.PlayersNameInputDto;
+import blackjack.view.InputView;
+import blackjack.view.OutputView;
+
+import java.util.List;
+
+public class BlackJackController {
+ private final InputView inputView = new InputView();
+ private final OutputView outputView = new OutputView();
+
+ public void run() {
+ PlayersNameInputDto namesInput = inputView.getPlayersName();
+ Dealer dealer = new Dealer();
+ Deck deck = new Deck();
+ List<Player> players = PlayersFactory.createPlayers(namesInput.getPlayersName());
+
+ drawTowCards(dealer, players, deck);
+ drawCardToPlayers(players, deck);
+ drawCardToDealer(dealer, deck);
+ outputView.printCardsResult(dealer, players);
+ outputView.printGameResult(GameResult.of(dealer, players));
+ }
+
+ private void drawTowCards(Dealer dealer, List<Player> players, Deck deck) {
+ for (Player player : players) {
+ player.receiveCard(deck.drawCard());
+ player.receiveCard(deck.drawCard());
+ }
+ dealer.receiveCard(deck.drawCard());
+ dealer.receiveCard(deck.drawCard());
+ outputView.printFirstCardsGiven(players, dealer);
+ outputView.printDealerCard(dealer);
+ outputView.printPlayersCard(players);
+ }
+
+ private void drawCardToPlayers(List<Player> players, Deck deck) {
+ for (Player player : players) {
+ drawCardToPlayer(player, deck);
+ }
+ }
+
+ private void drawCardToPlayer(Player player, Deck deck) {
+ DrawCardRequestDto drawCardRequest = inputView.getPlayersResponse(player);
+ while (player.drawable() && drawCardRequest.isYes()) {
+ player.receiveCard(deck.drawCard());
+
+ outputView.printCards(player);
+ drawCardRequest = inputView.getPlayersResponse(player);
+ }
+ }
+
+ private void drawCardToDealer(Dealer dealer, Deck deck) {
+ while (dealer.drawable()) {
+ dealer.receiveCard(deck.drawCard());
+ outputView.printDealerCardGiven();
+ }
+ }
+} | Java | DTO๋ ์์ ์ด ๊ฐ์ง๊ณ ์๋ ๋ฐ์ดํฐ์ ๋ํด์, ์ด๋ค ํ์/ํ๋จ์ ํ ์ ์๋ค๊ณ ์๊ฐํด์. ์
๋ ฅ๋ฐ์ ๊ฐ์ด Y/N์ธ์ง ํ๋จํ๋ ๋ก์ง์ DTO๋ก ๊ฐ๋ ๋๋ค๊ณ ์๊ฐํฉ๋๋ค.
๋ค๋ง ํด๋น ๋ก์ง์ด ์ฌ๋ฌ ๊ณณ์์ ์ฌ์ฉ๋๊ฑฐ๋, ์ด๋ฅผ ํ๋์ ๋๋ฉ์ธ ํ์๋ก ์ ์ํ๋ค๋ฉด DTO -> Domain์ผ๋ก ์ ํํ ๋ค์ ๋๋ฉ์ธ์์ ํ๋จํ๋ ๊ฒ๋ ์ข์ ๊ฒ ๊ฐ์์. ํ์ฌ๋ ํด๋น ๋ถ๋ถ์ ๋ํ ๋๋ฉ์ธ ๋ก์ง์ด Controller์ ๋์ ์๊ธฐ์ ์ํ์๋ ํํ๋ก ํฌ์ฅํด์ฃผ์๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค๐
์ถ๊ฐ๋ก ๋ค์ด๋ฐ์ ํ๋ฐํ์ด๊ณ ์ฌ๋ฐ์ฌ์ง๋ง, ๊ฐ์ธ์ ์ผ๋ก ํ๋ก๊ทธ๋จ์๊ฒ ๋์ด์จ Input์ ๋ด๋ DTO๋ Request/์ฐ๋ฆฌ ํ๋ก๊ทธ๋จ์์ ๋ฐํํด์ฃผ๋DTO๋ Response๋ก ์ฌ์ฉํ๊ณ ์์ด์. response๋ก ์์ฑํด์ฃผ์ ๋งฅ๋ฝ์ ์๊ฒ ์ผ๋, Client-Server๊ฐ ํญ์ ์ ๋์ ์ผ๋ก ๋ฌ๋ผ์ง ์ ์๋ค๋ฉด DTO๊ฐ ๋ง์์ก์ ๋ ํท๊ฐ๋ฆด ์ ์๋ค๊ณ ์๊ฐํด์๐ (์ถ๊ฐ๋ก DTO๋ > Dto๋ก ์ ๊ณ ์๊ธดํฉ๋๋ค - ์ทจํฅ) |
@@ -0,0 +1,17 @@
+package blackjack.utils;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Collectors;
+
+public class StringUtil {
+ private static final String COMMA = ",";
+ private static final String RESPONSE_RESTRICT_MESSAGE = "y ํน์ n ๋ง ์
๋ ฅํ ์ ์์ต๋๋ค.";
+
+ public static List<String> splitByComma(String input) {
+ List<String> names = Arrays.asList(input.split(COMMA));
+ return names.stream()
+ .map(String::trim)
+ .collect(Collectors.toList());
+ }
+} | Java | `Utils์ฑ ํด๋์ค`๋ ์ผ๋ฐ์ ์ผ๋ก ์ ๋ง ์ ํธ๋ฆฌํฐํ ๊ฒ๋ค๋ง ๊ธฐ๋ฅ์ ๋ด๋ ๊ฒ์ด ์ผ๋ฐ์ ์ด์์. ํ์ฌ ์ ํธ๋ก์ง์ด Y/N์ด๋ผ๋ ์ด๋ค ๋ฃฐ์ ๋ํด์ ๋๋ฌด ๋ง์ด ์๊ณ ์๋ ์ํ์ธ ๊ฒ ๊ฐ์ต๋๋ค
๋๋ฉ์ธ ํน์ DTO์ ๋ก์ง์ผ๋ก ๋ณ๊ฒฝํ๋ ๊ฒ์ด ์ข์๋ณด์ด๊ณ , Util์์ ์ฌ์ฉํ์ ๋ค๋ฉด ๊ฒ์ฆ ๋์์ด ๋๋ Y/N๋ ํ๋ผ๋ฏธํฐ๋ก ๋ฐ๋๋ค๋ฉด ์กฐ๊ธ ๋ ๋ฒ์ฉ์ ์ผ๋ก ์ฌ์ฉํ ์ ์๋ ๋ฉ์๋๊ฐ ๋ ๊ฒ ๊ฐ์์. |
@@ -0,0 +1,32 @@
+package blackjack.domain.card;
+
+import blackjack.domain.card.strategy.DrawStrategy;
+import blackjack.domain.card.strategy.RandomDrawStrategy;
+import lombok.Getter;
+
+import java.util.LinkedList;
+import java.util.List;
+
+public class Deck {
+
+ private static final String ALERT_NO_CARD_LEFT = "์ฌ์ฉ ๊ฐ๋ฅํ ์นด๋๋ฅผ ๋ชจ๋ ์์งํ์์ต๋๋ค.";
+
+ @Getter
+ private final List<Card> deck;
+
+ public Deck() {
+ this.deck = new LinkedList<>(DeckFactory.createDeck());
+ }
+
+ public Card drawCard() {
+ if (deck.isEmpty()) {
+ throw new RuntimeException(ALERT_NO_CARD_LEFT);
+ }
+ return deck.remove(generateNextDrawCardIndex(new RandomDrawStrategy()));
+ }
+
+ private int generateNextDrawCardIndex(DrawStrategy drawStrategy) {
+ return drawStrategy.getNextIndex(deck);
+ }
+
+} | Java | LinkedList๋ก ์ ์ธํ์ ์ด์ ๋ ์นด๋๋ฅผ ํ์ฅ์ฉ ์ญ์ ํ ๋ ArrayList๊ฐ ๋นํจ์จ์ ์ด๋ผ์ ๊ทธ๋ ๊ฒ ํ์ ๊ฑธ๊น์? ๐ |
@@ -0,0 +1,32 @@
+package blackjack.domain.card;
+
+import blackjack.domain.card.strategy.DrawStrategy;
+import blackjack.domain.card.strategy.RandomDrawStrategy;
+import lombok.Getter;
+
+import java.util.LinkedList;
+import java.util.List;
+
+public class Deck {
+
+ private static final String ALERT_NO_CARD_LEFT = "์ฌ์ฉ ๊ฐ๋ฅํ ์นด๋๋ฅผ ๋ชจ๋ ์์งํ์์ต๋๋ค.";
+
+ @Getter
+ private final List<Card> deck;
+
+ public Deck() {
+ this.deck = new LinkedList<>(DeckFactory.createDeck());
+ }
+
+ public Card drawCard() {
+ if (deck.isEmpty()) {
+ throw new RuntimeException(ALERT_NO_CARD_LEFT);
+ }
+ return deck.remove(generateNextDrawCardIndex(new RandomDrawStrategy()));
+ }
+
+ private int generateNextDrawCardIndex(DrawStrategy drawStrategy) {
+ return drawStrategy.getNextIndex(deck);
+ }
+
+} | Java | ํ์ฌ๋ ๊ฒฝ๊ธฐ๋์ค์ ์นด๋๊ฐ ๋ชจ๋ ์์ง๋๋ฉด, ํ๋ก๊ทธ๋จ์ด ์ข
๋ฃ๋๋ ๊ตฌ์กฐ์ธ๋ฐ์. ์ผ๋ฐ์ ์ผ๋ก ๊ฒฝ๊ธฐ๋ฅผ ํ๋ค, ์นด๋๊ฐ ๋ชจ๋ ์์ง๋๋ค๊ณ ๊ทธ ๊ฒ์์ด ๋ฌดํจ๊ฐ ๋์ง ์๋ฏ์ด ์กฐ๊ธ ๋ ๊ตฌ์ฒด์ ์ธ ๋ฐฉ๋ฒ/๊ตฌํ์ ๊ณ ๋ฏผํด๋ณด๋ฉด ์ข์ ๊ฒ ๊ฐ์์. (๊ตฌํ์ ํ์ง ์์ผ์
๋ ๋ฉ๋๋ค)
๋๋ฉ์ธ์ ๋ํด์ ์กฐ๊ธ ๋ ๋ฅ๋์ ์ผ๋ก ์ดํดํ๋ฉด ์ด๋จ๊น ๋ผ๋ ์๋ฏธ์์ ๋๋ฆฐ ํผ๋๋ฐฑ์
๋๋ค. (์ฐธ๊ณ ๋ก ๋ธ๋์ญ์์๋ ์ฐธ๊ฐ ์ธ์์ ์ ํํ๊ณ ์๋๋ผ๊ตฌ์๐) |
@@ -0,0 +1,32 @@
+package blackjack.domain.card;
+
+import blackjack.domain.card.strategy.DrawStrategy;
+import blackjack.domain.card.strategy.RandomDrawStrategy;
+import lombok.Getter;
+
+import java.util.LinkedList;
+import java.util.List;
+
+public class Deck {
+
+ private static final String ALERT_NO_CARD_LEFT = "์ฌ์ฉ ๊ฐ๋ฅํ ์นด๋๋ฅผ ๋ชจ๋ ์์งํ์์ต๋๋ค.";
+
+ @Getter
+ private final List<Card> deck;
+
+ public Deck() {
+ this.deck = new LinkedList<>(DeckFactory.createDeck());
+ }
+
+ public Card drawCard() {
+ if (deck.isEmpty()) {
+ throw new RuntimeException(ALERT_NO_CARD_LEFT);
+ }
+ return deck.remove(generateNextDrawCardIndex(new RandomDrawStrategy()));
+ }
+
+ private int generateNextDrawCardIndex(DrawStrategy drawStrategy) {
+ return drawStrategy.getNextIndex(deck);
+ }
+
+} | Java | Randomํ ๊ฐ์ ํ
์คํธํ๊ธฐ ์ํด์, ๋ ์ด์ฑ์นด์์ ํ๋ ๋ฐฉ์์ผ๋ก ์ด๋ฅผ ์ธ๋ถ์์ ์ฃผ์
๋ฐ๋ ํํ๋ก ํ๋ฉด ์ด๋จ๊น์? |
@@ -0,0 +1,39 @@
+package blackjack.domain.card;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+public class DeckFactory {
+
+ private static final List<Card> cardsDeck;
+
+ static {
+ cardsDeck = createCardsDeck();
+ }
+
+ private static List<Card> createCardsDeck() {
+ List<Card> cards = new ArrayList<>();
+
+ for (Denomination denomination : Denomination.values()) {
+ cards.addAll(createCards(denomination));
+ }
+ return cards;
+ }
+
+ private static List<Card> createCards(Denomination denomination) {
+ List<Card> cards = new ArrayList<>();
+
+ for (Type type : Type.values()) {
+ cards.add(new Card(denomination, type));
+ }
+
+ return cards;
+ }
+
+ public static List<Card> createDeck() {
+ return Collections.unmodifiableList(cardsDeck);
+ }
+}
+
+ | Java | ์คํํฑํ๊ฒ ์ดํ๋ฆฌ์ผ์ด์
์ด ์์๋จ๊ณผ ๋์์ ์๊ธด๋ค๋ ๊ฒ์ ๋ช
์์ ์ผ๋ก ํ๊ธฐ ์ํด์ static { } ํํ๋ก ์ด๊ธฐํ๋ฅผ ํ ์๋ ์์ต๋๋ค๐ |
@@ -0,0 +1,39 @@
+package blackjack.domain.card;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+public class DeckFactory {
+
+ private static final List<Card> cardsDeck;
+
+ static {
+ cardsDeck = createCardsDeck();
+ }
+
+ private static List<Card> createCardsDeck() {
+ List<Card> cards = new ArrayList<>();
+
+ for (Denomination denomination : Denomination.values()) {
+ cards.addAll(createCards(denomination));
+ }
+ return cards;
+ }
+
+ private static List<Card> createCards(Denomination denomination) {
+ List<Card> cards = new ArrayList<>();
+
+ for (Type type : Type.values()) {
+ cards.add(new Card(denomination, type));
+ }
+
+ return cards;
+ }
+
+ public static List<Card> createDeck() {
+ return Collections.unmodifiableList(cardsDeck);
+ }
+}
+
+ | Java | ๋ฉ์๋์ ๋ค์ด๋ฐ์ผ๋ก ๋ดค์ ๋ `Deck` ์ ๋ง๋ค ๊ฒ ๊ฐ์๋ฐ, List<Card> ๋ฅผ ๋ฐํํ๊ณ ์๋ ๋ถ๋ถ์ด ์ง๊ด์ ์ผ๋ก ์ดํด๋์ง ์๋ ๊ฒ ๊ฐ์ต๋๋ค. ์ถ๊ฐ๋ก ์ดํ๋ฆฌ์ผ์ด์
์ด ๋ธ๊ณผ ๋์์ `cardDecks`๋ฅผ ๋ง๋ค๊ณ ์์ด์, ์ฌ์ฉํ๋ค๋ฉด getter ํํ๋ก ์ฌ์ฉํด์ผํ์ง ์์๊น ์ถ๋ค์.
ํน์ ์ด ๋ฉ์๋๋ฅผ ์ฌ์ฉํ๋ ์ฌ๋ ์
์ฅ์์๋ `์ดํ๋ฆฌ์ผ์ด์
์์ ํด๋น ๊ฐ(List<Card>)์ ํญ์ ๊ณ ์ ๋์ด ์๋ค๋ผ๋๊ฑธ ๋ชฐ๋ผ๋ ๋๊ณ ํ์ํ ๋ ๋ฌ๋ผํ๋ฉด ๋๋ค` ๋๋์ผ๋ก ์์ฑํ์ ๊ฑธ๊น์? > ์ ๊ฒฝ์ฐ์๋ ์ฌ์ฉ์ ์
์ฅ์์ ํญ์ ๋ฑ์ ๋ง๋ค๊ฑฐ๋ผ ์์ํ๊ณ ๋ก์ง์ ์งํํ ์ ์์ด์ ์ํํ ๊ฒ ๊ฐ์์! |
@@ -0,0 +1,38 @@
+package blackjack.domain.card;
+
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class CardTest {
+
+ @DisplayName("์นด๋ ๊ฐ์ฒด์ ์ซ์์ ์ข
๋ฅ๊ฐ์ด ๊ฐ์ผ๋ฉด ๊ฐ์ ๊ฐ์ฒด๋ก ํ๋จํ๋ค")
+ @Test
+ void equalsTest() {
+ //given, when, then
+ assertThat(new Card(Denomination.TWO, Type.DIAMOND))
+ .isEqualTo(new Card(Denomination.TWO, Type.DIAMOND));
+
+ }
+
+ @DisplayName("์นด๋ ๊ฐ์ฒด์ ์ซ์์ ์ข
๋ฅ๋ฅผ ์ถ๋ ฅํ๋ค")
+ @Test
+ void printCardTwoDiamond() {
+ //given
+ Card card = new Card(Denomination.TWO, Type.DIAMOND);
+
+ //when, then
+ assertThat(card).hasToString("2๋ค์ด์๋ชฌ๋");
+ }
+
+ @DisplayName("์นด๋ ๊ฐ์ฒด์ ์ซ์์ ์ข
๋ฅ๋ฅผ ์ถ๋ ฅํ๋ค")
+ @Test
+ void printCardAceHeart() {
+ //given
+ Card card = new Card(Denomination.ACE, Type.HEART);
+
+ //when, then
+ assertThat(card.toString()).isEqualTo("Aํํธ");
+ }
+} | Java | `assertThat(card).hasToString("2๋ค์ด์๋ชฌ๋")` ์ด๋ฐ ๋ฌธ๋ฒ๋ ์์ต๋๋ค๐ |
@@ -0,0 +1,102 @@
+package blackjack.domain.participant;
+
+import blackjack.domain.card.Card;
+import blackjack.domain.card.Denomination;
+import lombok.Getter;
+import org.apache.commons.lang3.StringUtils;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+
+@Getter
+public abstract class Participant {
+ private static final int DIFFERENCE_OF_ACE_SCORE = 10;
+ private static final int BLACKJACK = 21;
+ private static final int ZERO = 0;
+ private static final String CHECK_NULL_OR_EMPTY = "์ด๋ฆ์ด ๋น ์นธ ํน์ null ๊ฐ์ด ์๋์ง ํ์ธํด์ฃผ์ธ์.";
+ private static final String CHECK_CONTAINING_ONLY_LETTERS_AND_DIGITS = "์ด๋ฆ์ ํน์๋ฌธ์๋ฅผ ํฌํจํ์ง ์์ ๋ฌธ์์ ์ซ์๋ก ์ง์ ํด์ฃผ์ธ์.";
+
+ private final String name;
+ private final List<Card> cards;
+
+ protected Participant(String name) {
+ validateName(name);
+
+ this.name = name;
+ this.cards = new ArrayList<>();
+ }
+
+ private void validateName(String name) {
+ validateNullOrEmpty(name);
+ validateAlphaNumeric(name);
+ }
+
+ private void validateNullOrEmpty(String name) {
+ if (StringUtils.isBlank(name)) {
+ throw new IllegalArgumentException(CHECK_NULL_OR_EMPTY);
+ }
+ }
+
+ private void validateAlphaNumeric(String name) {
+ if (!StringUtils.isAlphanumericSpace(name)) {
+ throw new IllegalArgumentException(CHECK_CONTAINING_ONLY_LETTERS_AND_DIGITS);
+ }
+ }
+
+ protected abstract boolean drawable();
+
+ public void receiveCard(Card card) {
+ cards.add(card);
+ }
+
+ public int getCardsSum() {
+ int scoreOfAceAsEleven = sumOfCardsScore();
+ int aceCount = getAceCount();
+
+ while (canCountAceAsOne(scoreOfAceAsEleven, aceCount)) {
+ scoreOfAceAsEleven = scoreOfAceAsOne(scoreOfAceAsEleven);
+ aceCount--;
+ }
+
+ return scoreOfAceAsEleven;
+ }
+
+ private int scoreOfAceAsOne(int scoreOfAceAsEleven) {
+ return scoreOfAceAsEleven - DIFFERENCE_OF_ACE_SCORE;
+ }
+
+ private boolean canCountAceAsOne(int scoreOfAceAsEleven, int aceCount) {
+ return scoreOfAceAsEleven > BLACKJACK && aceCount > ZERO;
+ }
+
+ private int getAceCount() {
+ return (int) cards.stream()
+ .filter(Card::isAce)
+ .count();
+ }
+
+ private int sumOfCardsScore() {
+ return cards.stream()
+ .map(Card::getDenomination)
+ .mapToInt(Denomination::getScore)
+ .sum();
+ }
+
+ public boolean isBust() {
+ return getCardsSum() > BLACKJACK;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ Participant that = (Participant) o;
+ return Objects.equals(name, that.name) && Objects.equals(cards, that.cards);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(name, cards);
+ }
+} | Java | ACE์ ์๋ฅผ ๊ฒฐ์ ํ ๋, 1 ๋๋ 11์ด ๋๋ ๋ก์ง์ Denomination์ ์ญํ ์ด ์๋๊น์? |
@@ -0,0 +1,27 @@
+package blackjack.domain.participant;
+
+import lombok.Getter;
+
+@Getter
+public class Player extends Participant {
+
+ private static final int PLAYER_DRAW_THRESHOLD = 21;
+ private static final String DEALER_NAME = "๋๋ฌ";
+ private static final String CHECK_SAME_NAME_AS_DEALER = "์ด๋ฆ์ ๋๋ฌ์ ๊ฐ์ ์ ์์ผ๋ ๋ค๋ฅธ ์ด๋ฆ์ ์ง์ ํด์ฃผ์ธ์.";
+
+ public Player(String name) {
+ super(name);
+ validateDealerNameDuplicated(name);
+ }
+
+ private void validateDealerNameDuplicated(String name) {
+ if (name.equals(DEALER_NAME)) {
+ throw new IllegalArgumentException(CHECK_SAME_NAME_AS_DEALER);
+ }
+ }
+
+ @Override
+ public boolean drawable() {
+ return getCardsSum() < PLAYER_DRAW_THRESHOLD;
+ }
+} | Java | ์ฌ๋ฐ๋ ์ ์ฝ์ฌํญ์ธ ๊ฒ ๊ฐ์ต๋๋ค๐ |
@@ -0,0 +1,27 @@
+package blackjack.domain.participant;
+
+import lombok.Getter;
+
+@Getter
+public class Player extends Participant {
+
+ private static final int PLAYER_DRAW_THRESHOLD = 21;
+ private static final String DEALER_NAME = "๋๋ฌ";
+ private static final String CHECK_SAME_NAME_AS_DEALER = "์ด๋ฆ์ ๋๋ฌ์ ๊ฐ์ ์ ์์ผ๋ ๋ค๋ฅธ ์ด๋ฆ์ ์ง์ ํด์ฃผ์ธ์.";
+
+ public Player(String name) {
+ super(name);
+ validateDealerNameDuplicated(name);
+ }
+
+ private void validateDealerNameDuplicated(String name) {
+ if (name.equals(DEALER_NAME)) {
+ throw new IllegalArgumentException(CHECK_SAME_NAME_AS_DEALER);
+ }
+ }
+
+ @Override
+ public boolean drawable() {
+ return getCardsSum() < PLAYER_DRAW_THRESHOLD;
+ }
+} | Java | ํ์ฌ ์ฌ์ฉํ์ ์ด์ ๋ OutputView ๋ก์ง์ ๋จ์ํ๊ฒ ํ๊ธฐ ์ํจ์ธ ๊ฒ ๊ฐ์์. ํ๋ฉด์ ๋ณด์ฌ์ฃผ๋ ํํ๊ฐ ๋ฌ๋ผ์ก์ ๋, ๋๋ฉ์ธ์ ์์ ํด์ผ ํ๋ค๋ฉด ์์กด๊ด๊ณ๊ฐ ์ ๋ชป ์ค๊ณ๋๊ฑฐ๋ผ๊ณ ์๊ฐํฉ๋๋ค! |
@@ -0,0 +1,27 @@
+package blackjack.domain.participant;
+
+import lombok.Getter;
+
+@Getter
+public class Player extends Participant {
+
+ private static final int PLAYER_DRAW_THRESHOLD = 21;
+ private static final String DEALER_NAME = "๋๋ฌ";
+ private static final String CHECK_SAME_NAME_AS_DEALER = "์ด๋ฆ์ ๋๋ฌ์ ๊ฐ์ ์ ์์ผ๋ ๋ค๋ฅธ ์ด๋ฆ์ ์ง์ ํด์ฃผ์ธ์.";
+
+ public Player(String name) {
+ super(name);
+ validateDealerNameDuplicated(name);
+ }
+
+ private void validateDealerNameDuplicated(String name) {
+ if (name.equals(DEALER_NAME)) {
+ throw new IllegalArgumentException(CHECK_SAME_NAME_AS_DEALER);
+ }
+ }
+
+ @Override
+ public boolean drawable() {
+ return getCardsSum() < PLAYER_DRAW_THRESHOLD;
+ }
+} | Java | ํด๋น ๋ฉ์๋๋ ์ด๊ฒผ๋ค๊ฐ, ์๋๋ผ `๊ฒฝ๊ธฐ ๊ฒฐ๊ณผ๋ฅผ ๋ฐํํด์ฃผ๋ ๋ฉ์๋`๋๊น ์ด๋ฆ์ ๋ณ๊ฒฝํด์ฃผ์๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค. ์ถ๊ฐ๋ก `Rule`์ด ์ฌ์ฉ์์ ๋๋ฌ๋ฅผ ๋ชจ๋ ๋ฐ์ ๊ฒฐ๊ณผ๋ฅผ ๋ฐํํด์ฃผ๋๊ฒ ์ญํ ์ด ์ ์ ํ์ง ์์๊น์? (ํ์ฌ์ rule.compare๊ณผ getWinningResult๋ฅผ ํฉ์น ๋ฉ์๋๋ฅผ Rule์์ ์ ๊ณตํ๋ฉด ์ด๋จ๊น์?) |
@@ -0,0 +1,27 @@
+package blackjack.domain.participant;
+
+import lombok.Getter;
+
+@Getter
+public class Player extends Participant {
+
+ private static final int PLAYER_DRAW_THRESHOLD = 21;
+ private static final String DEALER_NAME = "๋๋ฌ";
+ private static final String CHECK_SAME_NAME_AS_DEALER = "์ด๋ฆ์ ๋๋ฌ์ ๊ฐ์ ์ ์์ผ๋ ๋ค๋ฅธ ์ด๋ฆ์ ์ง์ ํด์ฃผ์ธ์.";
+
+ public Player(String name) {
+ super(name);
+ validateDealerNameDuplicated(name);
+ }
+
+ private void validateDealerNameDuplicated(String name) {
+ if (name.equals(DEALER_NAME)) {
+ throw new IllegalArgumentException(CHECK_SAME_NAME_AS_DEALER);
+ }
+ }
+
+ @Override
+ public boolean drawable() {
+ return getCardsSum() < PLAYER_DRAW_THRESHOLD;
+ }
+} | Java | `๋ก์ง์ ์์ ์๊ฐ ์๋ค` ๋ผ๋ ์๊ฐ์ผ๋ก `get`์ ์ฌ์ฉํด์ฃผ์ ๊ฒ ๊ฐ์์. ๋ค๋ง ์๊ฒ ์๋ ๊ฒฝ์ฐ์๋ `NullPoint`๊ฐ ๋ ํ
๋ฐ์. ์ด ๋ฉ์์ง๋ฅผ ๋ณด๊ณ ์ด๋ค ์๋ฏธ์ธ์ง ์ฐพ๊ธฐ๊ฐ ์ด๋ ค์ธ ๊ฒ ๊ฐ์์.
์๋ ๊ฒ ์ ๋งคํ ๊ฒฝ์ฐ์ ์ ๋ orElseThrow๋ฅผ ํ๋ค๊ฑฐ๋, ๋ก๊ทธ๋ฅผ ํตํด์ ํ๋ก๊ทธ๋จ ์์ฒด๊ฐ ์๋ชป๋์์์ ์๋ ค์ฃผ๋ ํํ๋ก ๋จ๊ธฐ๋ ํธ์ด์์. |
@@ -0,0 +1,50 @@
+package blackjack.domain.result;
+
+import blackjack.domain.participant.Dealer;
+import blackjack.domain.participant.Player;
+import lombok.Getter;
+
+import java.util.Arrays;
+import java.util.function.BiFunction;
+
+public enum Rule{
+ // ์นด๋ ๊ฐ์ ํฉ์ด 21์ ๋์ผ๋ฉด ์นํจ ๊ฒฐ์ (ํ๋ ์ด์ด ๊ธฐ์ค์ผ๋ก ์ ์ธ)
+ PLAYER_BUST(((player, dealer) -> player.isBust()), WinningResult.LOSE, 1),
+ DEALER_BUST(((player, dealer) -> dealer.isBust()), WinningResult.WIN, 2),
+
+ // ์นด๋ ๊ฐ์ ํฉ์ด 21์ ๋์ง ์์ผ๋ฉด์, ๊ฐ์ด ๋ ํฐ์ชฝ์ด ์นํจ๊ฒฐ์ (์ด๋ฏธ ์ฌ๊ธฐ์ ๊ฒฐ์ , BlackJack ์ฒดํฌ ํ์์์)
+ PLAYER_HIGHER(((player, dealer) -> player.getCardsSum() > dealer.getCardsSum()), WinningResult.WIN, 3),
+ DEALER_HIGHER(((player, dealer) -> player.getCardsSum() < dealer.getCardsSum()), WinningResult.LOSE, 4),
+
+ // ๋ฌด์น๋ถ ๊ฒฐ์
+ TIES(((player, dealer) -> player.getCardsSum() == dealer.getCardsSum()), WinningResult.TIE, 5);
+
+ private BiFunction<Player, Dealer, Boolean> compare;
+ private WinningResult winningResult;
+ @Getter
+ private int verificationOrder;
+
+ Rule(BiFunction<Player, Dealer, Boolean> compare, WinningResult winningResult, int verificationOrder) {
+ this.compare = compare;
+ this.winningResult = winningResult;
+ this.verificationOrder = verificationOrder;
+ }
+
+ public Boolean findMatchingRule(Player player, Dealer dealer) {
+ return compare.apply(player, dealer);
+ }
+
+ public WinningResult getWinningResult() {
+ return winningResult;
+ }
+
+ public static WinningResult resultPlayerVersusDealer(Player player, Dealer dealer) {
+
+ return Arrays.stream(Rule.values())
+ .sorted(new RuleComparator())
+ .filter(rule -> rule.findMatchingRule(player, dealer))
+ .findFirst()
+ .orElseThrow(() -> new RuntimeException("์ผ์นํ๋ ๊ฒฐ๊ณผ๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค."))
+ .getWinningResult();
+ }
+} | Java | ์ ๋ก์ง๋ค์ด ์์์ ๋ฐ๋ผ ์ํฅ์ ๋ฐ์ ๊ฒ ๊ฐ์์. `์๋๋ ํ๋ ์ด์ด๊ฐ ๋ฒ์คํธ์ธ ๊ฒฝ์ฐ ํญ์ ํจ๋ฐฐ๋ก ๊ฐ์ฃผ๋๋๋ฐ ๋ฌด์น๋ถ Enum์ ๋งจ ์๋ก ์ฌ๋ฆฌ๋ฉด, ๋น๊ธด๊ฑฐ๋ก ๊ฐ์ฃผ๋๋ ํ์`์ผ๋ก์ฌ! ๊ทธ๋ ๋ค๋ฉด ๊ธฐ์กด `Enum์ ์์๊ฐ ์ค์ํ๋ค`๋ ๊ฒ์ ๋ช
์์ ์ผ๋ก ๋๋ฌ๋ด๊ฑฐ๋, ๋ค๋ฅธ ๋ฐฉ๋ฒ์ ์ฌ์ฉํด์ค์ผ ๋ค๋ฅธ ์ฌ๋์ด ์ค์ํ ์ฌ์ง๋ฅผ ์ค์ผ ์ ์์ ๊ฒ ๊ฐ์์ใ
ใ
(์ฌ๊ธด ๊ฐ์ฅ ์ค์ํ ๋ก์ง์ด๋๊น ๋๋์ฑ์ด์!) |
@@ -0,0 +1,50 @@
+package blackjack.domain.result;
+
+import blackjack.domain.participant.Dealer;
+import blackjack.domain.participant.Player;
+import lombok.Getter;
+
+import java.util.Arrays;
+import java.util.function.BiFunction;
+
+public enum Rule{
+ // ์นด๋ ๊ฐ์ ํฉ์ด 21์ ๋์ผ๋ฉด ์นํจ ๊ฒฐ์ (ํ๋ ์ด์ด ๊ธฐ์ค์ผ๋ก ์ ์ธ)
+ PLAYER_BUST(((player, dealer) -> player.isBust()), WinningResult.LOSE, 1),
+ DEALER_BUST(((player, dealer) -> dealer.isBust()), WinningResult.WIN, 2),
+
+ // ์นด๋ ๊ฐ์ ํฉ์ด 21์ ๋์ง ์์ผ๋ฉด์, ๊ฐ์ด ๋ ํฐ์ชฝ์ด ์นํจ๊ฒฐ์ (์ด๋ฏธ ์ฌ๊ธฐ์ ๊ฒฐ์ , BlackJack ์ฒดํฌ ํ์์์)
+ PLAYER_HIGHER(((player, dealer) -> player.getCardsSum() > dealer.getCardsSum()), WinningResult.WIN, 3),
+ DEALER_HIGHER(((player, dealer) -> player.getCardsSum() < dealer.getCardsSum()), WinningResult.LOSE, 4),
+
+ // ๋ฌด์น๋ถ ๊ฒฐ์
+ TIES(((player, dealer) -> player.getCardsSum() == dealer.getCardsSum()), WinningResult.TIE, 5);
+
+ private BiFunction<Player, Dealer, Boolean> compare;
+ private WinningResult winningResult;
+ @Getter
+ private int verificationOrder;
+
+ Rule(BiFunction<Player, Dealer, Boolean> compare, WinningResult winningResult, int verificationOrder) {
+ this.compare = compare;
+ this.winningResult = winningResult;
+ this.verificationOrder = verificationOrder;
+ }
+
+ public Boolean findMatchingRule(Player player, Dealer dealer) {
+ return compare.apply(player, dealer);
+ }
+
+ public WinningResult getWinningResult() {
+ return winningResult;
+ }
+
+ public static WinningResult resultPlayerVersusDealer(Player player, Dealer dealer) {
+
+ return Arrays.stream(Rule.values())
+ .sorted(new RuleComparator())
+ .filter(rule -> rule.findMatchingRule(player, dealer))
+ .findFirst()
+ .orElseThrow(() -> new RuntimeException("์ผ์นํ๋ ๊ฒฐ๊ณผ๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค."))
+ .getWinningResult();
+ }
+} | Java | ์น์ ํ ์ฃผ์ ์ข๋ค์. ํด๋น ๋ฉ์๋๋ participant์๊ฒ ๊ฐ์ ๋น๊ตํ๋ ํํ๋ก ๋ฆฌํฉํ ๋งํ ์ ์์ ๊ฒ ๊ฐ์์ |
@@ -0,0 +1,50 @@
+package blackjack.domain.result;
+
+import blackjack.domain.participant.Dealer;
+import blackjack.domain.participant.Player;
+import lombok.Getter;
+
+import java.util.Arrays;
+import java.util.function.BiFunction;
+
+public enum Rule{
+ // ์นด๋ ๊ฐ์ ํฉ์ด 21์ ๋์ผ๋ฉด ์นํจ ๊ฒฐ์ (ํ๋ ์ด์ด ๊ธฐ์ค์ผ๋ก ์ ์ธ)
+ PLAYER_BUST(((player, dealer) -> player.isBust()), WinningResult.LOSE, 1),
+ DEALER_BUST(((player, dealer) -> dealer.isBust()), WinningResult.WIN, 2),
+
+ // ์นด๋ ๊ฐ์ ํฉ์ด 21์ ๋์ง ์์ผ๋ฉด์, ๊ฐ์ด ๋ ํฐ์ชฝ์ด ์นํจ๊ฒฐ์ (์ด๋ฏธ ์ฌ๊ธฐ์ ๊ฒฐ์ , BlackJack ์ฒดํฌ ํ์์์)
+ PLAYER_HIGHER(((player, dealer) -> player.getCardsSum() > dealer.getCardsSum()), WinningResult.WIN, 3),
+ DEALER_HIGHER(((player, dealer) -> player.getCardsSum() < dealer.getCardsSum()), WinningResult.LOSE, 4),
+
+ // ๋ฌด์น๋ถ ๊ฒฐ์
+ TIES(((player, dealer) -> player.getCardsSum() == dealer.getCardsSum()), WinningResult.TIE, 5);
+
+ private BiFunction<Player, Dealer, Boolean> compare;
+ private WinningResult winningResult;
+ @Getter
+ private int verificationOrder;
+
+ Rule(BiFunction<Player, Dealer, Boolean> compare, WinningResult winningResult, int verificationOrder) {
+ this.compare = compare;
+ this.winningResult = winningResult;
+ this.verificationOrder = verificationOrder;
+ }
+
+ public Boolean findMatchingRule(Player player, Dealer dealer) {
+ return compare.apply(player, dealer);
+ }
+
+ public WinningResult getWinningResult() {
+ return winningResult;
+ }
+
+ public static WinningResult resultPlayerVersusDealer(Player player, Dealer dealer) {
+
+ return Arrays.stream(Rule.values())
+ .sorted(new RuleComparator())
+ .filter(rule -> rule.findMatchingRule(player, dealer))
+ .findFirst()
+ .orElseThrow(() -> new RuntimeException("์ผ์นํ๋ ๊ฒฐ๊ณผ๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค."))
+ .getWinningResult();
+ }
+} | Java | ํด๋น ๋ฉ์๋๋ ๋น๊ตํ๋ ๋ฉ์๋๊ฐ ์๋๋ผ, ์ด๋ค Rule์ธ์ง๋ฅผ ์ฐพ๋๊ฑฐ์ ๊ฐ๊น๋ค์. ์๊ฒ๋ ๋ฉ์๋ ์ด๋ฆ ์์ ํด์ฃผ์๋ฉด ์ข์ ๊ฒ ๊ฐ์์. |
@@ -0,0 +1,27 @@
+package blackjack.domain.result;
+
+import lombok.Getter;
+
+@Getter
+public enum WinningResult {
+
+ WIN("์น"),
+ LOSE("ํจ"),
+ TIE("๋ฌด์น๋ถ");
+
+ private final String result;
+
+ WinningResult(String result) {
+ this.result = result;
+ }
+
+ public WinningResult reverse() {
+ if (this == WIN) {
+ return LOSE;
+ }
+ if (this == LOSE) {
+ return WIN;
+ }
+ return TIE;
+ }
+} | Java | ์๊ฑฐ ์ ๊ฐ ์ ์ ํ ๋, ์ ๋๋๊ฑด๋ฐ WinningResult๊ฐ WinningResult ๋ฉค๋ฒ๋ณ์๋ฅผ ๊ฐ์ง๊ณ , ๋ฐ๋๋ก ์ ์ธํ๋ฉด ์๋๋๋ผ๊ตฌ์. ์ ์๋๋์ง ๋ฐ๋ก ์ดํด๊ฐ์๋ฉด Enum์ ์ ์ดํดํ๊ณ ๊ณ์ ๊ฒ ๊ฐ์ต๋๋คใ
ใ
ใ
```java
WIN("์น", LOST) // ์๋ฐ์์ผ๋ก์ฌ
``` |
@@ -0,0 +1,66 @@
+package blackjack.controller;
+
+import blackjack.domain.card.Deck;
+import blackjack.domain.participant.Dealer;
+import blackjack.domain.participant.Player;
+import blackjack.domain.participant.PlayersFactory;
+import blackjack.domain.result.GameResult;
+import blackjack.dto.DrawCardRequestDto;
+import blackjack.dto.PlayersNameInputDto;
+import blackjack.view.InputView;
+import blackjack.view.OutputView;
+
+import java.util.List;
+
+public class BlackJackController {
+ private final InputView inputView = new InputView();
+ private final OutputView outputView = new OutputView();
+
+ public void run() {
+ PlayersNameInputDto namesInput = inputView.getPlayersName();
+ Dealer dealer = new Dealer();
+ Deck deck = new Deck();
+ List<Player> players = PlayersFactory.createPlayers(namesInput.getPlayersName());
+
+ drawTowCards(dealer, players, deck);
+ drawCardToPlayers(players, deck);
+ drawCardToDealer(dealer, deck);
+ outputView.printCardsResult(dealer, players);
+ outputView.printGameResult(GameResult.of(dealer, players));
+ }
+
+ private void drawTowCards(Dealer dealer, List<Player> players, Deck deck) {
+ for (Player player : players) {
+ player.receiveCard(deck.drawCard());
+ player.receiveCard(deck.drawCard());
+ }
+ dealer.receiveCard(deck.drawCard());
+ dealer.receiveCard(deck.drawCard());
+ outputView.printFirstCardsGiven(players, dealer);
+ outputView.printDealerCard(dealer);
+ outputView.printPlayersCard(players);
+ }
+
+ private void drawCardToPlayers(List<Player> players, Deck deck) {
+ for (Player player : players) {
+ drawCardToPlayer(player, deck);
+ }
+ }
+
+ private void drawCardToPlayer(Player player, Deck deck) {
+ DrawCardRequestDto drawCardRequest = inputView.getPlayersResponse(player);
+ while (player.drawable() && drawCardRequest.isYes()) {
+ player.receiveCard(deck.drawCard());
+
+ outputView.printCards(player);
+ drawCardRequest = inputView.getPlayersResponse(player);
+ }
+ }
+
+ private void drawCardToDealer(Dealer dealer, Deck deck) {
+ while (dealer.drawable()) {
+ dealer.receiveCard(deck.drawCard());
+ outputView.printDealerCardGiven();
+ }
+ }
+} | Java | ์ฌ๋ฌ๋ช
์ด ๋์์ ์์ฒญํ๋ ๊ฒฝ์ฐ๋ฅผ ๊ณ ๋ คํ์ง ์์๋ค์. ์๋น์ค ๊ฐ๋ฐ์๋ก์ ํญ์ ์๊ฐํด์ผ ํ ๋ถ๋ถ์ธ ๊ฒ ๊ฐ์ต๋๋ค.
view๋ฅผ ์ ์ธํ ํด๋์ค๋ณ์๋ค์ ๋ก์ปฌ๋ณ์๋ก ์์ ํ์ต๋๋ค. |
@@ -0,0 +1,66 @@
+package blackjack.controller;
+
+import blackjack.domain.card.Deck;
+import blackjack.domain.participant.Dealer;
+import blackjack.domain.participant.Player;
+import blackjack.domain.participant.PlayersFactory;
+import blackjack.domain.result.GameResult;
+import blackjack.dto.DrawCardRequestDto;
+import blackjack.dto.PlayersNameInputDto;
+import blackjack.view.InputView;
+import blackjack.view.OutputView;
+
+import java.util.List;
+
+public class BlackJackController {
+ private final InputView inputView = new InputView();
+ private final OutputView outputView = new OutputView();
+
+ public void run() {
+ PlayersNameInputDto namesInput = inputView.getPlayersName();
+ Dealer dealer = new Dealer();
+ Deck deck = new Deck();
+ List<Player> players = PlayersFactory.createPlayers(namesInput.getPlayersName());
+
+ drawTowCards(dealer, players, deck);
+ drawCardToPlayers(players, deck);
+ drawCardToDealer(dealer, deck);
+ outputView.printCardsResult(dealer, players);
+ outputView.printGameResult(GameResult.of(dealer, players));
+ }
+
+ private void drawTowCards(Dealer dealer, List<Player> players, Deck deck) {
+ for (Player player : players) {
+ player.receiveCard(deck.drawCard());
+ player.receiveCard(deck.drawCard());
+ }
+ dealer.receiveCard(deck.drawCard());
+ dealer.receiveCard(deck.drawCard());
+ outputView.printFirstCardsGiven(players, dealer);
+ outputView.printDealerCard(dealer);
+ outputView.printPlayersCard(players);
+ }
+
+ private void drawCardToPlayers(List<Player> players, Deck deck) {
+ for (Player player : players) {
+ drawCardToPlayer(player, deck);
+ }
+ }
+
+ private void drawCardToPlayer(Player player, Deck deck) {
+ DrawCardRequestDto drawCardRequest = inputView.getPlayersResponse(player);
+ while (player.drawable() && drawCardRequest.isYes()) {
+ player.receiveCard(deck.drawCard());
+
+ outputView.printCards(player);
+ drawCardRequest = inputView.getPlayersResponse(player);
+ }
+ }
+
+ private void drawCardToDealer(Dealer dealer, Deck deck) {
+ while (dealer.drawable()) {
+ dealer.receiveCard(deck.drawCard());
+ outputView.printDealerCardGiven();
+ }
+ }
+} | Java | Dto ์ด๋ฆ์ DrawCardRequestDto๋ก ๋ณ๊ฒฝํ๊ณ ํ๋จ๋ก์ง์ Dto๋ก ์ด๋ํ์ต๋๋ค.
Dto๊ฐ ๊ฐ์ง ๋ฐ์ดํฐ๋ง์ ์ด์ฉํ ๊ฐ๋จํ ๋ก์ง์ Dto์์ ์ฒ๋ฆฌํด๋ ๋๋ค๋ ๊ฒ์ ์๊ฒ ๋์์ต๋๋ค.
Dto ์ด๋ฆ์ ๋ฐ์์จ ๊ฒ์ธ์ง, ๋ฐํํ๋ ๊ฒ์ธ์ง์ ๋ฐ๋ผ ํต์ผํ๋ฉด ์ผ๊ด์ฑ์ด ์์ด ํท๊ฐ๋ฆด ์ผ์ด ์์ด์ ์ข์ ๋ฐฉ๋ฒ์ธ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,17 @@
+package blackjack.utils;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Collectors;
+
+public class StringUtil {
+ private static final String COMMA = ",";
+ private static final String RESPONSE_RESTRICT_MESSAGE = "y ํน์ n ๋ง ์
๋ ฅํ ์ ์์ต๋๋ค.";
+
+ public static List<String> splitByComma(String input) {
+ List<String> names = Arrays.asList(input.split(COMMA));
+ return names.stream()
+ .map(String::trim)
+ .collect(Collectors.toList());
+ }
+} | Java | ๋ก์ง์ DrawCardRequestDto๋ก ์ด๋ํ์ต๋๋ค. |
@@ -0,0 +1,32 @@
+package blackjack.domain.card;
+
+import blackjack.domain.card.strategy.DrawStrategy;
+import blackjack.domain.card.strategy.RandomDrawStrategy;
+import lombok.Getter;
+
+import java.util.LinkedList;
+import java.util.List;
+
+public class Deck {
+
+ private static final String ALERT_NO_CARD_LEFT = "์ฌ์ฉ ๊ฐ๋ฅํ ์นด๋๋ฅผ ๋ชจ๋ ์์งํ์์ต๋๋ค.";
+
+ @Getter
+ private final List<Card> deck;
+
+ public Deck() {
+ this.deck = new LinkedList<>(DeckFactory.createDeck());
+ }
+
+ public Card drawCard() {
+ if (deck.isEmpty()) {
+ throw new RuntimeException(ALERT_NO_CARD_LEFT);
+ }
+ return deck.remove(generateNextDrawCardIndex(new RandomDrawStrategy()));
+ }
+
+ private int generateNextDrawCardIndex(DrawStrategy drawStrategy) {
+ return drawStrategy.getNextIndex(deck);
+ }
+
+} | Java | ๋ต ๊ทธ๋ ์ต๋๋ค. |
@@ -0,0 +1,32 @@
+package blackjack.domain.card;
+
+import blackjack.domain.card.strategy.DrawStrategy;
+import blackjack.domain.card.strategy.RandomDrawStrategy;
+import lombok.Getter;
+
+import java.util.LinkedList;
+import java.util.List;
+
+public class Deck {
+
+ private static final String ALERT_NO_CARD_LEFT = "์ฌ์ฉ ๊ฐ๋ฅํ ์นด๋๋ฅผ ๋ชจ๋ ์์งํ์์ต๋๋ค.";
+
+ @Getter
+ private final List<Card> deck;
+
+ public Deck() {
+ this.deck = new LinkedList<>(DeckFactory.createDeck());
+ }
+
+ public Card drawCard() {
+ if (deck.isEmpty()) {
+ throw new RuntimeException(ALERT_NO_CARD_LEFT);
+ }
+ return deck.remove(generateNextDrawCardIndex(new RandomDrawStrategy()));
+ }
+
+ private int generateNextDrawCardIndex(DrawStrategy drawStrategy) {
+ return drawStrategy.getNextIndex(deck);
+ }
+
+} | Java | DrawStrategy ์ธํฐํ์ด์ค๋ฅผ ๋ง๋ค๊ณ ๊ทธ๊ฒ์ ๊ตฌํํ๋ RandomDrawStrategy ํด๋์ค๋ฅผ ๋ง๋ค์์ต๋๋ค. |
@@ -0,0 +1,39 @@
+package blackjack.domain.card;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+public class DeckFactory {
+
+ private static final List<Card> cardsDeck;
+
+ static {
+ cardsDeck = createCardsDeck();
+ }
+
+ private static List<Card> createCardsDeck() {
+ List<Card> cards = new ArrayList<>();
+
+ for (Denomination denomination : Denomination.values()) {
+ cards.addAll(createCards(denomination));
+ }
+ return cards;
+ }
+
+ private static List<Card> createCards(Denomination denomination) {
+ List<Card> cards = new ArrayList<>();
+
+ for (Type type : Type.values()) {
+ cards.add(new Card(denomination, type));
+ }
+
+ return cards;
+ }
+
+ public static List<Card> createDeck() {
+ return Collections.unmodifiableList(cardsDeck);
+ }
+}
+
+ | Java | ์คํํฑ๋ธ๋ก์ผ๋ก ๋ณ๊ฒฝํ์ต๋๋ค.
๊ธฐ๋ฅ์ ๋ฑํธ๋ฅผ ์ฌ์ฉํ ์ฝ๋์ ์ ํํ ๋์ผํ๊ฑด๊ฐ์? |
@@ -0,0 +1,38 @@
+package blackjack.domain.card;
+
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class CardTest {
+
+ @DisplayName("์นด๋ ๊ฐ์ฒด์ ์ซ์์ ์ข
๋ฅ๊ฐ์ด ๊ฐ์ผ๋ฉด ๊ฐ์ ๊ฐ์ฒด๋ก ํ๋จํ๋ค")
+ @Test
+ void equalsTest() {
+ //given, when, then
+ assertThat(new Card(Denomination.TWO, Type.DIAMOND))
+ .isEqualTo(new Card(Denomination.TWO, Type.DIAMOND));
+
+ }
+
+ @DisplayName("์นด๋ ๊ฐ์ฒด์ ์ซ์์ ์ข
๋ฅ๋ฅผ ์ถ๋ ฅํ๋ค")
+ @Test
+ void printCardTwoDiamond() {
+ //given
+ Card card = new Card(Denomination.TWO, Type.DIAMOND);
+
+ //when, then
+ assertThat(card).hasToString("2๋ค์ด์๋ชฌ๋");
+ }
+
+ @DisplayName("์นด๋ ๊ฐ์ฒด์ ์ซ์์ ์ข
๋ฅ๋ฅผ ์ถ๋ ฅํ๋ค")
+ @Test
+ void printCardAceHeart() {
+ //given
+ Card card = new Card(Denomination.ACE, Type.HEART);
+
+ //when, then
+ assertThat(card.toString()).isEqualTo("Aํํธ");
+ }
+} | Java | assert๋ฌธ์ผ๋ก ๋ฌธ์์ด์ ๋น๊ตํ ๋๋ hasToString๋ฉ์๋๋ฅผ ์ฌ์ฉํ๊ฒ ์ต๋๋ค. |
@@ -0,0 +1,102 @@
+package blackjack.domain.participant;
+
+import blackjack.domain.card.Card;
+import blackjack.domain.card.Denomination;
+import lombok.Getter;
+import org.apache.commons.lang3.StringUtils;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+
+@Getter
+public abstract class Participant {
+ private static final int DIFFERENCE_OF_ACE_SCORE = 10;
+ private static final int BLACKJACK = 21;
+ private static final int ZERO = 0;
+ private static final String CHECK_NULL_OR_EMPTY = "์ด๋ฆ์ด ๋น ์นธ ํน์ null ๊ฐ์ด ์๋์ง ํ์ธํด์ฃผ์ธ์.";
+ private static final String CHECK_CONTAINING_ONLY_LETTERS_AND_DIGITS = "์ด๋ฆ์ ํน์๋ฌธ์๋ฅผ ํฌํจํ์ง ์์ ๋ฌธ์์ ์ซ์๋ก ์ง์ ํด์ฃผ์ธ์.";
+
+ private final String name;
+ private final List<Card> cards;
+
+ protected Participant(String name) {
+ validateName(name);
+
+ this.name = name;
+ this.cards = new ArrayList<>();
+ }
+
+ private void validateName(String name) {
+ validateNullOrEmpty(name);
+ validateAlphaNumeric(name);
+ }
+
+ private void validateNullOrEmpty(String name) {
+ if (StringUtils.isBlank(name)) {
+ throw new IllegalArgumentException(CHECK_NULL_OR_EMPTY);
+ }
+ }
+
+ private void validateAlphaNumeric(String name) {
+ if (!StringUtils.isAlphanumericSpace(name)) {
+ throw new IllegalArgumentException(CHECK_CONTAINING_ONLY_LETTERS_AND_DIGITS);
+ }
+ }
+
+ protected abstract boolean drawable();
+
+ public void receiveCard(Card card) {
+ cards.add(card);
+ }
+
+ public int getCardsSum() {
+ int scoreOfAceAsEleven = sumOfCardsScore();
+ int aceCount = getAceCount();
+
+ while (canCountAceAsOne(scoreOfAceAsEleven, aceCount)) {
+ scoreOfAceAsEleven = scoreOfAceAsOne(scoreOfAceAsEleven);
+ aceCount--;
+ }
+
+ return scoreOfAceAsEleven;
+ }
+
+ private int scoreOfAceAsOne(int scoreOfAceAsEleven) {
+ return scoreOfAceAsEleven - DIFFERENCE_OF_ACE_SCORE;
+ }
+
+ private boolean canCountAceAsOne(int scoreOfAceAsEleven, int aceCount) {
+ return scoreOfAceAsEleven > BLACKJACK && aceCount > ZERO;
+ }
+
+ private int getAceCount() {
+ return (int) cards.stream()
+ .filter(Card::isAce)
+ .count();
+ }
+
+ private int sumOfCardsScore() {
+ return cards.stream()
+ .map(Card::getDenomination)
+ .mapToInt(Denomination::getScore)
+ .sum();
+ }
+
+ public boolean isBust() {
+ return getCardsSum() > BLACKJACK;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ Participant that = (Participant) o;
+ return Objects.equals(name, that.name) && Objects.equals(cards, that.cards);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(name, cards);
+ }
+} | Java | ์ด ๋ถ๋ถ ์ดํด๊ฐ ์ ์ ๋๋๋ฐ์,
์ ์๊ฐ์๋ Participant๊ฐ ๊ฐ์ง ์นด๋ ๋ชฉ๋ก์ ๋ฐ๋ผ ์์ด์ค๋ฅผ 1๋ก ๊ณ์ฐํ ์ง, 11๋ก ๊ณ์ฐํ ์ง ๋ค๋ฅด๊ฒ ํ๋จํด์ผ ํ๊ธฐ ๋๋ฌธ์
Participant์ ๋ก์ง์ธ ๊ฒ ๊ฐ์ต๋๋ค.
Denomination ์ธ๋ถ์ ์กฐ๊ฑด์ ๋ฐ๋ผ 1 ํน์ 11๋ก ๊ณ์ฐ๋๊ธฐ ๋๋ฌธ์ Denomination์ ํฌํจํ ์์ ๊ตฌ์กฐ์์ ๊ฒฐ์ ํ๋ ๊ฒ ๋ง๋ค๊ณ ์๊ฐํฉ๋๋ค.
Denomination์ score๋ฅผ 1๋ก ๊ฐ์ง๋ enum์ ์ถ๊ฐํด์ ๋ฆฌํฉํ ๋ง์ ์๋ํด๋ดค๋๋ฐ ์ด๋ป๊ฒ ํด์ผ ํ ์ง ์ ๋ชจ๋ฅด๊ฒ ์ต๋๋ค. |
@@ -0,0 +1,27 @@
+package blackjack.domain.participant;
+
+import lombok.Getter;
+
+@Getter
+public class Player extends Participant {
+
+ private static final int PLAYER_DRAW_THRESHOLD = 21;
+ private static final String DEALER_NAME = "๋๋ฌ";
+ private static final String CHECK_SAME_NAME_AS_DEALER = "์ด๋ฆ์ ๋๋ฌ์ ๊ฐ์ ์ ์์ผ๋ ๋ค๋ฅธ ์ด๋ฆ์ ์ง์ ํด์ฃผ์ธ์.";
+
+ public Player(String name) {
+ super(name);
+ validateDealerNameDuplicated(name);
+ }
+
+ private void validateDealerNameDuplicated(String name) {
+ if (name.equals(DEALER_NAME)) {
+ throw new IllegalArgumentException(CHECK_SAME_NAME_AS_DEALER);
+ }
+ }
+
+ @Override
+ public boolean drawable() {
+ return getCardsSum() < PLAYER_DRAW_THRESHOLD;
+ }
+} | Java | ๋ง์ํ์ ๋ถ๋ถ์ด ๋ง๋ค๊ณ ์๊ฐํฉ๋๋ค. ๋ฌธ์์ด ์์ฑ ๋ก์ง์ view๋ก ์ด๋ํ์ต๋๋ค. |
@@ -0,0 +1,27 @@
+package blackjack.domain.participant;
+
+import lombok.Getter;
+
+@Getter
+public class Player extends Participant {
+
+ private static final int PLAYER_DRAW_THRESHOLD = 21;
+ private static final String DEALER_NAME = "๋๋ฌ";
+ private static final String CHECK_SAME_NAME_AS_DEALER = "์ด๋ฆ์ ๋๋ฌ์ ๊ฐ์ ์ ์์ผ๋ ๋ค๋ฅธ ์ด๋ฆ์ ์ง์ ํด์ฃผ์ธ์.";
+
+ public Player(String name) {
+ super(name);
+ validateDealerNameDuplicated(name);
+ }
+
+ private void validateDealerNameDuplicated(String name) {
+ if (name.equals(DEALER_NAME)) {
+ throw new IllegalArgumentException(CHECK_SAME_NAME_AS_DEALER);
+ }
+ }
+
+ @Override
+ public boolean drawable() {
+ return getCardsSum() < PLAYER_DRAW_THRESHOLD;
+ }
+} | Java | orElseThrow๋ก ์์ ํ๊ณ , ๋ฉ์ธ์ง๋ฅผ ๋ด์ ์์ธ๋ฅผ ๋์ง๋๋ก ํ์ต๋๋ค. |
@@ -1,16 +1,28 @@
package webserver;
-import java.io.DataOutputStream;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import webserver.controller.*;
+import webserver.domain.HttpRequest;
+import webserver.domain.HttpResponse;
+
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import java.util.HashMap;
+import java.util.Map;
public class RequestHandler implements Runnable {
private static final Logger logger = LoggerFactory.getLogger(RequestHandler.class);
+ private static final Map<String, Controller> controllers = new HashMap<>();
+
+ static {
+ controllers.put("/user/create", new CreateUserController());
+ controllers.put("/user/login", new LoginController());
+ controllers.put("/user/list", new ListUserController());
+ controllers.put("/user/list.html", new ListUserController());
+ }
private Socket connection;
@@ -21,35 +33,12 @@ public RequestHandler(Socket connectionSocket) {
public void run() {
logger.debug("New Client Connect! Connected IP : {}, Port : {}", connection.getInetAddress(),
connection.getPort());
-
try (InputStream in = connection.getInputStream(); OutputStream out = connection.getOutputStream()) {
- // TODO ์ฌ์ฉ์ ์์ฒญ์ ๋ํ ์ฒ๋ฆฌ๋ ์ด ๊ณณ์ ๊ตฌํํ๋ฉด ๋๋ค.
- DataOutputStream dos = new DataOutputStream(out);
- byte[] body = "Hello World".getBytes();
- response200Header(dos, body.length);
- responseBody(dos, body);
- } catch (IOException e) {
- logger.error(e.getMessage());
- }
- }
-
- private void response200Header(DataOutputStream dos, int lengthOfBodyContent) {
- try {
- dos.writeBytes("HTTP/1.1 200 OK \r\n");
- dos.writeBytes("Content-Type: text/html;charset=utf-8\r\n");
- dos.writeBytes("Content-Length: " + lengthOfBodyContent + "\r\n");
- dos.writeBytes("\r\n");
- } catch (IOException e) {
- logger.error(e.getMessage());
- }
- }
-
- private void responseBody(DataOutputStream dos, byte[] body) {
- try {
- dos.write(body, 0, body.length);
- dos.flush();
+ HttpRequest httpRequest = new HttpRequest(in);
+ HttpResponse httpResponse = new HttpResponse(out);
+ controllers.getOrDefault(httpRequest.getPath(), new DefaultController()).service(httpRequest, httpResponse);
} catch (IOException e) {
logger.error(e.getMessage());
}
}
-}
+}
\ No newline at end of file | Java | path์ ๋ง๋ Controller ์ ์ ์ข์ต๋๋ค ๐ |
@@ -0,0 +1,80 @@
+package webserver.controller;
+
+import webserver.domain.HttpRequest;
+import webserver.domain.HttpResponse;
+import webserver.domain.HttpStatusCode;
+import webserver.exceptions.InvalidRequestException;
+import webserver.exceptions.NotYetSentException;
+
+public abstract class AbstractController implements Controller {
+
+ public void service(HttpRequest request, HttpResponse response) {
+ try {
+ System.out.println(request.getMethod().name() + " " + request.getPath());
+ methodMapping(request, response);
+ } catch (Exception e) {
+ if(!response.isSent()){
+ System.out.println("์์ ์ปจํธ๋กค๋ฌ์์ ์ฒ๋ฆฌ ๋๋ฝ๋ ์์ธ ์ํฉ : " + e.getMessage());
+ e.printStackTrace();
+ response.send(HttpStatusCode.NOT_IMPLEMENTED, e.getMessage());
+ }
+ } finally {
+ if (!response.isSent()) {
+ response.send(HttpStatusCode.INTERNAL_SERVER_ERROR);
+ throw new NotYetSentException("response์ ๋ฉ์๋ send()๊ฐ ํธ์ถ๋์ง ์์์ต๋๋ค");
+ }
+ }
+ }
+
+ private void methodMapping(HttpRequest request, HttpResponse response) {
+ switch (request.getMethod()) {
+ case GET:
+ validateGetRequest(request, response);
+ doGet(request, response);
+ return;
+ case POST:
+ validatePostRequest(request, response);
+ doPost(request, response);
+ return;
+ case PUT:
+ validatePutRequest(request, response);
+ doPut(request, response);
+ return;
+ case DELETE:
+ validateDeleteRequest(request, response);
+ doDelete(request, response);
+ return;
+ default:
+ response.send(HttpStatusCode.METHOD_NOT_ALLOWED);
+ }
+ }
+
+ public void doPost(HttpRequest request, HttpResponse response) {
+ response.send(HttpStatusCode.METHOD_NOT_ALLOWED);
+ }
+
+ public void doGet(HttpRequest request, HttpResponse response) {
+ response.send(HttpStatusCode.METHOD_NOT_ALLOWED);
+ }
+
+ public void doPut(HttpRequest request, HttpResponse response) {
+ response.send(HttpStatusCode.METHOD_NOT_ALLOWED);
+ }
+
+ public void doDelete(HttpRequest request, HttpResponse response) {
+ response.send(HttpStatusCode.METHOD_NOT_ALLOWED);
+ }
+
+ // ํ์์์ ์ค๋ฒ๋ผ์ด๋ฉ ํ์ฌ ์ธํ๊ฐ์ ๊ฒ์ฆํ๋ค
+ public void validatePostRequest(HttpRequest request, HttpResponse response) throws InvalidRequestException {
+ }
+
+ public void validateGetRequest(HttpRequest request, HttpResponse response) throws InvalidRequestException {
+ }
+
+ public void validatePutRequest(HttpRequest request, HttpResponse response) throws InvalidRequestException {
+ }
+
+ public void validateDeleteRequest(HttpRequest request, HttpResponse response) throws InvalidRequestException {
+ }
+} | Java | ์ถ์ ํด๋์ค service ๋ฉ์๋์ ํ๋ฆ์ ์ ๋ฆฌํ์ฌ ํ
ํ๋ฆฟ ๋ฉ์๋ ํจํด์ผ๋ก ์ ์ฉํด์ฃผ์
จ๋ค์ ๐ ๐ฏ |
@@ -0,0 +1,21 @@
+package webserver.controller;
+
+import utils.FileIoUtils;
+import webserver.domain.HttpRequest;
+import webserver.domain.HttpResponse;
+import webserver.domain.HttpStatusCode;
+
+import java.io.IOException;
+import java.net.URISyntaxException;
+
+public class DefaultController extends AbstractController {
+ @Override
+ public void doGet(HttpRequest httpRequest, HttpResponse httpResponse) {
+ try {
+ httpResponse.send(HttpStatusCode.OK, FileIoUtils.readStaticHttpFile(httpRequest.getPath()));
+ } catch (URISyntaxException | IOException e) {
+ httpResponse.send(HttpStatusCode.NOT_FOUND);
+ }
+ }
+
+} | Java | http://localhost:8080/index.html ๋ก ์ ์ํ์ ๋ ์ ์์ ์ธ ํ์ด์ง ํธ์ถ์ด ๋์ง ์๊ณ ์์ด์.
(index ๋ฟ๋ง ์๋๋ผ ์ ์ฒด์ ์ผ๋ก ์นํ์ด์ง ์๋ต์ด ์๋ชป ๋ ๊ฒ ๊ฐ์ต๋๋ค!)
์ด ๋ถ๋ถ ํ์ธ ๋ถํ๋๋ฆฝ๋๋ค. ๊ทธ๋ฆฌ๊ณ ํด๋น ๋ฉ์๋๋ Controller์ ๊ด์ฌ์ฌ๊ฐ ์๋๊ฒ ๊ฐ์์!
์ ํธ์ฑ ํด๋์ค๋ก ๋ง๋ค์ด์ง๋ ๊ฒ์ด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค! |
@@ -0,0 +1,32 @@
+package webserver.controller;
+
+import webserver.domain.HttpHeader;
+import webserver.domain.HttpRequest;
+import webserver.domain.HttpResponse;
+import webserver.domain.HttpStatusCode;
+import webserver.exceptions.InvalidRequestException;
+
+import java.io.IOException;
+
+import static service.JwpService.getProfilePage;
+import static service.JwpService.isLogin;
+
+public class ListUserController extends AbstractController {
+ @Override
+ public void doGet(HttpRequest httpRequest, HttpResponse httpResponse) {
+ try {
+ httpResponse.send(HttpStatusCode.OK, getProfilePage());
+ } catch (IOException e) {
+ httpResponse.send(HttpStatusCode.INTERNAL_SERVER_ERROR, "์ฝ์ด๋ค์ด๋๋ฐ ๋ฌธ์ ๊ฐ ๋ฐ์ํ์์ต๋๋ค");
+ }
+ }
+
+ @Override
+ public void validateGetRequest(HttpRequest request, HttpResponse response) throws InvalidRequestException {
+ if (!isLogin(request.getHeaders().get(HttpHeader.COOKIE))) {
+ response.getHeaders().add(HttpHeader.LOCATION, "/user/login.html");
+ response.send(HttpStatusCode.FOUND);
+ throw new InvalidRequestException("์๋ชป๋ ๋ก๊ทธ์ธ ์์ฒญ");
+ }
+ }
+} | Java | TemplateView๋ฅผ ๋ง๋๋ ๋ถ๋ถ๋ Controller ๋ณด๋ค๋ ๋ค๋ฅธ ๊ณณ์์ ์ฌ์ฉํ ์ ์๋๋ก ์ ํธ์ฑ ํด๋์ค๋ก ๋ถ๋ฆฌํ๋๊ฒ ์ด๋จ๊น์? |
@@ -0,0 +1,32 @@
+package webserver.controller;
+
+import webserver.domain.HttpHeader;
+import webserver.domain.HttpRequest;
+import webserver.domain.HttpResponse;
+import webserver.domain.HttpStatusCode;
+import webserver.exceptions.InvalidRequestException;
+
+import java.io.IOException;
+
+import static service.JwpService.getProfilePage;
+import static service.JwpService.isLogin;
+
+public class ListUserController extends AbstractController {
+ @Override
+ public void doGet(HttpRequest httpRequest, HttpResponse httpResponse) {
+ try {
+ httpResponse.send(HttpStatusCode.OK, getProfilePage());
+ } catch (IOException e) {
+ httpResponse.send(HttpStatusCode.INTERNAL_SERVER_ERROR, "์ฝ์ด๋ค์ด๋๋ฐ ๋ฌธ์ ๊ฐ ๋ฐ์ํ์์ต๋๋ค");
+ }
+ }
+
+ @Override
+ public void validateGetRequest(HttpRequest request, HttpResponse response) throws InvalidRequestException {
+ if (!isLogin(request.getHeaders().get(HttpHeader.COOKIE))) {
+ response.getHeaders().add(HttpHeader.LOCATION, "/user/login.html");
+ response.send(HttpStatusCode.FOUND);
+ throw new InvalidRequestException("์๋ชป๋ ๋ก๊ทธ์ธ ์์ฒญ");
+ }
+ }
+} | Java | login ์ํ์ธ์ง ์ฌ๋ถ๋ฅผ Request๊ฐ ์ ์ ์์ง ์์๊น์? ํด๋น ํ๋์ Request์๊ฒ ์์ํด์ค์๋ค! |
@@ -0,0 +1,46 @@
+package webserver.controller;
+
+import db.DataBase;
+import model.User;
+import webserver.domain.*;
+import webserver.exceptions.InvalidRequestException;
+
+public class LoginController extends AbstractController {
+ private static final String INVALID_REQUEST_MESSAGE = "userId, password๊ฐ ํ์ํฉ๋๋ค";
+ @Override
+ public void doPost(HttpRequest httpRequest, HttpResponse httpResponse) {
+ User findUser = DataBase.findUserById(httpRequest.getParameters().get("userId"));
+ if(findUser == null){
+ sendLoginFailed(httpResponse);
+ return;
+ }
+ if (!findUser.getPassword().equals(httpRequest.getParameters().get("password"))) {
+ sendLoginFailed(httpResponse);
+ return;
+ }
+ sendLoginSucceeded(httpResponse);
+ }
+
+ @Override
+ public void validatePostRequest(HttpRequest request, HttpResponse response) throws InvalidRequestException {
+ HttpParameters httpParameters = request.getParameters();
+ if (httpParameters.contain("userId") && httpParameters.contain("password")) {
+ return;
+ }
+ response.send(HttpStatusCode.BAD_REQUEST, INVALID_REQUEST_MESSAGE);
+ throw new InvalidRequestException(INVALID_REQUEST_MESSAGE);
+ }
+
+ private void sendLoginSucceeded(HttpResponse httpResponse) {
+ httpResponse.getHeaders().add(HttpHeader.SET_COOKIE, "logined=true; Path=/");
+ httpResponse.getHeaders().add(HttpHeader.LOCATION, "/index.html");
+ httpResponse.send(HttpStatusCode.FOUND);
+ }
+
+ private void sendLoginFailed(HttpResponse httpResponse) {
+ httpResponse.getHeaders().add(HttpHeader.SET_COOKIE, "logined=false; Path=/");
+ httpResponse.getHeaders().add(HttpHeader.LOCATION, "/user/login_failed.html");
+ httpResponse.send(HttpStatusCode.FOUND);
+ }
+
+} | Java | response header์ cookie, location ์
ํ
ํด์ฃผ๋ ๋ถ๋ถ์ Response๋ก ์ฑ
์์ ์ด๋์ํฌ ์ ์์ง ์์๊น์?
Controller์์ ๋ก๊ทธ์ธ์ฌ๋ถ์ location๋ง httpResponse์๊ฒ ๋๊ธฐ๋ฉด ์์์ ์
ํ
๋์ด์ผํ ๊ฒ ๊ฐ์์ :) |
@@ -0,0 +1,80 @@
+package webserver.domain;
+
+import utils.IOUtils;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+
+
+public class HttpRequest {
+ private final HttpHeaders headers;
+ private final HttpParameters parameters;
+ private HttpMethod method;
+ private String body;
+ private String path;
+
+ public HttpRequest(InputStream in) throws IOException {
+ headers = new HttpHeaders();
+ parameters = new HttpParameters();
+ BufferedReader reader = new BufferedReader(new InputStreamReader(in));
+
+ readFirstLine(reader);
+ readHeaders(reader);
+ if (headers.contain(HttpHeader.CONTENT_LENGTH)) {
+ body = IOUtils.readData(reader, Integer.parseInt(headers.get(HttpHeader.CONTENT_LENGTH)));
+ parameters.parseAndSet(body);
+ }
+ }
+
+ private void readFirstLine(BufferedReader reader) throws IOException {
+ String[] firstLineTokens = reader.readLine().split(" ");
+ String requestUrl = firstLineTokens[1];
+ method = HttpMethod.valueOf(firstLineTokens[0]);
+ parseUrl(requestUrl);
+ }
+
+ private void readHeaders(BufferedReader reader) throws IOException {
+ String line = reader.readLine();
+ while (isValid(line)) {
+ String[] header = line.split(": ");
+ headers.add(header[0], header[1]);
+ line = reader.readLine();
+ }
+ }
+
+ private boolean isValid(String line) {
+ return (line != null) && !"".equals(line);
+ }
+
+ private void parseUrl(String requestUrl) {
+ if (requestUrl.indexOf('?') == -1) {
+ path = requestUrl;
+ return;
+ }
+ String[] urlToken = requestUrl.split("\\?");
+ path = urlToken[0];
+ parameters.parseAndSet(urlToken[1]);
+ }
+
+ public HttpHeaders getHeaders() {
+ return headers;
+ }
+
+ public HttpParameters getParameters() {
+ return parameters;
+ }
+
+ public HttpMethod getMethod() {
+ return method;
+ }
+
+ public String getBody() {
+ return body;
+ }
+
+ public String getPath() {
+ return path;
+ }
+} | Java | Request-Line์ ํ์ฑํ ๋ 1, 0 ๊ณผ ๊ฐ์ ์๋ฏธ๋ฅผ ์ฐพ๊ธฐ ์ด๋ ค์ด ๋ก์ง์ด ์กด์ฌํ๋๋ฐ์!
firstLine์ ์คํ์ Method SP Request-URI SP HTTP-Version CRLF ์ผ๋ก ์ ์๋ฉ๋๋ค.
์คํ์ ๋งค์น ํจํด์ผ๋ก ์ ์ํ๊ณ ๊ทธ์ ๋ง๊ฒ Index ์๋ฏธ๋ฅผ ๋ถ์ฌํด์ฃผ๋๊ฑด ์ด๋จ๊น์? |
@@ -0,0 +1,21 @@
+package webserver.controller;
+
+import utils.FileIoUtils;
+import webserver.domain.HttpRequest;
+import webserver.domain.HttpResponse;
+import webserver.domain.HttpStatusCode;
+
+import java.io.IOException;
+import java.net.URISyntaxException;
+
+public class DefaultController extends AbstractController {
+ @Override
+ public void doGet(HttpRequest httpRequest, HttpResponse httpResponse) {
+ try {
+ httpResponse.send(HttpStatusCode.OK, FileIoUtils.readStaticHttpFile(httpRequest.getPath()));
+ } catch (URISyntaxException | IOException e) {
+ httpResponse.send(HttpStatusCode.NOT_FOUND);
+ }
+ }
+
+} | Java | ์นํ์ด์ง๊ฐ ์ ๋จ๋๊ฒ ์๋๋ผ์ ์์ค๋ ์ ๋ฐ์์ค๋๋ฐ ์ ๊ทธ๋ฌ๋ ์ถ์๋๋ฐ, ๋ฒ๊ทธ์๋ค์. ์ ๊ณ ์ณ์ ๋ฐ์ํ ๊ฒ์! |
@@ -0,0 +1,80 @@
+package webserver.domain;
+
+import utils.IOUtils;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+
+
+public class HttpRequest {
+ private final HttpHeaders headers;
+ private final HttpParameters parameters;
+ private HttpMethod method;
+ private String body;
+ private String path;
+
+ public HttpRequest(InputStream in) throws IOException {
+ headers = new HttpHeaders();
+ parameters = new HttpParameters();
+ BufferedReader reader = new BufferedReader(new InputStreamReader(in));
+
+ readFirstLine(reader);
+ readHeaders(reader);
+ if (headers.contain(HttpHeader.CONTENT_LENGTH)) {
+ body = IOUtils.readData(reader, Integer.parseInt(headers.get(HttpHeader.CONTENT_LENGTH)));
+ parameters.parseAndSet(body);
+ }
+ }
+
+ private void readFirstLine(BufferedReader reader) throws IOException {
+ String[] firstLineTokens = reader.readLine().split(" ");
+ String requestUrl = firstLineTokens[1];
+ method = HttpMethod.valueOf(firstLineTokens[0]);
+ parseUrl(requestUrl);
+ }
+
+ private void readHeaders(BufferedReader reader) throws IOException {
+ String line = reader.readLine();
+ while (isValid(line)) {
+ String[] header = line.split(": ");
+ headers.add(header[0], header[1]);
+ line = reader.readLine();
+ }
+ }
+
+ private boolean isValid(String line) {
+ return (line != null) && !"".equals(line);
+ }
+
+ private void parseUrl(String requestUrl) {
+ if (requestUrl.indexOf('?') == -1) {
+ path = requestUrl;
+ return;
+ }
+ String[] urlToken = requestUrl.split("\\?");
+ path = urlToken[0];
+ parameters.parseAndSet(urlToken[1]);
+ }
+
+ public HttpHeaders getHeaders() {
+ return headers;
+ }
+
+ public HttpParameters getParameters() {
+ return parameters;
+ }
+
+ public HttpMethod getMethod() {
+ return method;
+ }
+
+ public String getBody() {
+ return body;
+ }
+
+ public String getPath() {
+ return path;
+ }
+} | Java | ๋งค์น ํจํด ์ข๋ค์ ์์ง ๋ฐ์์ ๋ชปํ์์ง๋ง ๋งค์น ํจํด์ด๋ผ๋ ์์ด๋์ด ์๋ ค์ฃผ์
์ ๊ฐ์ฌํฉ๋๋ค |
@@ -0,0 +1,46 @@
+package webserver.controller;
+
+import db.DataBase;
+import model.User;
+import webserver.domain.*;
+import webserver.exceptions.InvalidRequestException;
+
+public class LoginController extends AbstractController {
+ private static final String INVALID_REQUEST_MESSAGE = "userId, password๊ฐ ํ์ํฉ๋๋ค";
+ @Override
+ public void doPost(HttpRequest httpRequest, HttpResponse httpResponse) {
+ User findUser = DataBase.findUserById(httpRequest.getParameters().get("userId"));
+ if(findUser == null){
+ sendLoginFailed(httpResponse);
+ return;
+ }
+ if (!findUser.getPassword().equals(httpRequest.getParameters().get("password"))) {
+ sendLoginFailed(httpResponse);
+ return;
+ }
+ sendLoginSucceeded(httpResponse);
+ }
+
+ @Override
+ public void validatePostRequest(HttpRequest request, HttpResponse response) throws InvalidRequestException {
+ HttpParameters httpParameters = request.getParameters();
+ if (httpParameters.contain("userId") && httpParameters.contain("password")) {
+ return;
+ }
+ response.send(HttpStatusCode.BAD_REQUEST, INVALID_REQUEST_MESSAGE);
+ throw new InvalidRequestException(INVALID_REQUEST_MESSAGE);
+ }
+
+ private void sendLoginSucceeded(HttpResponse httpResponse) {
+ httpResponse.getHeaders().add(HttpHeader.SET_COOKIE, "logined=true; Path=/");
+ httpResponse.getHeaders().add(HttpHeader.LOCATION, "/index.html");
+ httpResponse.send(HttpStatusCode.FOUND);
+ }
+
+ private void sendLoginFailed(HttpResponse httpResponse) {
+ httpResponse.getHeaders().add(HttpHeader.SET_COOKIE, "logined=false; Path=/");
+ httpResponse.getHeaders().add(HttpHeader.LOCATION, "/user/login_failed.html");
+ httpResponse.send(HttpStatusCode.FOUND);
+ }
+
+} | Java | Response์ ๋๊ฒจ์ฃผ๋ ค๊ณ ํ์์ง๋ง Response๊ฐ ์์ํ๊ฒ HTTP ์คํ์ ๋ฐ๋ฅธ ์ ์ก๋ง ๋๋๋ก ๊ฐ๊ฒฐํ๊ฒ ์ง์ฌ์ ธ์์ด์ ์ค๊ฐ ํด๋์ค๋ฅผ ๋ง๋๋ ๋ฐฉ๋ฒ์ผ๋ก ๊ณ ๋ฏผํด๋ณด๊ณ ์์ด์. |
@@ -0,0 +1,32 @@
+package webserver.controller;
+
+import webserver.domain.HttpHeader;
+import webserver.domain.HttpRequest;
+import webserver.domain.HttpResponse;
+import webserver.domain.HttpStatusCode;
+import webserver.exceptions.InvalidRequestException;
+
+import java.io.IOException;
+
+import static service.JwpService.getProfilePage;
+import static service.JwpService.isLogin;
+
+public class ListUserController extends AbstractController {
+ @Override
+ public void doGet(HttpRequest httpRequest, HttpResponse httpResponse) {
+ try {
+ httpResponse.send(HttpStatusCode.OK, getProfilePage());
+ } catch (IOException e) {
+ httpResponse.send(HttpStatusCode.INTERNAL_SERVER_ERROR, "์ฝ์ด๋ค์ด๋๋ฐ ๋ฌธ์ ๊ฐ ๋ฐ์ํ์์ต๋๋ค");
+ }
+ }
+
+ @Override
+ public void validateGetRequest(HttpRequest request, HttpResponse response) throws InvalidRequestException {
+ if (!isLogin(request.getHeaders().get(HttpHeader.COOKIE))) {
+ response.getHeaders().add(HttpHeader.LOCATION, "/user/login.html");
+ response.send(HttpStatusCode.FOUND);
+ throw new InvalidRequestException("์๋ชป๋ ๋ก๊ทธ์ธ ์์ฒญ");
+ }
+ }
+} | Java | Request ์ ์์ํ๋ฉด ํ๋ผ๋ฏธํฐ๋ฅผ ๋งคํํ๊ณ , ๊ฐ์ ํ ๋นํ๋ Request ์ญํ ๊น์ง๋ง ๋งก๊ธด ์ํ๋ผ ์ค๊ฐ ํด๋์ค๋ฅผ ๋ง๋๋ ๋ฐฉ์์ผ๋ก ๊ณ ๋ฏผ์ ํด๋ณด์์ด์. ๊ทธ๋ฌ๋ค๊ฐ, Spring ์ ์๋ ArgumentResolver ์ ์ ์ฌํ๊ฒ, ๊ฒ์ฆ์ด ํ์ํ ๋์๋ง ์ค๋ฒ๋ผ์ด๋ฉ ํ๋๋ก AbstractController์ validate...Request ๋ผ๋ ๋ฉ์๋๋ค์ ๋ง๋ค์ด ๋ณด์์ต๋๋ค.
์ด ๊ฒฝ์ฐ, ๋ก๊ทธ์ธ์ด ํ์ํ ์ ์ฌํ ์ปจํธ๋กค๋ฌ์ ๋ํด์ ์ค๋ณต ์ฝ๋๊ฐ ์์ฑ๋๋ค๋ ๋ถ๋ด์ด ์๋๋ฐ, ๋ก๊ทธ์ธ ์๋น์ค๋ฅผ ํตํฉํ๋ ์ถ์ ๊ฐ์ฒด์ธ ๋ก๊ทธ์ธ ์ปจํธ๋กค๋ฌ๋ฅผ ๋ง๋ค๊ฑฐ๋, ๋์ค์ MVC ๋ชจ๋ธ์ธ ์ด๋
ธํ
์ด์
์ ์ ์ฉํ ๊นํ๋๋ฐ ์ด๋ฐ ๋ฐฉ์์ ์ด๋ค๊ฐ์? |
@@ -0,0 +1,45 @@
+package controller;
+
+import controller.handler.Handler;
+import exception.utils.NoFileException;
+import model.request.HttpRequest;
+import model.response.HttpResponse;
+import model.PathInfo;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public abstract class Controller {
+ private static final Logger log = LoggerFactory.getLogger( Controller.class );
+ protected final Map<PathInfo, Handler> handlers = new HashMap<>();
+ protected String basePath = "";
+
+ public void putHandler(String path, String method, Handler handler) {
+ handlers.put(new PathInfo(basePath + path, method), handler);
+ }
+
+ public void setBasePath(String basePath) {
+ this.basePath = basePath;
+ }
+
+ public boolean hasSameBasePath(String path) {
+ return path.startsWith(basePath);
+ }
+
+ public boolean handle(HttpRequest request, HttpResponse response) throws NoFileException, IOException {
+ for (Map.Entry<PathInfo, Handler> entry : handlers.entrySet()) {
+ log.info("matching {} with controller {}", request.getPath(), entry.getKey().getPath());
+
+ if (request.getPath().matches(entry.getKey().getPath())) {
+ log.info("handling {} with controller {}", request.getPath(), entry.getKey().getPath());
+ entry.getValue().handle(request, response);
+ return true;
+ }
+ }
+ return false;
+ }
+} | Java | handlers ๋ ๊ตณ์ด LinkedHashMap ์ ์ฌ์ฉํ ์ด์ ๊ฐ ์์๊น์? |
@@ -0,0 +1,30 @@
+package model;
+
+import java.util.Objects;
+
+public class PathInfo {
+ private final String path;
+ private final String method;
+
+ public PathInfo(String path, String method) {
+ this.path = path;
+ this.method = method;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ PathInfo that = (PathInfo) o;
+ return Objects.equals(path, that.path) && Objects.equals(method, that.method);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(path, method);
+ }
+
+ public String getPath() {
+ return path;
+ }
+} | Java | PathInfo ๊ฐ์ฒด๋ฅผ ๋ณ๋๋ก ์ ์ธํ์
จ๊ตฐ์ ๐ฏ |
@@ -0,0 +1,44 @@
+package controller;
+
+import controller.handler.SecuredHandler;
+import model.request.HttpRequest;
+import model.response.HttpResponse;
+import service.UserService;
+import view.View;
+
+import java.io.IOException;
+import java.io.OutputStream;
+
+public class UserController extends Controller {
+ {
+ setBasePath("/user");
+ putHandler("/create", "POST", this::handleCreate);
+ putHandler("/login", "POST", this::handleLogin);
+ putHandler("/list", "GET", new SecuredHandler(this::handleUserList));
+ putHandler("/logout", "GET", new SecuredHandler(this::handleLogout));
+ }
+
+ private UserService userService = new UserService();
+
+ public void handleCreate(HttpRequest request, HttpResponse response) {
+ userService.addUser(request.getParsedBody());
+ response.sendRedirect("/index.html");
+ }
+
+ public void handleLogin(HttpRequest request, HttpResponse response) {
+ if (!userService.login(request.getParsedBody())) {
+ response.setCookie("logined=false").sendRedirect("/user/login_failed.html");
+ return;
+ }
+ response.setCookie("logined=true").sendRedirect("/index.html");
+ }
+
+ public void handleUserList(HttpRequest request, HttpResponse response) throws IOException {
+ byte[] body = View.getUsersView(userService.findAll(), "/user/list");
+ response.sendView(body);
+ }
+
+ public void handleLogout(HttpRequest request, HttpResponse response) throws IOException {
+ response.setCookie("logined=false").sendRedirect("/index.html");
+ }
+} | Java | DataBase ์ ์ง์ ์ ๊ทผํ์ง ๋ง๊ณ ๋ณ๋์ ์๋น์ค ํด๋์ค๋ก ๋ถ๋ฆฌํด๋ณด๋ฉด ์ด๋จ๊น์? |
@@ -0,0 +1,44 @@
+package controller;
+
+import controller.handler.SecuredHandler;
+import model.request.HttpRequest;
+import model.response.HttpResponse;
+import service.UserService;
+import view.View;
+
+import java.io.IOException;
+import java.io.OutputStream;
+
+public class UserController extends Controller {
+ {
+ setBasePath("/user");
+ putHandler("/create", "POST", this::handleCreate);
+ putHandler("/login", "POST", this::handleLogin);
+ putHandler("/list", "GET", new SecuredHandler(this::handleUserList));
+ putHandler("/logout", "GET", new SecuredHandler(this::handleLogout));
+ }
+
+ private UserService userService = new UserService();
+
+ public void handleCreate(HttpRequest request, HttpResponse response) {
+ userService.addUser(request.getParsedBody());
+ response.sendRedirect("/index.html");
+ }
+
+ public void handleLogin(HttpRequest request, HttpResponse response) {
+ if (!userService.login(request.getParsedBody())) {
+ response.setCookie("logined=false").sendRedirect("/user/login_failed.html");
+ return;
+ }
+ response.setCookie("logined=true").sendRedirect("/index.html");
+ }
+
+ public void handleUserList(HttpRequest request, HttpResponse response) throws IOException {
+ byte[] body = View.getUsersView(userService.findAll(), "/user/list");
+ response.sendView(body);
+ }
+
+ public void handleLogout(HttpRequest request, HttpResponse response) throws IOException {
+ response.setCookie("logined=false").sendRedirect("/index.html");
+ }
+} | Java | ์์ ๋ง์ฐฌ๊ฐ์ง๋ก ์ง์ DataBase ์ ์ ๊ทผํ๊ธฐ ๋ณด๋ค ์๋น์ค ๊ฐ์ฒด๋ฅผ ์ฌ์ฉํ๋ ๋ฐฉ๋ฒ์ ์ด๋จ๊น์?
๋๊ฒจ์ค ๊ฐ์ ๊ธฐ๋ฐ์ผ๋ก ๋ก๊ทธ์ธ ๋์๋์ง ๋์ง ์์๋์ง ์ฌ๋ถ๋ฅผ boolean ๊ฐ์ผ๋ก ์กฐํํ ์ ์๋ค๋ฉด
์ข ๋ ๊ฐ๊ฒฐํ ์ฝ๋๋ก ๊ฐ์ ํ ์ ์์๊ฒ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,45 @@
+package controller;
+
+import controller.handler.Handler;
+import exception.utils.NoFileException;
+import model.request.HttpRequest;
+import model.response.HttpResponse;
+import model.PathInfo;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public abstract class Controller {
+ private static final Logger log = LoggerFactory.getLogger( Controller.class );
+ protected final Map<PathInfo, Handler> handlers = new HashMap<>();
+ protected String basePath = "";
+
+ public void putHandler(String path, String method, Handler handler) {
+ handlers.put(new PathInfo(basePath + path, method), handler);
+ }
+
+ public void setBasePath(String basePath) {
+ this.basePath = basePath;
+ }
+
+ public boolean hasSameBasePath(String path) {
+ return path.startsWith(basePath);
+ }
+
+ public boolean handle(HttpRequest request, HttpResponse response) throws NoFileException, IOException {
+ for (Map.Entry<PathInfo, Handler> entry : handlers.entrySet()) {
+ log.info("matching {} with controller {}", request.getPath(), entry.getKey().getPath());
+
+ if (request.getPath().matches(entry.getKey().getPath())) {
+ log.info("handling {} with controller {}", request.getPath(), entry.getKey().getPath());
+ entry.getValue().handle(request, response);
+ return true;
+ }
+ }
+ return false;
+ }
+} | Java | handle ๋ฉ์๋์ ์ฒซ๋ฒ์งธ ์ธ์๋ HttpRequest ์ธ๋ฐ, ๋๋ฒ์งธ ์ธ์๋ OutputStream ์ด๋ค์.
HttpRequest / HttpResponse ํํ๊ฐ ๋ ์ ํฉํด ๋ณด์
๋๋ค ๐ |
@@ -0,0 +1,66 @@
+package controller;
+
+import controller.error.ErrorHandlerFactory;
+import controller.handler.Handler;
+import exception.utils.NoFileException;
+import model.request.HttpRequest;
+import model.response.HttpResponse;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import webserver.RequestHandler;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.Socket;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
+
+public class ControllerManager {
+ private static final Logger log = LoggerFactory.getLogger(RequestHandler.class);
+ private static final List<Controller> controllers = new ArrayList<>();
+ static {
+ registerController(new ViewController());
+ registerController(new UserController());
+ }
+
+ public static void registerController(Controller controller) {
+ controllers.add(controller);
+ }
+
+ public static void runControllers(Socket connection) {
+ try (InputStream in = connection.getInputStream(); OutputStream out = connection.getOutputStream()) {
+ HttpRequest httpRequest = HttpRequest.of(in);
+ HttpResponse httpResponse = HttpResponse.of(out);
+ handleRequest(httpRequest, httpResponse);
+ } catch (IOException e) {
+ log.error("{} {}", e.getMessage(), e.getStackTrace());
+ }
+ }
+
+ private static void handleRequest(HttpRequest httpRequest, HttpResponse httpResponse) {
+ List<Controller> selectedControllers = controllers.stream()
+ .filter(controller -> controller.hasSameBasePath(httpRequest.getPath()))
+ .collect(Collectors.toList());
+ try {
+ for (Controller controller : selectedControllers) {
+ if (controller.handle(httpRequest, httpResponse)) return;
+ }
+
+ defaultHandle(httpRequest, httpResponse);
+ } catch (NoFileException | IOException | RuntimeException e) {
+ Handler errorHandler = ErrorHandlerFactory.getHandler(e);
+ try {
+ errorHandler.handle(httpRequest, httpResponse);
+ log.warn(e.getMessage());
+ } catch (Exception handleError) {
+ log.error("{} {}", handleError.getMessage(), handleError.getStackTrace());
+ }
+ }
+ }
+
+ public static void defaultHandle(HttpRequest request, HttpResponse response) throws NoFileException {
+ response.forward("./templates", request.getPath());
+ }
+} | Java | ์ปจํธ๋กค๋ฌ ๋งค๋์ ๊น์ง ์์ฑํ์
จ๋ค์ ๐ |
@@ -1,16 +1,48 @@
package model;
+import exception.user.WrongEmailException;
+import exception.user.WrongIdException;
+import exception.user.WrongNameException;
+import exception.user.WrongPasswordException;
+
public class User {
- private String userId;
- private String password;
- private String name;
- private String email;
+ private final String userId;
+ private final String password;
+ private final String name;
+ private final String email;
public User(String userId, String password, String name, String email) {
- this.userId = userId;
- this.password = password;
- this.name = name;
- this.email = email;
+ this.userId = validateId(userId);
+ this.password = validatePw(password);
+ this.name = validateName(name);
+ this.email = validateEmail(email.replace("%40", "@"));
+ }
+
+ private String validatePw(String password) {
+ if(!password.matches("^[\\w]{1,30}$")){
+ throw new WrongPasswordException();
+ }
+ return password;
+ }
+
+ private String validateId(String userId) {
+ if(!userId.matches("^[\\w]{1,30}$"))
+ throw new WrongIdException();
+ return userId;
+ }
+
+ private String validateName(String name) {
+ if (!name.matches("^[\\w๊ฐ-ํฃ]{1,30}$")) {
+ throw new WrongNameException();
+ }
+ return name;
+ }
+
+ private String validateEmail(String email) {
+ if(!email.matches("^[\\w]{1,30}@[\\w]{1,30}.[\\w]{1,30}$")){
+ throw new WrongEmailException();
+ }
+ return email;
}
public String getUserId() { | Java | validation ๋ก์ง์ ์ถ๊ฐํ์ ๊ฒ์ ๊ธ์ ์ ์
๋๋ค.
๋ค๋ง User ๊ฐ์ฒด๊ฐ ์ธ์คํด์คํ ๋ ๋๋ง๋ค validate ๋ฉ์๋๊ฐ ํธ์ถ๋๊ฒ ๋๋๋ฐ์.
User ๋ผ๋ ๋๋ฉ์ธ ๋ชจ๋ธ์ด ๊ฐ์ถ๊ณ ์์ด์ผํ ํ์์ ์ธ validation ์ธ์ง
์๋๋ฉด ์๋ก์ด User ๋ฅผ ์์ฑํ๋ ์ฌ์ฉ์์ ์์ฒญ์์๋ง ํ์ํ validation ์ธ์ง์ ๋ฐ๋ผ์
User ๊ฐ์ฒด์์ ์ฒ๋ฆฌํ๋๊ฒ ์ ํฉํ ์๋ ์๊ณ / Controller ์์ญ์์ ์ฒ๋ฆฌํ๋ ๊ฒ์ด ๋ ๋์ ์๋ ์์ต๋๋ค.
์ด๋ถ๋ถ์ ํ๋ฒ ๊ณ ๋ฏผํด๋ด์ฃผ์ธ์ ๐ |
@@ -0,0 +1,7 @@
+package exception.utils;
+
+public class NoFileException extends Exception {
+ public NoFileException(String path) {
+ super(path + " ํ์ผ์ ์ฐพ์ ์ ์์ต๋๋ค.");
+ }
+} | Java | NoFIleException ๊ณผ ๊ฐ์ ๊ฒฝ์ฐ์๋ ์ด๋ค ํ์ผ์ ์ฐพ์ ์ ์๋์ง ํ์๋ ์ ์๊ฒ ๊ฐ์ ๋๋ฉด ๋ ์ข๊ฒ ์ต๋๋ค. |
@@ -0,0 +1,30 @@
+package controller;
+
+import exception.utils.NoFileException;
+import model.request.HttpRequest;
+import model.response.HttpResponse;
+
+import java.io.IOException;
+import java.io.OutputStream;
+
+public class ViewController extends Controller {
+
+ {
+ setBasePath("");
+ putHandler("/js/.*", "GET", this::handleFile);
+ putHandler("/css/.*", "GET", this::handleFile);
+ putHandler("/fonts/.*", "GET", this::handleFile);
+ putHandler("/favicon.ico", "GET", this::handleFile);
+ putHandler("/index.html", "GET", this::handleView);
+ putHandler("/", "GET", this::handleView);
+ }
+
+ public void handleFile(HttpRequest request, HttpResponse response) throws NoFileException {
+ response.forward("./static", request.getPath());
+ }
+
+ public void handleView(HttpRequest request, HttpResponse response) throws NoFileException {
+ response.forward("./templates",
+ (request.getPath().equals("/") ? "/index.html" : request.getPath()));
+ }
+} | Java | 
Fonts ํ์ผ์ด ๋ก๋ฉ๋์ง ์๋ ํ์์ด ์์ต๋๋ค. ํ์ธ ๋ถํ๋๋ ค์ :smile |
@@ -0,0 +1,45 @@
+package controller;
+
+import controller.handler.Handler;
+import exception.utils.NoFileException;
+import model.request.HttpRequest;
+import model.response.HttpResponse;
+import model.PathInfo;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public abstract class Controller {
+ private static final Logger log = LoggerFactory.getLogger( Controller.class );
+ protected final Map<PathInfo, Handler> handlers = new HashMap<>();
+ protected String basePath = "";
+
+ public void putHandler(String path, String method, Handler handler) {
+ handlers.put(new PathInfo(basePath + path, method), handler);
+ }
+
+ public void setBasePath(String basePath) {
+ this.basePath = basePath;
+ }
+
+ public boolean hasSameBasePath(String path) {
+ return path.startsWith(basePath);
+ }
+
+ public boolean handle(HttpRequest request, HttpResponse response) throws NoFileException, IOException {
+ for (Map.Entry<PathInfo, Handler> entry : handlers.entrySet()) {
+ log.info("matching {} with controller {}", request.getPath(), entry.getKey().getPath());
+
+ if (request.getPath().matches(entry.getKey().getPath())) {
+ log.info("handling {} with controller {}", request.getPath(), entry.getKey().getPath());
+ entry.getValue().handle(request, response);
+ return true;
+ }
+ }
+ return false;
+ }
+} | Java | Handlers ๊ฐ ์์๋ฅผ ๊ธฐ๋ฐ์ผ๋ก ๋ฑ๋ก๋์ด์ผ ํ ํ์๊ฐ ์๋ค๋ฉด ์ฐจํ์ ์ค์ํ๊ธฐ ์ฌ์ด ๊ตฌ์กฐ ์
๋๋ค.
path ๋ฅผ ๊ธฐ๋ฐ์ผ๋ก ๋์ํ handler ๊ฐ ๋ค๋ฅธ ๋ฐฉ์์ผ๋ก ๋งค์นญ๋ ์๋ ์์์ง ๊ณ ๋ฏผํด๋ด์ฃผ์ธ์ ๐ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.