Eugene Yoo

캡스톤 디자인2 커밋

Showing 362 changed files with 5063 additions and 1 deletions
# 프로젝트 주제: 최신 웹 구조 습득 및 실습
# 캡스톤 디자인 2 주제: 최신 웹 구조 습득 및 실습
# 프로젝트 주제: React와 오픈 API를 활용한 최신 웹 구조 습득 및 실습
## 컴퓨터 공학과 2016104135 - 유유진
React, Vue, Apollo, Graph.QL과 같은 최신 웹 기술을 사용하여 퍼포먼스도 뛰어나고 유연한 웹서비스를 구현해보도록 한다.
# 실행 방법
프로젝트 소스코드 폴더에서 **npm install .**로 모듈을 설치한 뒤 터미널에 **C:/`{프로젝트 위치}`> yarn dev**를 치면 실행된다.
*데이터를 제외하고 업로드해서 정상적인 작동은 하지 않습니다. 시연 때 보신 결과와 최종보고서 및 실행결과 사진을 확인해주세요.*
# 폴더 구성 설명
## 면담 보고서
각 월별 면담 보고서 (3~6)월 면담보고서가 들어 있습니다. 대면 면담을 한 것은 사진을 첨부했고, 서면으로 면담한 것은 사진이 첨부되어 있지 않습니다.
## 진행과제
프로젝트를 진행하기에 앞서 필요한 지식을 습득하기 위해 HTML + CSS + JavaScript를 공부, 실습하는 과제를 내주셨고 관련 과제 결과를 담았습니다.
## 진행 보고서
캡스톤 디자인 2를 진행하면서 제출한 보고서를 담았습니다. 주제(프로젝트 계획), 중간, 기말보고서로 나뉩니다.
## 프로젝트
프로젝트 하면서 작성한 소스코드를 모았습니다. 크롤러, 프로젝트, 실행결과 사진이 있고 추가로 웹페이지 기획안과 최종발표자료까지 함께 들어있습니다.
실행결과 사진은 탭 순서대로 구성되어 있습니다. 검색 결과는 1~5까지 있는데 검색 결과 Top3와 원형 그래프, 그 아래에 나오는 요일 별 수치를 보여주는 막대 그래프 캡처로 구성되어 있습니다.
......
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>회원가입</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function () {
$("#datepicker").datepicker();
//여기 #은 id인데 <p>Date: <input type="text" id="datepicker"></p> 이렇게 넣을때
//type은 text id를 datepicker로 사용
});
</script>
<style>
.ui-widget-header {background:navy; color:#fff;}
.btn{width: 100px; height:50px; background: none; border:none; padding:0;}
/*크기 설정 해주고 background, border, padding을 none, 0으로 초기화*/
button img{width:90%;}/*부모(button)가 할당해준 값에서 최대치를 사용하도록 설정해서 button도 설정이 들어가게*/
</style>
</head>
<body>
<form action="#" method="POST">
<!-- 전송될 무언가는 반드시 form으로 감싸져야한다.,
이게 어디로 전송될지 action 다음 스크립트 파일을 적어주면 된다.-->
<!--서버에 어떻게 전송할지에 대한 방법이 적혀야함(method) form옆에는 반드시 따라붙음 -->
<!-- post = 암호화, get 암호화x 주소표시줄에 같이 표시되서 묻어간다.-->
<!-- 개발자 도구에서 확인해보면 옆에 메소드가 붙어있음 회원가입은 암호화해야하니까 post-->
<fieldset>
<!--필드셋으로 묶고 legend 라벨링-->
<legend>필수 입력 사항</legend>
<p>
<label for="name">이름: </label>
<input id="name" type="text" name="username">
<!--name 데이터베이스의 필드(애트리뷰트)명이다.-->
<!-- 경우 프로그래머끼리 협의를 보거나 백앤드 작업자를 위해 비워두고 커스텀하게 한다.-->
</p>
<!--패러그래프: tab 역할을 한다.-->
<p>
<label for="email">이메일: </label>
<input id="email" type="email" name="useremail">
<!--input(사용자 입력 가능칸) label 붙어 있어야 한다 이때 적절한 id 주자 id==for 매치-->
<!-- input에는 type 있는데 type 설정해서 우리가 원하는 형태로 데이터를 받을 있음 -->
<!-- email type 걸면 브라우저가 이메일 형식 이외의 것을 차단함-->
</p>
<p>
<label for="password">비밀번호: </label>
<input id="password" type="password" name="userpassword">
<!--type password시에 가려서 나옴-->
</p>
</fieldset>
<fieldset>
<legend>선택 입력 사항</legend>
<p>
<label for="datepicker">생년월일: </label>
<input id="datepicker" type="date" name="userpassword">
<!--달력은 크롬이나 파폭에서는 type 구현이 되어있는데 이번엔 jQuery 라이브러리로 활용해보자-->
<!--라이브러리를 쓰면 어느 환경에서든 같은 달력을 있다. 기본을 쓰면 어느 브라우저는 나올 수도 있음-->
</p>
<p>
<span>거주지를 선택해주세요.</span>
<select name="user address"><!--미리 값이 있고 골라라 할때 사용-->
<option value ="" disabled>거주지를 선택해주세요</option> <!-- 경우 선택이 안댐-->
<option value="서울시">서울시</option>
<option value="경기도">경기도</option>
<option value="충청도">충청도</option>
<option value="제주도">제주도</option>
</select>
</p>
<p>
<span>취미는</span>
<label for="coding">코딩</label>
<input id="coding" type="checkbox" name="userinterest">
<label for="game">게임</label>
<input id="game" type="checkbox" name="userinterest">
<!--여기서 label input 연동을 안해두면 글씨를 클릭했을때는 체크가 되지 않는다.-->
</p>
<p>
<span>성별</span>
<label for="male">남성</label>
<input id="male" type="radio" value = "남성" name ="sex">
<label for="female">여성</label>
<input id="female" type="radio" value = "여성" name ="sex">
</p>
<p>
<span>기타 사항</span>
<textarea name ="usermessage"></textarea><!--크기가 자율적임-->
<textarea name ="usermessage" rows="10" cols="30"></textarea>
<!-- <textarea>(이곳)<textarea> 엔터가 들어가면 공백이 들어가보임, 들어가면 안댐-->
<!--만약 사이에 텍스트가 들어가면 스크롤로 자동 전환 된다.-->
<textarea name ="contract" readonly ="readonly" rows="10" cols="30">아파치 하둡은 대량의 자료를 처리할 있는 컴퓨터 클러스터에서 동작하는 분산 응용 프로그램을 지원하는 프리웨어 자바 소프트웨어 프레임워크이다. 원래 너치의 분산 처리를 지원하기 위해 개발된 것으로, 아파치 루씬의 하부 프로젝트이다. 위키백과 작성 언어: 자바 최초 출시일: 2006 4 1 개발자: 아파치 소프트웨어 재단 라이선스: 아파치 라이선스 2.0 안정화 버전: 3.0.0 / 2017 12 13 종류: 분산 파일 시스템</textarea>
<!--위의 readonly 옵션을 주면 수정 불가. 저렇게 value값이 같을 경우 readonly 생략가능-->
</p>
</fieldset>
<input type="submit" value="회원 가입" /> <!-- 전송해주는 형태 + value -> 안에 들어갈 -->
<input type="reset" value="재작성" />
<input type="button" value="뒤로 가기" onclick="history.go(-1)"/>
<!-- input value 있는 값이 나오고 button 가운뎃값이 나온다.-->
<!--
<hr/>
<input class ="btn" type="image" src="send.png" alt="send"/>
<button class ="btn" type="submit"><img src="send.png" alt="send"></button>-->
<!-- input button 이미지를 넣는 방식 개의 이미지가 다르다. button 무조건
테두리(border, background) 생기는데 이때 필요없을 경우css에서 없애야 한다.-->
</form>
<!--<fieldset>
<legend>CSS Test</legend>
<p style="color: blue">Lorem ipsum dolor.</p>-->
<!--Inline Style Sheet: 속성과 값만 들어감 꾸미는데 한계가 있고, 재사용 불가-->
<!--Internal Style Sheet: <style>(여기)</style> 작성하는 방식
<style>
h1{
color : blue;
}
</style>
이러면 문서 안의 h1의 모든 요소가 파란색 글자를 가지게 된다.
보통 <head></head>사시에 넣으나 html 문서의 어디에 넣어도 적용이 잘 되며, 이 방법은 html 문서 안의
여러 요소를 한번에 꾸밀 수 있다는 장점이 있으나, 또 다른 html 문서에는 적용할 수 없다는 단점이 있다.
-->
<!--Linking Style Sheet: 별도로 CSS 파일을 만들고 html 문서와 연결하는 방법이다. 예를 들어 h1 요소의 글자를
빨간색으로 하고 싶다면, 다음의; 내용으로 style.css 파일을 만든다
style.css--------------
| h1{ |
| color: red; |
| } |
-----------------------.
이후 적용을 원하는 html 문서에
<link rel="stylesheet" href="style.css">
코드를 추가한다. 경로는 html과 같이 있을 경우 위처럼 쓰고
문서가 있는 폴더에 css 폴더가 있고, 그 안에 style.css 파일이 있다면 다음과 같이 해야한다.
<link rel="stylesheet" href="css/style.css">
-->
<!--</fieldset>-->
</body>
</html>
\ No newline at end of file
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>회원가입</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function () {
$("#datepicker").datepicker();
//여기 #은 id인데 <p>Date: <input type="text" id="datepicker"></p> 이렇게 넣을때
//type은 text id를 datepicker로 사용
});
</script>
<style>
.ui-widget-header {background:navy; color:#fff;}
.btn{width: 100px; height:50px; background: none; border:none; padding:0;}
/*크기 설정 해주고 background, border, padding을 none, 0으로 초기화*/
button img{width:90%;}/*부모(button)가 할당해준 값에서 최대치를 사용하도록 설정해서 button도 설정이 들어가게*/
</style>
</head>
<body>
<form action="#" method="POST">
<!-- 전송될 무언가는 반드시 form으로 감싸져야한다.,
이게 어디로 전송될지 action 다음 스크립트 파일을 적어주면 된다.-->
<!--서버에 어떻게 전송할지에 대한 방법이 적혀야함(method) form옆에는 반드시 따라붙음 -->
<!-- post = 암호화, get 암호화x 주소표시줄에 같이 표시되서 묻어간다.-->
<!-- 개발자 도구에서 확인해보면 옆에 메소드가 붙어있음 회원가입은 암호화해야하니까 post-->
<fieldset>
<!--필드셋으로 묶고 legend 라벨링-->
<legend>필수 입력 사항</legend>
<p>
<label for="name">이름: </label>
<input id="name" type="text" name="username">
<!--name 데이터베이스의 필드(애트리뷰트)명이다.-->
<!-- 경우 프로그래머끼리 협의를 보거나 백앤드 작업자를 위해 비워두고 커스텀하게 한다.-->
</p>
<!--패러그래프: tab 역할을 한다.-->
<p>
<label for="email">이메일: </label>
<input id="email" type="email" name="useremail">
<!--input(사용자 입력 가능칸) label 붙어 있어야 한다 이때 적절한 id 주자 id==for 매치-->
<!-- input에는 type 있는데 type 설정해서 우리가 원하는 형태로 데이터를 받을 있음 -->
<!-- email type 걸면 브라우저가 이메일 형식 이외의 것을 차단함-->
</p>
<p>
<label for="password">비밀번호: </label>
<input id="password" type="password" name="userpassword">
<!--type password시에 가려서 나옴-->
</p>
</fieldset>
<fieldset>
<legend>선택 입력 사항</legend>
<p>
<label for="datepicker">생년월일: </label>
<input id="datepicker" type="date" name="userpassword">
<!--달력은 크롬이나 파폭에서는 type 구현이 되어있는데 이번엔 jQuery 라이브러리로 활용해보자-->
<!--라이브러리를 쓰면 어느 환경에서든 같은 달력을 있다. 기본을 쓰면 어느 브라우저는 나올 수도 있음-->
</p>
<p>
<span>거주지를 선택해주세요.</span>
<select name="user address"><!--미리 값이 있고 골라라 할때 사용-->
<option value ="" disabled>거주지를 선택해주세요</option> <!-- 경우 선택이 안댐-->
<option value="서울시">서울시</option>
<option value="경기도">경기도</option>
<option value="충청도">충청도</option>
<option value="제주도">제주도</option>
</select>
</p>
<p>
<span>취미는</span>
<label for="coding">코딩</label>
<input id="coding" type="checkbox" name="userinterest">
<label for="game">게임</label>
<input id="game" type="checkbox" name="userinterest">
<!--여기서 label input 연동을 안해두면 글씨를 클릭했을때는 체크가 되지 않는다.-->
</p>
<p>
<span>성별</span>
<label for="male">남성</label>
<input id="male" type="radio" value = "남성" name ="sex">
<label for="female">여성</label>
<input id="female" type="radio" value = "여성" name ="sex">
</p>
<p>
<span>기타 사항</span>
<textarea name ="usermessage"></textarea><!--크기가 자율적임-->
<textarea name ="usermessage" rows="10" cols="30"></textarea>
<!-- <textarea>(이곳)<textarea> 엔터가 들어가면 공백이 들어가보임, 들어가면 안댐-->
<!--만약 사이에 텍스트가 들어가면 스크롤로 자동 전환 된다.-->
<textarea name ="contract" readonly ="readonly" rows="10" cols="30">아파치 하둡은 대량의 자료를 처리할 있는 컴퓨터 클러스터에서 동작하는 분산 응용 프로그램을 지원하는 프리웨어 자바 소프트웨어 프레임워크이다. 원래 너치의 분산 처리를 지원하기 위해 개발된 것으로, 아파치 루씬의 하부 프로젝트이다. 위키백과 작성 언어: 자바 최초 출시일: 2006 4 1 개발자: 아파치 소프트웨어 재단 라이선스: 아파치 라이선스 2.0 안정화 버전: 3.0.0 / 2017 12 13 종류: 분산 파일 시스템</textarea>
<!--위의 readonly 옵션을 주면 수정 불가. 저렇게 value값이 같을 경우 readonly 생략가능-->
</p>
</fieldset>
<input type="submit" value="회원 가입" /> <!-- 전송해주는 형태 + value -> 안에 들어갈 -->
<input type="reset" value="재작성" />
<input type="button" value="뒤로 가기" onclick="history.go(-1)"/>
<!-- input value 있는 값이 나오고 button 가운뎃값이 나온다.-->
<!--
<hr/>
<input class ="btn" type="image" src="send.png" alt="send"/>
<button class ="btn" type="submit"><img src="send.png" alt="send"></button>-->
<!-- input button 이미지를 넣는 방식 개의 이미지가 다르다. button 무조건
테두리(border, background) 생기는데 이때 필요없을 경우css에서 없애야 한다.-->
</form>
<!--<fieldset>
<legend>CSS Test</legend>
<p style="color: blue">Lorem ipsum dolor.</p>-->
<!--Inline Style Sheet: 속성과 값만 들어감 꾸미는데 한계가 있고, 재사용 불가-->
<!--Internal Style Sheet: <style>(여기)</style> 작성하는 방식
<style>
h1{
color : blue;
}
</style>
이러면 문서 안의 h1의 모든 요소가 파란색 글자를 가지게 된다.
보통 <head></head>사시에 넣으나 html 문서의 어디에 넣어도 적용이 잘 되며, 이 방법은 html 문서 안의
여러 요소를 한번에 꾸밀 수 있다는 장점이 있으나, 또 다른 html 문서에는 적용할 수 없다는 단점이 있다.
-->
<!--Linking Style Sheet: 별도로 CSS 파일을 만들고 html 문서와 연결하는 방법이다. 예를 들어 h1 요소의 글자를
빨간색으로 하고 싶다면, 다음의; 내용으로 style.css 파일을 만든다
style.css--------------
| h1{ |
| color: red; |
| } |
-----------------------.
이후 적용을 원하는 html 문서에
<link rel="stylesheet" href="style.css">
코드를 추가한다. 경로는 html과 같이 있을 경우 위처럼 쓰고
문서가 있는 폴더에 css 폴더가 있고, 그 안에 style.css 파일이 있다면 다음과 같이 해야한다.
<link rel="stylesheet" href="css/style.css">
-->
<!--</fieldset>-->
</body>
</html>
\ No newline at end of file
<!DOCTYPE html>
<html lang="ko">
<head>
<style type="text/css">
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: "맑은 고딕";
font-size: 0.75em;
color: #333;
}
#login-form {
width: 250px;
margin: 100px auto;
border: 10px solid skyblue;
border-radius: 5px;
padding: 15px;
}
#login-form label {
display: block;
}
#login-form label {
margin-top: 10px;
}
#login-form input {
margin-top: 5px;
}
/* 애트리뷰트 선택자 */
#login-form input[type='image'] {
margin: 0px auto;
width: 90px;
height: 40px;
}
#login-form input[type='button'] {
background: url( "images/join.png" ) no-repeat;
background-position: center center;
background-size: contain;
border: none;
width: 90px;
height: 50px;
}
</style>
</head>
<body>
<form id="login-form" action="#" method="POST">
<label class="Legend" for="id">아이디</label>
<input id="id" type="text" maxlength="20" name="userid" />
<label class="Legend" for="password">패스워드</label>
<input id="password" type="password" maxlength="20" name="userpassword"/>
</br></br>
<input type="image" src="images/login_btn.png" value="로그인">
<input type="button" onclick="location.href='join.html'"/>
</form>
</body>
</html>
\ No newline at end of file
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>회원가입</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function () {
$("#datepicker").datepicker();
});
</script>
<style>
body{
background: #34495e;
margin: 0;
}
.box{
width: 300px;
padding: 40px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
background: #191919;
text-align: center;
}
.box h1{
color: white;
text-transform: uppercase;
font-weight: 500;
}
.box input[type="text"],.box input[type="password"], .box input[type="email"]{
border:0;
background: none;
margin: 20px auto;
text-align: center;
border: 2px solid #3498db;
padding: 14px 10px;
width: 200px;
outline: none;
color: white;
border-radius: 24px;
transition: 0.25s;
cursor: pointer;
}
.box input[type="text"]:focus,.box input[type="password"]:focus, .box input[type="email"]:focus{
width: 280px;
border-color:#2ecc71;
}
.box input[type="submit"]:hover, .box input[type="button"]:hover, .box input[type="reset"]:hover{
background:#2ecc71;
}
.ui-widget-header {background:navy; color:#fff;}
input[class="btn"]{
border: none;
color: white;
font-family: NanumSquareWeb;
font-size: large;
font-weight: bold;
text-align: center;
border-radius: 20px;
width: 32%;
height: 40px;
float: left;
}
input[id="submit"]{
background-color: #191919;
border: 2px solid #3498db;
}
input[id="reset"]{
background-color: #191919;
border: 2px solid #3498db;
}
input[id="back"]{
background-color: #191919;
border: 2px solid #3498db;
}
button img{width:90%;}
@media(max-width: 577px ){
input[class='btn'] {
width: 100%;
}
}
</style>
</head>
<body>
<form class="box" action="#" method="POST">
<h1>필수 입력 사항</h1>
<p>
<input id="name" type="text" name="username" placeholder="Name">
</p>
<p>
<input id="password" type="password" name="userpassword" placeholder="Password">
</p>
<p>
<input id="email" type="email" name="useremail" placeholder="Email">
</p>
<input class="btn" id="submit" type="submit" background-color="" value="회원 가입" /> <!-- 전송해주는 형태 + value -> 안에 들어갈 값-->
<input class="btn" id="reset" type="reset" value="재작성" />
<input class="btn" id="back" type="button" value="뒤로 가기" onclick="history.go(-1)"/>
</form>
</body>
</html>
\ No newline at end of file
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1" />
<style type="text/css">
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
/*모든 element에 적용되는 것 */
@font-face {
font-family: NanumSquareWeb;
src: local(NanumSquareR),
local(NanumSquare),
url(NanumSquareR.eot?#iefix) format('embedded-opentype'),
url(NanumSquareR.woff) format('woff'),
url(NanumSquareR.ttf) format('truetype');
font-style: normal;
font-weight: normal;
unicode-range: U+0-10FFFF;
}
h1 {
font-family: NanumSquareWeb, sans-serif;
}
body {
font-family: "맑은 고딕";
font-size: 0.75em;
color: #333;
}
#login-form {
width: 250px;
height: 250px;
margin: 100px auto;
border: 10px solid skyblue;
border-radius: 5px;
padding: 15px;
}
#login-form label {
display: block;
}
#login-form label {
margin-top: 10px;
}
#login-form input {
margin-top: 5px;
}
/* 애트리뷰트 선택자 */
#login-form input[type='image'] {
margin: 0px auto;
background-size: cover;
width: 90px;
height: 40px;
}
#login-form input[id='Lbutton'] {
background-color: orange;
border: none;
color: white;
font-family: NanumSquareWeb;
font-size: large;
font-weight: bold;
text-align: center;
border-radius: 20px;
width: 100%;
height: 40px;
float: left;
}
#login-form input[id='Jbutton'] {
background-color: red;
font-size: large;
font-weight: bold;
text-align: center;
font-family: NanumSquareWeb;
border-radius: 20px;
border: none;
color: white;
width: 100%;
height: 40px;
float: left;
}
@media(min-width: 577px ){
#login-form {
height: 200px;
}
#login-form input[id='Jbutton'] {
width: 50%;
}
#login-form input[id='Lbutton'] {
width: 50%;
}
}
</style>
</head>
<body>
<form id="login-form" action="#" method="POST">
<label class="Legend" for="id">아이디</label>
<input id="id" type="text" maxlength="20" name="userid" />
<label class="Legend" for="password">패스워드</label>
<input id="password" type="password" maxlength="20" name="userpassword" />
</br></br>
<div class="btn">
<input id="Lbutton" type="button" name="login" value="Login">
<input id="Jbutton" type="button" name="join" onclick="location.href='join.html'" value="Join">
</div>
</form>
</body>
</html>
\ No newline at end of file
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>회원가입</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function () {
$("#datepicker").datepicker();
});
</script>
<style>
body {
background: #34495e;
margin: 0;
}
.box {
width: 300px;
padding: 40px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: #191919;
text-align: center;
}
.box h1 {
color: white;
text-transform: uppercase;
font-weight: 500;
}
.box input[type="text"],
.box input[type="password"],
.box input[type="email"] {
border: 0;
background: none;
margin: 20px auto;
text-align: center;
border: 2px solid #3498db;
padding: 14px 10px;
width: 200px;
outline: none;
color: white;
border-radius: 24px;
transition: 0.25s;
cursor: pointer;
}
.box input[type="text"]:focus,
.box input[type="password"]:focus,
.box input[type="email"]:focus {
width: 280px;
border-color: #2ecc71;
}
.box input[type="submit"]:hover,
.box input[type="button"]:hover,
.box input[type="reset"]:hover {
background: #2ecc71;
}
.ui-widget-header {
background: navy;
color: #fff;
}
input[class="btn"] {
border: none;
color: white;
font-family: NanumSquareWeb;
font-size: large;
font-weight: bold;
text-align: center;
border-radius: 20px;
width: 32%;
height: 40px;
float: left;
}
input[id="submit"] {
background-color: #191919;
border: 2px solid #3498db;
}
input[id="reset"] {
background-color: #191919;
border: 2px solid #3498db;
}
input[id="back"] {
background-color: #191919;
border: 2px solid #3498db;
}
button img {
width: 90%;
}
@media(max-width: 577px) {
input[class='btn'] {
width: 100%;
}
}
</style>
<span id="alert-success" style="display: none;">비밀번호가 일치합니다.</span>
<span id="alert-danger" style="display: none; color: #ffffff; font-weight: bold; ">비밀번호가 일치하지 않습니다.</span>
</head>
<body>
<form class="box" action="#" method="POST" onsubmit="return checkAll(this)">
<h1>필수 입력 사항</h1>
<input id="id" type="text" name="userid" placeholder="ID" required>
<input id="name" type="text" name="username" placeholder="Name" required>
<input class="pw" id="password" type="password" name="userpassword" placeholder="Password" required>
<input class="pw" id="password_check" type="password" name="userpassword_check" placeholder="Password Check" required>
<input id="email" type="email" name="useremail" placeholder="Email" required>
<input class="btn" id="submit" type="submit" background-color="" value="회원 가입" />
<!-- 전송해주는 형태 + value -> 안에 들어갈 값-->
<input class="btn" id="reset" type="reset" value="재작성" />
<input class="btn" id="back" type="button" value="뒤로 가기" onclick="history.go(-1)" />
</form>
<script language="javascript">
function checkAll(form) {
if (!checkUserId(form.userid.value)) {
return false;
}
if (!checkPassword(form.userid.value, form.userpassword.value, form.userpassword_check.value)) {
return false;
}
if (!checkMail(form.useremail.value)) {
return false;
}
return true;
}
function checkUserId(id) {
//함수 매개변수로 넘어오는 값은 input 태그에 들어가는 값.
//Id가 입력되었는지 확인하기
if (!checkExistData(id, "아이디를"))
return false;
var idRegExp = /^[a-zA-z0-9]{5,15}$/; //아이디 유효성 검사
if (!idRegExp.test(id)) {
alert("아이디는 영문 대소문자와 숫자 5~15자리로 입력해야합니다!");
form.userid.value = "";
document.getElementById(userid).focus();
return false;
}
return true; //확인이 완료되었을 때
}
function checkPassword(id, password1, password2) {
//비밀번호가 입력되었는지 확인하기
if (!checkExistData(password1, "비밀번호를"))
return false;
//비밀번호 확인이 입력되었는지 확인하기
if (!checkExistData(password2, "비밀번호 확인을"))
return false;
var swit = new Boolean(true);
var password1RegExp = /^[a-zA-z0-9]{4,12}$/; //비밀번호 유효성 검사
if (!password1RegExp.test(password1)) {
alert("비밀번호는 영문 대소문자와 숫자 4~12자리로 입력해야합니다!");
document.getElementById(userpassword).focus();
swit = false;
}
//비밀번호와 비밀번호 확인이 맞지 않다면..
if (password1 != password2) {
alert("두 비밀번호가 맞지 않습니다.");
document.getElementById(userpassword_check).focus();
swit = false;
}
//아이디와 비밀번호가 같을 때..
if (id == password1) {
alert("아이디와 비밀번호는 같을 수 없습니다!");
document.getElementById(userid).focus();
document.getElementById(userpassword).focus();
swit = false;
}
if(swit)
{
return true;
}
else{
form.userpassword.value = "";
form.userpassword_check.value = "";
return false;
}
}
function checkMail(email) {
//mail이 입력되었는지 확인하기
if (!checkExistData(mail, "이메일을"))
return false;
var emailRegExp = /^[A-Za-z0-9_]+[A-Za-z0-9]*[@]{1}[A-Za-z0-9]+[A-Za-z0-9]*[.]{1}[A-Za-z]{1,3}$/;
if (!emailRegExp.test(mail)) {
alert("이메일 형식이 올바르지 않습니다!");
form.useremail.value = "";
document.getElementById(useremail).focus();
return false;
}
return true; //확인이 완료되었을 때
}
// 공백확인 함수
function checkExistData(value, dataName) {
if (value == "") {
alert(dataName + " 입력해주세요!");
return false;
}
return true;
}
</script>
</body>
</html>
\ No newline at end of file
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>회원가입</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function () {
$("#datepicker").datepicker();
});
</script>
<style>
body {
background: #34495e;
margin: 0;
}
.box {
width: 300px;
padding: 40px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: #191919;
text-align: center;
}
.box h1 {
color: white;
text-transform: uppercase;
font-weight: 500;
}
.box input[type="text"],
.box input[type="password"],
.box input[type="email"] {
border: 0;
background: none;
margin: 20px auto;
text-align: center;
border: 2px solid #3498db;
padding: 14px 10px;
width: 200px;
outline: none;
color: white;
border-radius: 24px;
transition: 0.25s;
cursor: pointer;
}
.box input[type="text"]:focus,
.box input[type="password"]:focus,
.box input[type="email"]:focus {
width: 280px;
border-color: #2ecc71;
}
.box input[type="submit"]:hover,
.box input[type="button"]:hover,
.box input[type="reset"]:hover {
background: #2ecc71;
}
.ui-widget-header {
background: navy;
color: #fff;
}
input[class="btn"] {
border: none;
color: white;
font-family: NanumSquareWeb;
font-size: large;
font-weight: bold;
text-align: center;
border-radius: 20px;
width: 32%;
height: 40px;
float: left;
}
input[id="submit"] {
background-color: #191919;
border: 2px solid #3498db;
}
input[id="reset"] {
background-color: #191919;
border: 2px solid #3498db;
}
input[id="back"] {
background-color: #191919;
border: 2px solid #3498db;
}
button img {
width: 90%;
}
@media(max-width: 577px) {
input[class='btn'] {
width: 100%;
}
}
</style>
<span id="alert-success" style="display: none;">비밀번호가 일치합니다.</span>
<span id="alert-danger" style="display: none; color: #ffffff; font-weight: bold; ">비밀번호가 일치하지 않습니다.</span>
</head>
<body>
<form class="box" action="#" method="POST">
<div class="Join_form">
<h1>필수 입력 사항</h1>
<div class="div_id" id="div_id">
<input id="id" class="id" type="text" name="userid" placeholder="ID" required>
<div class="div_id_text" id="div_id_text"></div>
</div>
<div class="div_name" id="div_name">
<input id="name" type="text" name="username" placeholder="Name" required>
</div>
<div class="div_pw" id="div_pw">
<input class="pw1" id="password" type="password" name="userpassword" placeholder="Password" required>
<div class="div_pw_text" id="div_pw_text"></div>
</div>
<div class="div_check" id="div_check">
<input class="pw2" id="password_check" type="password" name="userpassword_check"
placeholder="Password Check" required>
<div class="div_check_text" id="div_check_text"></div>
</div>
<div class="div_email" id="div_email">
<input id="email" class="mail" type="email" name="useremail" placeholder="Email" required>
<div class="div_email_text" id="div_email_text"></div>
</div>
<div class="div_btn">
<input class="btn" id="submit" type="submit" background-color="" value="회원 가입" />
<!-- 전송해주는 형태 + value -> 안에 들어갈 값-->
<input class="btn" id="reset" type="reset" value="재작성" />
<input class="btn" id="back" type="button" value="뒤로 가기" onclick="history.go(-1)" />
</div>
</div>
</form>
<script>
var email = $('.mail');
var id = $('.id');
var password = $('.pw1');
var password_check = $('.pw2');
var idRegExp = /^[a-zA-z0-9]{5,15}$/; //아이디 유효성 검사
var emailRegExp = /^[A-Za-z0-9_]+[A-Za-z0-9]*[@]{1}[A-Za-z0-9]+[A-Za-z0-9]*[.]{1}[A-Za-z]{1,3}$/;
email.blur(function () {
if (!emailRegExp.test(email.val())) {
$("input[name='useremail']").css('border-color', '#ff0000');
$("input[name='useremail']").focus();
}
else {
setTimeout(function () { $("input[name='useremail']").css('border-color', '#3498db'); }, 500);
}
});
id.blur(function () {
if (!idRegExp.test(id.val())) {
$("#div_id_text").text("아이디는 5~15자의 영숫자로 만들어주세요.");
$("#div_id_text").css('color', 'red');
$("#div_id_text").css('font-size', '1.5vw');
}
else {
$("#div_id_text").text("");
}
});
password_check.blur(function () {
if (password.val() != '' && password_check.val() != '') {
if (password.val() != password_check.val()) {
$("#div_pw_text").text("비밀번호가 일치하지 않습니다.");
$("#div_pw_text").css('color', 'red');
$("#div_pw_text").css('font-size', '1.5vw');
$("#div_check_text").text("비밀번호가 일치하지 않습니다.");
$("#div_check_text").css('color', 'red');
$("#div_check_text").css('font-size', '1.5vw');
$("input[name='userpassword']").css('border-color', '#ff0000');
$("input[name='userpassword_check']").css('border-color', '#ff0000');
}
else {
$("#div_pw_text").text('');
$("#div_check_text").text('');
setTimeout(function () { $("input[name='userpassword']").css('border-color', '#3498db'); }, 500);
setTimeout(function () { $("input[name='userpassword_check']").css('border-color', '#3498db'); }, 500);
}
}
});
password.blur(function () {
if (password.val() != '' && password_check.val() != '') {
if (password.val() != password_check.val()) {
$("#div_pw_text").text("비밀번호가 일치하지 않습니다.");
$("#div_pw_text").css('color', 'red');
$("#div_pw_text").css('font-size', '1.5vw');
$("#div_check_text").text("비밀번호가 일치하지 않습니다.");
$("#div_check_text").css('color', 'red');
$("#div_check_text").css('font-size', '1.5vw');
$("input[name='userpassword']").css('border-color', '#ff0000');
$("input[name='userpassword_check']").css('border-color', '#ff0000');
}
else {
$("#div_pw_text").text('');
$("#div_check_text").text('');
setTimeout(function () { $("input[name='userpassword']").css('border-color', '#3498db'); }, 500);
setTimeout(function () { $("input[name='userpassword_check']").css('border-color', '#3498db'); }, 500);
}
}
});
</script>
</body>
</html>
\ No newline at end of file
# Default ignored files
/shelf/
/workspace.xml
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
# Editor-based HTTP Client requests
/httpRequests/
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="JavaScriptLibraryMappings">
<file url="file://$PROJECT_DIR$" libraries="{Node.js Core}" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="JavaScriptSettings">
<option name="languageLevel" value="ES6" />
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/df.iml" filepath="$PROJECT_DIR$/.idea/df.iml" />
</modules>
</component>
</project>
\ No newline at end of file
const axios = require('axios');
const mysql = require('mysql2');
const connection = mysql.createConnection({
host: 'localhost',
port: '3307',
user: 'root',
password: 'yj',
database: 'projectdf',
}).promise();
const GetItem = async (filter, page) => {
// filter = 에픽(204), 신화(207)
const response = await axios({
method: 'post',
url: 'http://df.nexon.com/FRM/info/equipment_search_api.php',
headers: {
'Accept': 'application/json, text/javascript, */*; q=0.01',
'X-Requested-With': 'XMLHttpRequest',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Referer': 'http://df.nexon.com/df/info/equipment/search?page=1&is_limit=&filter=207&max=100&min=100&level=Y&order_name=level&order_type=asc',
},
data: `mode=search&data[keyword]=&data[filter]=${filter}&data[level]=Y&data[min]=100&data[max]=100&data[setitem]=N&data[order_name]=level&data[order_type]=asc&page=${page}`,
});
return response.data.data.items;
};
(async () => {
const ex = /.운디네|.샐러맨더|.실프|포용의|맹렬히|휘감는|잔잔한|신록의 숨결|에너지 분배 제어기|전자기 진공관|제어 회로|무의식 : .|무형 : .|환영 : .|원초의 꿈.|진 :.|.결투장|퍼펙트 컨트롤|불타오르는 푸른 마력|암살자의 비수|마더 오브 네이쳐|거미 여왕의 목소리|풀 가드 네클레스|선지자의 목걸이|생멸 관장자의 팔찌|독을 머금은 가시장갑|할기의 링|올 엘리멘탈 크리스탈|웨슬리의 전술지휘봉|볼 오브 러데이니언|금지된 계약의 서|응축된 마력의 소용돌이|청면수라의 가면|얼어붙은 숨결의 결정|뒤틀린 이계의 마석|영광의 보석|적귀의 차원석|패스트퓨처 이어링|무념의 의식|무의식의 꽃|무형의 절개|무언의 죄악|무아의 고리/ig;
const filter_list = ['204', '207'];
for (const filter of filter_list) {
let page = 1;
while (true) {
const data = await GetItem(filter, page);
for (const item of data) {
try {
if (item.name.match(ex) == null) {
await connection.query('INSERT INTO `item_exception` SET ?', {
itemId: item.itemId,
name: item.name,
type: (filter === '204') ? 'epic' : 'myth',
});
}
} catch (e) {}
}
if (data.length === 0) {
break;
}
page++;
}
}
await connection.close();
})();
const axios = require('axios');
const crypto = require('crypto');
const mysql = require('mysql2');
const moment = require('moment');
const cron = require('node-cron');
const scheduler = require('node-schedule');
var now = new Date();
require('moment-timezone');
moment.tz.setDefault("Asia/Seoul");
const connection = mysql.createConnection({
host: 'localhost',
port: '3307',
user: 'root',
password: 'yj',
database: 'projectdf',
}).promise();
const GetItemDrop = async (itemId) => {
const response = await axios({
method: 'post',
url: `http://df.nexon.com/FRM/game/epic_drop.php?id=${itemId}`,
headers: {
'Accept': 'application/json, text/javascript, */*; q=0.01',
'X-Requested-With': 'XMLHttpRequest',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36',
'Referer': `http://df.nexon.com/df/info/equipment/view?id=${itemId}&page=3&is_limit=&filter=204&max=100&min=100&level=Y&order_name=level&order_type=asc`,
},
});
return response.data;
};
let job = scheduler.scheduleJob('*/15 * * * * *',function(){
var dateT = moment().format('YYYY-MM-DD HH:mm:ss');
console.log("Start "+dateT);
(async () => {
const [item_list] = await connection.query('SELECT * FROM `item_exception`');
for (const item of item_list) {
const data = await GetItemDrop(item.itemId);
for (const drop of data) {
const input = {
itemId: drop.item_no,
channel_name: drop.channel_name,
channel_number: drop.channel_number,
dungeon: drop.dungeon,
droped_at: moment.unix(drop.time).format('YYYY-MM-DD HH:mm:ss'),
};
input['hash'] = crypto.createHash('md5').update(JSON.stringify(input)).digest('hex');
try {
await connection.query('INSERT INTO `item_drop_exception` SET ?', input);
} catch (e) {}
}
}
var dateT2 = moment().format('YYYY-MM-DD HH:mm:ss');
console.log(dateT+" insert DB Done in" + dateT2);
})();
});
// await connection.close();-> 크론 작업을 돌리기 때문에 제외
// cron.schedule('*/15 * * * * *', function () {
// var dateT = moment().format('YYYY-MM-DD HH:mm:ss');
// console.log("Start "+dateT);
// const connection = mysql.createConnection({
// host: 'localhost',
// port: '3307',
// user: 'root',
// password: 'yj',
// database: 'projectdf',
// }).promise();
// const GetItemDrop = async (itemId) => {
// const response = await axios({
// method: 'post',
// url: `http://df.nexon.com/FRM/game/epic_drop.php?id=${itemId}`,
// headers: {
// 'Accept': 'application/json, text/javascript, */*; q=0.01',
// 'X-Requested-With': 'XMLHttpRequest',
// 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36',
// 'Referer': `http://df.nexon.com/df/info/equipment/view?id=${itemId}&page=3&is_limit=&filter=204&max=100&min=100&level=Y&order_name=level&order_type=asc`,
// },
// });
// return response.data;
// };
// (async () => {
// const [item_list] = await connection.query('SELECT * FROM `item_exception`');
// for (const item of item_list) {
// const data = await GetItemDrop(item.itemId);
// for (const drop of data) {
// const input = {
// itemId: drop.item_no,
// channel_name: drop.channel_name,
// channel_number: drop.channel_number,
// dungeon: drop.dungeon,
// droped_at: moment.unix(drop.time).format('YYYY-MM-DD HH:mm:ss'),
// };
// input['hash'] = crypto.createHash('md5').update(JSON.stringify(input)).digest('hex');
// try {
// await connection.query('INSERT INTO `item_drop_exception` SET ?', input);
// } catch (e) {}
// }
// }
// var dateT2 = moment().format('YYYY-MM-DD HH:mm:ss');
// console.log("insert DB Done " + dateT2);
// await connection.close();
// })();
// dateT = moment().format('YYYY-MM-DD HH:mm:ss');
// console.log("done "+dateT);
// });
{
"name": "df",
"version": "1.0.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"ansicolors": {
"version": "0.3.2",
"resolved": "https://registry.npmjs.org/ansicolors/-/ansicolors-0.3.2.tgz",
"integrity": "sha1-ZlWX3oap/+Oqm/vmyuXG6kJrSXk="
},
"axios": {
"version": "0.19.2",
"resolved": "https://registry.npmjs.org/axios/-/axios-0.19.2.tgz",
"integrity": "sha512-fjgm5MvRHLhx+osE2xoekY70AhARk3a6hkN+3Io1jc00jtquGvxYlKlsFUhmUET0V5te6CcZI7lcv2Ym61mjHA==",
"requires": {
"follow-redirects": "1.5.10"
}
},
"cardinal": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/cardinal/-/cardinal-2.1.1.tgz",
"integrity": "sha1-fMEFXYItISlU0HsIXeolHMe8VQU=",
"requires": {
"ansicolors": "~0.3.2",
"redeyed": "~2.1.0"
}
},
"debug": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz",
"integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==",
"requires": {
"ms": "2.0.0"
}
},
"denque": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/denque/-/denque-1.4.1.tgz",
"integrity": "sha512-OfzPuSZKGcgr96rf1oODnfjqBFmr1DVoc/TrItj3Ohe0Ah1C5WX5Baquw/9U9KovnQ88EqmJbD66rKYUQYN1tQ=="
},
"esprima": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz",
"integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A=="
},
"follow-redirects": {
"version": "1.5.10",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.5.10.tgz",
"integrity": "sha512-0V5l4Cizzvqt5D44aTXbFZz+FtyXV1vrDN6qrelxtfYQKW0KO0W2T/hkE8xvGa/540LkZlkaUjO4ailYTFtHVQ==",
"requires": {
"debug": "=3.1.0"
}
},
"generate-function": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz",
"integrity": "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==",
"requires": {
"is-property": "^1.0.2"
}
},
"iconv-lite": {
"version": "0.5.1",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.5.1.tgz",
"integrity": "sha512-ONHr16SQvKZNSqjQT9gy5z24Jw+uqfO02/ngBSBoqChZ+W8qXX7GPRa1RoUnzGADw8K63R1BXUMzarCVQBpY8Q==",
"requires": {
"safer-buffer": ">= 2.1.2 < 3"
}
},
"is-property": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz",
"integrity": "sha1-V/4cTkhHTt1lsJkR8msc1Ald2oQ="
},
"long": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/long/-/long-4.0.0.tgz",
"integrity": "sha512-XsP+KhQif4bjX1kbuSiySJFNAehNxgLb6hPRGJ9QsUr8ajHkuXGdrHmFUTUUXhDwVX2R5bY4JNZEwbUiMhV+MA=="
},
"lru-cache": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
"integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==",
"requires": {
"yallist": "^3.0.2"
}
},
"moment": {
"version": "2.25.3",
"resolved": "https://registry.npmjs.org/moment/-/moment-2.25.3.tgz",
"integrity": "sha512-PuYv0PHxZvzc15Sp8ybUCoQ+xpyPWvjOuK72a5ovzp2LI32rJXOiIfyoFoYvG3s6EwwrdkMyWuRiEHSZRLJNdg=="
},
"moment-timezone": {
"version": "0.5.31",
"resolved": "https://registry.npmjs.org/moment-timezone/-/moment-timezone-0.5.31.tgz",
"integrity": "sha512-+GgHNg8xRhMXfEbv81iDtrVeTcWt0kWmTEY1XQK14dICTXnWJnT0dxdlPspwqF3keKMVPXwayEsk1DI0AA/jdA==",
"requires": {
"moment": ">= 2.9.0"
}
},
"ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g="
},
"mysql2": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/mysql2/-/mysql2-2.1.0.tgz",
"integrity": "sha512-9kGVyi930rG2KaHrz3sHwtc6K+GY9d8wWk1XRSYxQiunvGcn4DwuZxOwmK11ftuhhwrYDwGx9Ta4VBwznJn36A==",
"requires": {
"cardinal": "^2.1.1",
"denque": "^1.4.1",
"generate-function": "^2.3.1",
"iconv-lite": "^0.5.0",
"long": "^4.0.0",
"lru-cache": "^5.1.1",
"named-placeholders": "^1.1.2",
"seq-queue": "^0.0.5",
"sqlstring": "^2.3.1"
}
},
"named-placeholders": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/named-placeholders/-/named-placeholders-1.1.2.tgz",
"integrity": "sha512-wiFWqxoLL3PGVReSZpjLVxyJ1bRqe+KKJVbr4hGs1KWfTZTQyezHFBbuKj9hsizHyGV2ne7EMjHdxEGAybD5SA==",
"requires": {
"lru-cache": "^4.1.3"
},
"dependencies": {
"lru-cache": {
"version": "4.1.5",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-4.1.5.tgz",
"integrity": "sha512-sWZlbEP2OsHNkXrMl5GYk/jKk70MBng6UU4YI/qGDYbgf6YbP4EvmqISbXCoJiRKs+1bSpFHVgQxvJ17F2li5g==",
"requires": {
"pseudomap": "^1.0.2",
"yallist": "^2.1.2"
}
},
"yallist": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-2.1.2.tgz",
"integrity": "sha1-HBH5IY8HYImkfdUS+TxmmaaoHVI="
}
}
},
"node-cron": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/node-cron/-/node-cron-2.0.3.tgz",
"integrity": "sha512-eJI+QitXlwcgiZwNNSRbqsjeZMp5shyajMR81RZCqeW0ZDEj4zU9tpd4nTh/1JsBiKbF8d08FCewiipDmVIYjg==",
"requires": {
"opencollective-postinstall": "^2.0.0",
"tz-offset": "0.0.1"
}
},
"opencollective-postinstall": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/opencollective-postinstall/-/opencollective-postinstall-2.0.2.tgz",
"integrity": "sha512-pVOEP16TrAO2/fjej1IdOyupJY8KDUM1CvsaScRbw6oddvpQoOfGk4ywha0HKKVAD6RkW4x6Q+tNBwhf3Bgpuw=="
},
"pseudomap": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/pseudomap/-/pseudomap-1.0.2.tgz",
"integrity": "sha1-8FKijacOYYkX7wqKw0wa5aaChrM="
},
"redeyed": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/redeyed/-/redeyed-2.1.1.tgz",
"integrity": "sha1-iYS1gV2ZyyIEacme7v/jiRPmzAs=",
"requires": {
"esprima": "~4.0.0"
}
},
"safer-buffer": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="
},
"seq-queue": {
"version": "0.0.5",
"resolved": "https://registry.npmjs.org/seq-queue/-/seq-queue-0.0.5.tgz",
"integrity": "sha1-1WgS4cAXpuTnw+Ojeh2m143TyT4="
},
"sqlstring": {
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/sqlstring/-/sqlstring-2.3.2.tgz",
"integrity": "sha512-vF4ZbYdKS8OnoJAWBmMxCQDkiEBkGQYU7UZPtL8flbDRSNkhaXvRJ279ZtI6M+zDaQovVU4tuRgzK5fVhvFAhg=="
},
"tz-offset": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/tz-offset/-/tz-offset-0.0.1.tgz",
"integrity": "sha512-kMBmblijHJXyOpKzgDhKx9INYU4u4E1RPMB0HqmKSgWG8vEcf3exEfLh4FFfzd3xdQOw9EuIy/cP0akY6rHopQ=="
},
"yallist": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",
"integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="
}
}
}
{
"name": "df",
"version": "1.0.0",
"description": "",
"main": "crawl.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"axios": "^0.19.2",
"moment": "^2.25.3",
"moment-timezone": "^0.5.31",
"mysql2": "^2.1.0",
"node-cron": "^2.0.3"
}
}
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `yarn start`
Runs the app in the development mode.<br />
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.<br />
You will also see any lint errors in the console.
### `yarn test`
Launches the test runner in the interactive watch mode.<br />
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `yarn build`
Builds the app for production to the `build` folder.<br />
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.<br />
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `yarn eject`
**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
### Code Splitting
This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting
### Analyzing the Bundle Size
This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size
### Making a Progressive Web App
This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app
### Advanced Configuration
This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration
### Deployment
This section has moved here: https://facebook.github.io/create-react-app/docs/deployment
### `yarn build` fails to minify
This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify
'use strict';
const fs = require('fs');
const path = require('path');
const paths = require('./paths');
// Make sure that including paths.js after env.js will read .env variables.
delete require.cache[require.resolve('./paths')];
const NODE_ENV = process.env.NODE_ENV;
if (!NODE_ENV) {
throw new Error(
'The NODE_ENV environment variable is required but was not specified.'
);
}
// https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use
const dotenvFiles = [
`${paths.dotenv}.${NODE_ENV}.local`,
`${paths.dotenv}.${NODE_ENV}`,
// Don't include `.env.local` for `test` environment
// since normally you expect tests to produce the same
// results for everyone
NODE_ENV !== 'test' && `${paths.dotenv}.local`,
paths.dotenv,
].filter(Boolean);
// Load environment variables from .env* files. Suppress warnings using silent
// if this file is missing. dotenv will never modify any environment variables
// that have already been set. Variable expansion is supported in .env files.
// https://github.com/motdotla/dotenv
// https://github.com/motdotla/dotenv-expand
dotenvFiles.forEach(dotenvFile => {
if (fs.existsSync(dotenvFile)) {
require('dotenv-expand')(
require('dotenv').config({
path: dotenvFile,
})
);
}
});
// We support resolving modules according to `NODE_PATH`.
// This lets you use absolute paths in imports inside large monorepos:
// https://github.com/facebook/create-react-app/issues/253.
// It works similar to `NODE_PATH` in Node itself:
// https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders
// Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored.
// Otherwise, we risk importing Node.js core modules into an app instead of webpack shims.
// https://github.com/facebook/create-react-app/issues/1023#issuecomment-265344421
// We also resolve them to make sure all tools using them work consistently.
const appDirectory = fs.realpathSync(process.cwd());
process.env.NODE_PATH = (process.env.NODE_PATH || '')
.split(path.delimiter)
.filter(folder => folder && !path.isAbsolute(folder))
.map(folder => path.resolve(appDirectory, folder))
.join(path.delimiter);
// Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be
// injected into the application via DefinePlugin in webpack configuration.
const REACT_APP = /^REACT_APP_/i;
function getClientEnvironment(publicUrl) {
const raw = Object.keys(process.env)
.filter(key => REACT_APP.test(key))
.reduce(
(env, key) => {
env[key] = process.env[key];
return env;
},
{
// Useful for determining whether we’re running in production mode.
// Most importantly, it switches React into the correct mode.
NODE_ENV: process.env.NODE_ENV || 'development',
// Useful for resolving the correct path to static assets in `public`.
// For example, <img src={process.env.PUBLIC_URL + '/img/logo.png'} />.
// This should only be used as an escape hatch. Normally you would put
// images into the `src` and `import` them in code to get their paths.
PUBLIC_URL: publicUrl,
// We support configuring the sockjs pathname during development.
// These settings let a developer run multiple simultaneous projects.
// They are used as the connection `hostname`, `pathname` and `port`
// in webpackHotDevClient. They are used as the `sockHost`, `sockPath`
// and `sockPort` options in webpack-dev-server.
WDS_SOCKET_HOST: process.env.WDS_SOCKET_HOST,
WDS_SOCKET_PATH: process.env.WDS_SOCKET_PATH,
WDS_SOCKET_PORT: process.env.WDS_SOCKET_PORT,
}
);
// Stringify all values so we can feed into webpack DefinePlugin
const stringified = {
'process.env': Object.keys(raw).reduce((env, key) => {
env[key] = JSON.stringify(raw[key]);
return env;
}, {}),
};
return { raw, stringified };
}
module.exports = getClientEnvironment;
'use strict';
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const chalk = require('react-dev-utils/chalk');
const paths = require('./paths');
// Ensure the certificate and key provided are valid and if not
// throw an easy to debug error
function validateKeyAndCerts({ cert, key, keyFile, crtFile }) {
let encrypted;
try {
// publicEncrypt will throw an error with an invalid cert
encrypted = crypto.publicEncrypt(cert, Buffer.from('test'));
} catch (err) {
throw new Error(
`The certificate "${chalk.yellow(crtFile)}" is invalid.\n${err.message}`
);
}
try {
// privateDecrypt will throw an error with an invalid key
crypto.privateDecrypt(key, encrypted);
} catch (err) {
throw new Error(
`The certificate key "${chalk.yellow(keyFile)}" is invalid.\n${
err.message
}`
);
}
}
// Read file and throw an error if it doesn't exist
function readEnvFile(file, type) {
if (!fs.existsSync(file)) {
throw new Error(
`You specified ${chalk.cyan(
type
)} in your env, but the file "${chalk.yellow(file)}" can't be found.`
);
}
return fs.readFileSync(file);
}
// Get the https config
// Return cert files if provided in env, otherwise just true or false
function getHttpsConfig() {
const { SSL_CRT_FILE, SSL_KEY_FILE, HTTPS } = process.env;
const isHttps = HTTPS === 'true';
if (isHttps && SSL_CRT_FILE && SSL_KEY_FILE) {
const crtFile = path.resolve(paths.appPath, SSL_CRT_FILE);
const keyFile = path.resolve(paths.appPath, SSL_KEY_FILE);
const config = {
cert: readEnvFile(crtFile, 'SSL_CRT_FILE'),
key: readEnvFile(keyFile, 'SSL_KEY_FILE'),
};
validateKeyAndCerts({ ...config, keyFile, crtFile });
return config;
}
return isHttps;
}
module.exports = getHttpsConfig;
'use strict';
// This is a custom Jest transformer turning style imports into empty objects.
// http://facebook.github.io/jest/docs/en/webpack.html
module.exports = {
process() {
return 'module.exports = {};';
},
getCacheKey() {
// The output is always the same.
return 'cssTransform';
},
};
'use strict';
const path = require('path');
const camelcase = require('camelcase');
// This is a custom Jest transformer turning file imports into filenames.
// http://facebook.github.io/jest/docs/en/webpack.html
module.exports = {
process(src, filename) {
const assetFilename = JSON.stringify(path.basename(filename));
if (filename.match(/\.svg$/)) {
// Based on how SVGR generates a component name:
// https://github.com/smooth-code/svgr/blob/01b194cf967347d43d4cbe6b434404731b87cf27/packages/core/src/state.js#L6
const pascalCaseFilename = camelcase(path.parse(filename).name, {
pascalCase: true,
});
const componentName = `Svg${pascalCaseFilename}`;
return `const React = require('react');
module.exports = {
__esModule: true,
default: ${assetFilename},
ReactComponent: React.forwardRef(function ${componentName}(props, ref) {
return {
$$typeof: Symbol.for('react.element'),
type: 'svg',
ref: ref,
key: null,
props: Object.assign({}, props, {
children: ${assetFilename}
})
};
}),
};`;
}
return `module.exports = ${assetFilename};`;
},
};
'use strict';
const fs = require('fs');
const path = require('path');
const paths = require('./paths');
const chalk = require('react-dev-utils/chalk');
const resolve = require('resolve');
/**
* Get additional module paths based on the baseUrl of a compilerOptions object.
*
* @param {Object} options
*/
function getAdditionalModulePaths(options = {}) {
const baseUrl = options.baseUrl;
// We need to explicitly check for null and undefined (and not a falsy value) because
// TypeScript treats an empty string as `.`.
if (baseUrl == null) {
// If there's no baseUrl set we respect NODE_PATH
// Note that NODE_PATH is deprecated and will be removed
// in the next major release of create-react-app.
const nodePath = process.env.NODE_PATH || '';
return nodePath.split(path.delimiter).filter(Boolean);
}
const baseUrlResolved = path.resolve(paths.appPath, baseUrl);
// We don't need to do anything if `baseUrl` is set to `node_modules`. This is
// the default behavior.
if (path.relative(paths.appNodeModules, baseUrlResolved) === '') {
return null;
}
// Allow the user set the `baseUrl` to `appSrc`.
if (path.relative(paths.appSrc, baseUrlResolved) === '') {
return [paths.appSrc];
}
// If the path is equal to the root directory we ignore it here.
// We don't want to allow importing from the root directly as source files are
// not transpiled outside of `src`. We do allow importing them with the
// absolute path (e.g. `src/Components/Button.js`) but we set that up with
// an alias.
if (path.relative(paths.appPath, baseUrlResolved) === '') {
return null;
}
// Otherwise, throw an error.
throw new Error(
chalk.red.bold(
"Your project's `baseUrl` can only be set to `src` or `node_modules`." +
' Create React App does not support other values at this time.'
)
);
}
/**
* Get webpack aliases based on the baseUrl of a compilerOptions object.
*
* @param {*} options
*/
function getWebpackAliases(options = {}) {
const baseUrl = options.baseUrl;
if (!baseUrl) {
return {};
}
const baseUrlResolved = path.resolve(paths.appPath, baseUrl);
if (path.relative(paths.appPath, baseUrlResolved) === '') {
return {
src: paths.appSrc,
};
}
}
/**
* Get jest aliases based on the baseUrl of a compilerOptions object.
*
* @param {*} options
*/
function getJestAliases(options = {}) {
const baseUrl = options.baseUrl;
if (!baseUrl) {
return {};
}
const baseUrlResolved = path.resolve(paths.appPath, baseUrl);
if (path.relative(paths.appPath, baseUrlResolved) === '') {
return {
'^src/(.*)$': '<rootDir>/src/$1',
};
}
}
function getModules() {
// Check if TypeScript is setup
const hasTsConfig = fs.existsSync(paths.appTsConfig);
const hasJsConfig = fs.existsSync(paths.appJsConfig);
if (hasTsConfig && hasJsConfig) {
throw new Error(
'You have both a tsconfig.json and a jsconfig.json. If you are using TypeScript please remove your jsconfig.json file.'
);
}
let config;
// If there's a tsconfig.json we assume it's a
// TypeScript project and set up the config
// based on tsconfig.json
if (hasTsConfig) {
const ts = require(resolve.sync('typescript', {
basedir: paths.appNodeModules,
}));
config = ts.readConfigFile(paths.appTsConfig, ts.sys.readFile).config;
// Otherwise we'll check if there is jsconfig.json
// for non TS projects.
} else if (hasJsConfig) {
config = require(paths.appJsConfig);
}
config = config || {};
const options = config.compilerOptions || {};
const additionalModulePaths = getAdditionalModulePaths(options);
return {
additionalModulePaths: additionalModulePaths,
webpackAliases: getWebpackAliases(options),
jestAliases: getJestAliases(options),
hasTsConfig,
};
}
module.exports = getModules();
'use strict';
const path = require('path');
const fs = require('fs');
const getPublicUrlOrPath = require('react-dev-utils/getPublicUrlOrPath');
// Make sure any symlinks in the project folder are resolved:
// https://github.com/facebook/create-react-app/issues/637
const appDirectory = fs.realpathSync(process.cwd());
const resolveApp = relativePath => path.resolve(appDirectory, relativePath);
// We use `PUBLIC_URL` environment variable or "homepage" field to infer
// "public path" at which the app is served.
// webpack needs to know it to put the right <script> hrefs into HTML even in
// single-page apps that may serve index.html for nested URLs like /todos/42.
// We can't use a relative path in HTML because we don't want to load something
// like /todos/42/static/js/bundle.7289d.js. We have to know the root.
const publicUrlOrPath = getPublicUrlOrPath(
process.env.NODE_ENV === 'development',
require(resolveApp('package.json')).homepage,
process.env.PUBLIC_URL
);
const moduleFileExtensions = [
'web.mjs',
'mjs',
'web.js',
'js',
'web.ts',
'ts',
'web.tsx',
'tsx',
'json',
'web.jsx',
'jsx',
];
// Resolve file paths in the same order as webpack
const resolveModule = (resolveFn, filePath) => {
const extension = moduleFileExtensions.find(extension =>
fs.existsSync(resolveFn(`${filePath}.${extension}`))
);
if (extension) {
return resolveFn(`${filePath}.${extension}`);
}
return resolveFn(`${filePath}.js`);
};
// config after eject: we're in ./config/
module.exports = {
dotenv: resolveApp('.env'),
appPath: resolveApp('.'),
appBuild: resolveApp('build'),
appPublic: resolveApp('public'),
appHtml: resolveApp('public/index.html'),
appIndexJs: resolveModule(resolveApp, 'src/index'),
appPackageJson: resolveApp('package.json'),
appSrc: resolveApp('src'),
appTsConfig: resolveApp('tsconfig.json'),
appJsConfig: resolveApp('jsconfig.json'),
yarnLockFile: resolveApp('yarn.lock'),
testsSetup: resolveModule(resolveApp, 'src/setupTests'),
proxySetup: resolveApp('src/setupProxy.js'),
appNodeModules: resolveApp('node_modules'),
publicUrlOrPath,
};
module.exports.moduleFileExtensions = moduleFileExtensions;
'use strict';
const { resolveModuleName } = require('ts-pnp');
exports.resolveModuleName = (
typescript,
moduleName,
containingFile,
compilerOptions,
resolutionHost
) => {
return resolveModuleName(
moduleName,
containingFile,
compilerOptions,
resolutionHost,
typescript.resolveModuleName
);
};
exports.resolveTypeReferenceDirective = (
typescript,
moduleName,
containingFile,
compilerOptions,
resolutionHost
) => {
return resolveModuleName(
moduleName,
containingFile,
compilerOptions,
resolutionHost,
typescript.resolveTypeReferenceDirective
);
};
'use strict';
const fs = require('fs');
const path = require('path');
const webpack = require('webpack');
const resolve = require('resolve');
const PnpWebpackPlugin = require('pnp-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
const InlineChunkHtmlPlugin = require('react-dev-utils/InlineChunkHtmlPlugin');
const TerserPlugin = require('terser-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const safePostCssParser = require('postcss-safe-parser');
const ManifestPlugin = require('webpack-manifest-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const WorkboxWebpackPlugin = require('workbox-webpack-plugin');
const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const getCSSModuleLocalIdent = require('react-dev-utils/getCSSModuleLocalIdent');
const paths = require('./paths');
const modules = require('./modules');
const getClientEnvironment = require('./env');
const ModuleNotFoundPlugin = require('react-dev-utils/ModuleNotFoundPlugin');
const ForkTsCheckerWebpackPlugin = require('react-dev-utils/ForkTsCheckerWebpackPlugin');
const typescriptFormatter = require('react-dev-utils/typescriptFormatter');
const postcssNormalize = require('postcss-normalize');
const appPackageJson = require(paths.appPackageJson);
// Source maps are resource heavy and can cause out of memory issue for large source files.
const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
// Some apps do not need the benefits of saving a web request, so not inlining the chunk
// makes for a smoother build process.
const shouldInlineRuntimeChunk = process.env.INLINE_RUNTIME_CHUNK !== 'false';
const isExtendingEslintConfig = process.env.EXTEND_ESLINT === 'true';
const imageInlineSizeLimit = parseInt(
process.env.IMAGE_INLINE_SIZE_LIMIT || '10000'
);
// Check if TypeScript is setup
const useTypeScript = fs.existsSync(paths.appTsConfig);
// style files regexes
const cssRegex = /\.css$/;
const cssModuleRegex = /\.module\.css$/;
const sassRegex = /\.(scss|sass)$/;
const sassModuleRegex = /\.module\.(scss|sass)$/;
// This is the production and development configuration.
// It is focused on developer experience, fast rebuilds, and a minimal bundle.
module.exports = function(webpackEnv) {
const isEnvDevelopment = webpackEnv === 'development';
const isEnvProduction = webpackEnv === 'production';
// Variable used for enabling profiling in Production
// passed into alias object. Uses a flag if passed into the build command
const isEnvProductionProfile =
isEnvProduction && process.argv.includes('--profile');
// We will provide `paths.publicUrlOrPath` to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
// Get environment variables to inject into our app.
const env = getClientEnvironment(paths.publicUrlOrPath.slice(0, -1));
// common function to get style loaders
const getStyleLoaders = (cssOptions, preProcessor) => {
const loaders = [
isEnvDevelopment && require.resolve('style-loader'),
isEnvProduction && {
loader: MiniCssExtractPlugin.loader,
// css is located in `static/css`, use '../../' to locate index.html folder
// in production `paths.publicUrlOrPath` can be a relative path
options: paths.publicUrlOrPath.startsWith('.')
? { publicPath: '../../' }
: {},
},
{
loader: require.resolve('css-loader'),
options: cssOptions,
},
{
// Options for PostCSS as we reference these options twice
// Adds vendor prefixing based on your specified browser support in
// package.json
loader: require.resolve('postcss-loader'),
options: {
// Necessary for external CSS imports to work
// https://github.com/facebook/create-react-app/issues/2677
ident: 'postcss',
plugins: () => [
require('postcss-flexbugs-fixes'),
require('postcss-preset-env')({
autoprefixer: {
flexbox: 'no-2009',
},
stage: 3,
}),
// Adds PostCSS Normalize as the reset css with default options,
// so that it honors browserslist config in package.json
// which in turn let's users customize the target behavior as per their needs.
postcssNormalize(),
],
sourceMap: isEnvProduction && shouldUseSourceMap,
},
},
].filter(Boolean);
if (preProcessor) {
loaders.push(
{
loader: require.resolve('resolve-url-loader'),
options: {
sourceMap: isEnvProduction && shouldUseSourceMap,
},
},
{
loader: require.resolve(preProcessor),
options: {
sourceMap: true,
},
}
);
}
return loaders;
};
return {
mode: isEnvProduction ? 'production' : isEnvDevelopment && 'development',
// Stop compilation early in production
bail: isEnvProduction,
devtool: isEnvProduction
? shouldUseSourceMap
? 'source-map'
: false
: isEnvDevelopment && 'cheap-module-source-map',
// These are the "entry points" to our application.
// This means they will be the "root" imports that are included in JS bundle.
entry: [
// Include an alternative client for WebpackDevServer. A client's job is to
// connect to WebpackDevServer by a socket and get notified about changes.
// When you save a file, the client will either apply hot updates (in case
// of CSS changes), or refresh the page (in case of JS changes). When you
// make a syntax error, this client will display a syntax error overlay.
// Note: instead of the default WebpackDevServer client, we use a custom one
// to bring better experience for Create React App users. You can replace
// the line below with these two lines if you prefer the stock client:
// require.resolve('webpack-dev-server/client') + '?/',
// require.resolve('webpack/hot/dev-server'),
isEnvDevelopment &&
require.resolve('react-dev-utils/webpackHotDevClient'),
// Finally, this is your app's code:
paths.appIndexJs,
// We include the app code last so that if there is a runtime error during
// initialization, it doesn't blow up the WebpackDevServer client, and
// changing JS code would still trigger a refresh.
].filter(Boolean),
output: {
// The build folder.
path: isEnvProduction ? paths.appBuild : undefined,
// Add /* filename */ comments to generated require()s in the output.
pathinfo: isEnvDevelopment,
// There will be one main bundle, and one file per asynchronous chunk.
// In development, it does not produce real files.
filename: isEnvProduction
? 'static/js/[name].[contenthash:8].js'
: isEnvDevelopment && 'static/js/bundle.js',
// TODO: remove this when upgrading to webpack 5
futureEmitAssets: true,
// There are also additional JS chunk files if you use code splitting.
chunkFilename: isEnvProduction
? 'static/js/[name].[contenthash:8].chunk.js'
: isEnvDevelopment && 'static/js/[name].chunk.js',
// webpack uses `publicPath` to determine where the app is being served from.
// It requires a trailing slash, or the file assets will get an incorrect path.
// We inferred the "public path" (such as / or /my-project) from homepage.
publicPath: paths.publicUrlOrPath,
// Point sourcemap entries to original disk location (format as URL on Windows)
devtoolModuleFilenameTemplate: isEnvProduction
? info =>
path
.relative(paths.appSrc, info.absoluteResourcePath)
.replace(/\\/g, '/')
: isEnvDevelopment &&
(info => path.resolve(info.absoluteResourcePath).replace(/\\/g, '/')),
// Prevents conflicts when multiple webpack runtimes (from different apps)
// are used on the same page.
jsonpFunction: `webpackJsonp${appPackageJson.name}`,
// this defaults to 'window', but by setting it to 'this' then
// module chunks which are built will work in web workers as well.
globalObject: 'this',
},
optimization: {
minimize: isEnvProduction,
minimizer: [
// This is only used in production mode
new TerserPlugin({
terserOptions: {
parse: {
// We want terser to parse ecma 8 code. However, we don't want it
// to apply any minification steps that turns valid ecma 5 code
// into invalid ecma 5 code. This is why the 'compress' and 'output'
// sections only apply transformations that are ecma 5 safe
// https://github.com/facebook/create-react-app/pull/4234
ecma: 8,
},
compress: {
ecma: 5,
warnings: false,
// Disabled because of an issue with Uglify breaking seemingly valid code:
// https://github.com/facebook/create-react-app/issues/2376
// Pending further investigation:
// https://github.com/mishoo/UglifyJS2/issues/2011
comparisons: false,
// Disabled because of an issue with Terser breaking valid code:
// https://github.com/facebook/create-react-app/issues/5250
// Pending further investigation:
// https://github.com/terser-js/terser/issues/120
inline: 2,
},
mangle: {
safari10: true,
},
// Added for profiling in devtools
keep_classnames: isEnvProductionProfile,
keep_fnames: isEnvProductionProfile,
output: {
ecma: 5,
comments: false,
// Turned on because emoji and regex is not minified properly using default
// https://github.com/facebook/create-react-app/issues/2488
ascii_only: true,
},
},
sourceMap: shouldUseSourceMap,
}),
// This is only used in production mode
new OptimizeCSSAssetsPlugin({
cssProcessorOptions: {
parser: safePostCssParser,
map: shouldUseSourceMap
? {
// `inline: false` forces the sourcemap to be output into a
// separate file
inline: false,
// `annotation: true` appends the sourceMappingURL to the end of
// the css file, helping the browser find the sourcemap
annotation: true,
}
: false,
},
cssProcessorPluginOptions: {
preset: ['default', { minifyFontValues: { removeQuotes: false } }],
},
}),
],
// Automatically split vendor and commons
// https://twitter.com/wSokra/status/969633336732905474
// https://medium.com/webpack/webpack-4-code-splitting-chunk-graph-and-the-splitchunks-optimization-be739a861366
splitChunks: {
chunks: 'all',
name: false,
},
// Keep the runtime chunk separated to enable long term caching
// https://twitter.com/wSokra/status/969679223278505985
// https://github.com/facebook/create-react-app/issues/5358
runtimeChunk: {
name: entrypoint => `runtime-${entrypoint.name}`,
},
},
resolve: {
// This allows you to set a fallback for where webpack should look for modules.
// We placed these paths second because we want `node_modules` to "win"
// if there are any conflicts. This matches Node resolution mechanism.
// https://github.com/facebook/create-react-app/issues/253
modules: ['node_modules', paths.appNodeModules].concat(
modules.additionalModulePaths || []
),
// These are the reasonable defaults supported by the Node ecosystem.
// We also include JSX as a common component filename extension to support
// some tools, although we do not recommend using it, see:
// https://github.com/facebook/create-react-app/issues/290
// `web` extension prefixes have been added for better support
// for React Native Web.
extensions: paths.moduleFileExtensions
.map(ext => `.${ext}`)
.filter(ext => useTypeScript || !ext.includes('ts')),
alias: {
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-native': 'react-native-web',
// Allows for better profiling with ReactDevTools
...(isEnvProductionProfile && {
'react-dom$': 'react-dom/profiling',
'scheduler/tracing': 'scheduler/tracing-profiling',
}),
...(modules.webpackAliases || {}),
},
plugins: [
// Adds support for installing with Plug'n'Play, leading to faster installs and adding
// guards against forgotten dependencies and such.
PnpWebpackPlugin,
// Prevents users from importing files from outside of src/ (or node_modules/).
// This often causes confusion because we only process files within src/ with babel.
// To fix this, we prevent you from importing files out of src/ -- if you'd like to,
// please link the files into your node_modules/ and let module-resolution kick in.
// Make sure your source files are compiled, as they will not be processed in any way.
new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
],
},
resolveLoader: {
plugins: [
// Also related to Plug'n'Play, but this time it tells webpack to load its loaders
// from the current package.
PnpWebpackPlugin.moduleLoader(module),
],
},
module: {
strictExportPresence: true,
rules: [
// Disable require.ensure as it's not a standard language feature.
{ parser: { requireEnsure: false } },
// First, run the linter.
// It's important to do this before Babel processes the JS.
{
test: /\.(js|mjs|jsx|ts|tsx)$/,
enforce: 'pre',
use: [
{
options: {
cache: true,
formatter: require.resolve('react-dev-utils/eslintFormatter'),
eslintPath: require.resolve('eslint'),
resolvePluginsRelativeTo: __dirname,
},
loader: require.resolve('eslint-loader'),
},
],
include: paths.appSrc,
},
{
// "oneOf" will traverse all following loaders until one will
// match the requirements. When no loader matches it will fall
// back to the "file" loader at the end of the loader list.
oneOf: [
// "url" loader works like "file" loader except that it embeds assets
// smaller than specified limit in bytes as data URLs to avoid requests.
// A missing `test` is equivalent to a match.
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: require.resolve('url-loader'),
options: {
limit: imageInlineSizeLimit,
name: 'static/media/[name].[hash:8].[ext]',
},
},
// Process application JS with Babel.
// The preset includes JSX, Flow, TypeScript, and some ESnext features.
{
test: /\.(js|mjs|jsx|ts|tsx)$/,
include: paths.appSrc,
loader: require.resolve('babel-loader'),
options: {
customize: require.resolve(
'babel-preset-react-app/webpack-overrides'
),
plugins: [
[
require.resolve('babel-plugin-named-asset-import'),
{
loaderMap: {
svg: {
ReactComponent:
'@svgr/webpack?-svgo,+titleProp,+ref![path]',
},
},
},
],
],
// This is a feature of `babel-loader` for webpack (not Babel itself).
// It enables caching results in ./node_modules/.cache/babel-loader/
// directory for faster rebuilds.
cacheDirectory: true,
// See #6846 for context on why cacheCompression is disabled
cacheCompression: false,
compact: isEnvProduction,
},
},
// Process any JS outside of the app with Babel.
// Unlike the application JS, we only compile the standard ES features.
{
test: /\.(js|mjs)$/,
exclude: /@babel(?:\/|\\{1,2})runtime/,
loader: require.resolve('babel-loader'),
options: {
babelrc: false,
configFile: false,
compact: false,
presets: [
[
require.resolve('babel-preset-react-app/dependencies'),
{ helpers: true },
],
],
cacheDirectory: true,
// See #6846 for context on why cacheCompression is disabled
cacheCompression: false,
// Babel sourcemaps are needed for debugging into node_modules
// code. Without the options below, debuggers like VSCode
// show incorrect code and set breakpoints on the wrong lines.
sourceMaps: shouldUseSourceMap,
inputSourceMap: shouldUseSourceMap,
},
},
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader turns CSS into JS modules that inject <style> tags.
// In production, we use MiniCSSExtractPlugin to extract that CSS
// to a file, but in development "style" loader enables hot editing
// of CSS.
// By default we support CSS Modules with the extension .module.css
{
test: cssRegex,
exclude: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction && shouldUseSourceMap,
}),
// Don't consider CSS imports dead code even if the
// containing package claims to have no side effects.
// Remove this when webpack adds a warning or an error for this.
// See https://github.com/webpack/webpack/issues/6571
sideEffects: true,
},
// Adds support for CSS Modules (https://github.com/css-modules/css-modules)
// using the extension .module.css
{
test: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction && shouldUseSourceMap,
modules: {
getLocalIdent: getCSSModuleLocalIdent,
},
}),
},
// Opt-in support for SASS (using .scss or .sass extensions).
// By default we support SASS Modules with the
// extensions .module.scss or .module.sass
{
test: sassRegex,
exclude: sassModuleRegex,
use: getStyleLoaders(
{
importLoaders: 3,
sourceMap: isEnvProduction && shouldUseSourceMap,
},
'sass-loader'
),
// Don't consider CSS imports dead code even if the
// containing package claims to have no side effects.
// Remove this when webpack adds a warning or an error for this.
// See https://github.com/webpack/webpack/issues/6571
sideEffects: true,
},
// Adds support for CSS Modules, but using SASS
// using the extension .module.scss or .module.sass
{
test: sassModuleRegex,
use: getStyleLoaders(
{
importLoaders: 3,
sourceMap: isEnvProduction && shouldUseSourceMap,
modules: {
getLocalIdent: getCSSModuleLocalIdent,
},
},
'sass-loader'
),
},
// "file" loader makes sure those assets get served by WebpackDevServer.
// When you `import` an asset, you get its (virtual) filename.
// In production, they would get copied to the `build` folder.
// This loader doesn't use a "test" so it will catch all modules
// that fall through the other loaders.
{
loader: require.resolve('file-loader'),
// Exclude `js` files to keep "css" loader working as it injects
// its runtime that would otherwise be processed through "file" loader.
// Also exclude `html` and `json` extensions so they get processed
// by webpacks internal loaders.
exclude: [/\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/],
options: {
name: 'static/media/[name].[hash:8].[ext]',
},
},
// ** STOP ** Are you adding a new loader?
// Make sure to add the new loader(s) before the "file" loader.
],
},
],
},
plugins: [
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin(
Object.assign(
{},
{
inject: true,
template: paths.appHtml,
},
isEnvProduction
? {
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
},
}
: undefined
)
),
// Inlines the webpack runtime script. This script is too small to warrant
// a network request.
// https://github.com/facebook/create-react-app/issues/5358
isEnvProduction &&
shouldInlineRuntimeChunk &&
new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [/runtime-.+[.]js/]),
// Makes some environment variables available in index.html.
// The public URL is available as %PUBLIC_URL% in index.html, e.g.:
// <link rel="icon" href="%PUBLIC_URL%/favicon.ico">
// It will be an empty string unless you specify "homepage"
// in `package.json`, in which case it will be the pathname of that URL.
new InterpolateHtmlPlugin(HtmlWebpackPlugin, env.raw),
// This gives some necessary context to module not found errors, such as
// the requesting resource.
new ModuleNotFoundPlugin(paths.appPath),
// Makes some environment variables available to the JS code, for example:
// if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
// It is absolutely essential that NODE_ENV is set to production
// during a production build.
// Otherwise React will be compiled in the very slow development mode.
new webpack.DefinePlugin(env.stringified),
// This is necessary to emit hot updates (currently CSS only):
isEnvDevelopment && new webpack.HotModuleReplacementPlugin(),
// Watcher doesn't work well if you mistype casing in a path so we use
// a plugin that prints an error when you attempt to do this.
// See https://github.com/facebook/create-react-app/issues/240
isEnvDevelopment && new CaseSensitivePathsPlugin(),
// If you require a missing module and then `npm install` it, you still have
// to restart the development server for webpack to discover it. This plugin
// makes the discovery automatic so you don't have to restart.
// See https://github.com/facebook/create-react-app/issues/186
isEnvDevelopment &&
new WatchMissingNodeModulesPlugin(paths.appNodeModules),
isEnvProduction &&
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: 'static/css/[name].[contenthash:8].css',
chunkFilename: 'static/css/[name].[contenthash:8].chunk.css',
}),
// Generate an asset manifest file with the following content:
// - "files" key: Mapping of all asset filenames to their corresponding
// output file so that tools can pick it up without having to parse
// `index.html`
// - "entrypoints" key: Array of files which are included in `index.html`,
// can be used to reconstruct the HTML if necessary
new ManifestPlugin({
fileName: 'asset-manifest.json',
publicPath: paths.publicUrlOrPath,
generate: (seed, files, entrypoints) => {
const manifestFiles = files.reduce((manifest, file) => {
manifest[file.name] = file.path;
return manifest;
}, seed);
const entrypointFiles = entrypoints.main.filter(
fileName => !fileName.endsWith('.map')
);
return {
files: manifestFiles,
entrypoints: entrypointFiles,
};
},
}),
// Moment.js is an extremely popular library that bundles large locale files
// by default due to how webpack interprets its code. This is a practical
// solution that requires the user to opt into importing specific locales.
// https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
// You can remove this if you don't use Moment.js:
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
// Generate a service worker script that will precache, and keep up to date,
// the HTML & assets that are part of the webpack build.
isEnvProduction &&
new WorkboxWebpackPlugin.GenerateSW({
clientsClaim: true,
exclude: [/\.map$/, /asset-manifest\.json$/],
importWorkboxFrom: 'cdn',
navigateFallback: paths.publicUrlOrPath + 'index.html',
navigateFallbackBlacklist: [
// Exclude URLs starting with /_, as they're likely an API call
new RegExp('^/_'),
// Exclude any URLs whose last part seems to be a file extension
// as they're likely a resource and not a SPA route.
// URLs containing a "?" character won't be blacklisted as they're likely
// a route with query params (e.g. auth callbacks).
new RegExp('/[^/?]+\\.[^/]+$'),
],
}),
// TypeScript type checking
useTypeScript &&
new ForkTsCheckerWebpackPlugin({
typescript: resolve.sync('typescript', {
basedir: paths.appNodeModules,
}),
async: isEnvDevelopment,
useTypescriptIncrementalApi: true,
checkSyntacticErrors: true,
resolveModuleNameModule: process.versions.pnp
? `${__dirname}/pnpTs.js`
: undefined,
resolveTypeReferenceDirectiveModule: process.versions.pnp
? `${__dirname}/pnpTs.js`
: undefined,
tsconfig: paths.appTsConfig,
reportFiles: [
'**',
'!**/__tests__/**',
'!**/?(*.)(spec|test).*',
'!**/src/setupProxy.*',
'!**/src/setupTests.*',
],
silent: true,
// The formatter is invoked directly in WebpackDevServerUtils during development
formatter: isEnvProduction ? typescriptFormatter : undefined,
}),
].filter(Boolean),
// Some libraries import Node modules but don't use them in the browser.
// Tell webpack to provide empty mocks for them so importing them works.
node: {
module: 'empty',
dgram: 'empty',
dns: 'mock',
fs: 'empty',
http2: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty',
},
// Turn off performance processing because we utilize
// our own hints via the FileSizeReporter
performance: false,
};
};
'use strict';
const fs = require('fs');
const errorOverlayMiddleware = require('react-dev-utils/errorOverlayMiddleware');
const evalSourceMapMiddleware = require('react-dev-utils/evalSourceMapMiddleware');
const noopServiceWorkerMiddleware = require('react-dev-utils/noopServiceWorkerMiddleware');
const ignoredFiles = require('react-dev-utils/ignoredFiles');
const redirectServedPath = require('react-dev-utils/redirectServedPathMiddleware');
const paths = require('./paths');
const getHttpsConfig = require('./getHttpsConfig');
const host = process.env.HOST || '0.0.0.0';
const sockHost = process.env.WDS_SOCKET_HOST;
const sockPath = process.env.WDS_SOCKET_PATH; // default: '/sockjs-node'
const sockPort = process.env.WDS_SOCKET_PORT;
module.exports = function(proxy, allowedHost) {
return {
// WebpackDevServer 2.4.3 introduced a security fix that prevents remote
// websites from potentially accessing local content through DNS rebinding:
// https://github.com/webpack/webpack-dev-server/issues/887
// https://medium.com/webpack/webpack-dev-server-middleware-security-issues-1489d950874a
// However, it made several existing use cases such as development in cloud
// environment or subdomains in development significantly more complicated:
// https://github.com/facebook/create-react-app/issues/2271
// https://github.com/facebook/create-react-app/issues/2233
// While we're investigating better solutions, for now we will take a
// compromise. Since our WDS configuration only serves files in the `public`
// folder we won't consider accessing them a vulnerability. However, if you
// use the `proxy` feature, it gets more dangerous because it can expose
// remote code execution vulnerabilities in backends like Django and Rails.
// So we will disable the host check normally, but enable it if you have
// specified the `proxy` setting. Finally, we let you override it if you
// really know what you're doing with a special environment variable.
disableHostCheck:
!proxy || process.env.DANGEROUSLY_DISABLE_HOST_CHECK === 'true',
// Enable gzip compression of generated files.
compress: true,
// Silence WebpackDevServer's own logs since they're generally not useful.
// It will still show compile warnings and errors with this setting.
clientLogLevel: 'none',
// By default WebpackDevServer serves physical files from current directory
// in addition to all the virtual build products that it serves from memory.
// This is confusing because those files won’t automatically be available in
// production build folder unless we copy them. However, copying the whole
// project directory is dangerous because we may expose sensitive files.
// Instead, we establish a convention that only files in `public` directory
// get served. Our build script will copy `public` into the `build` folder.
// In `index.html`, you can get URL of `public` folder with %PUBLIC_URL%:
// <link rel="icon" href="%PUBLIC_URL%/favicon.ico">
// In JavaScript code, you can access it with `process.env.PUBLIC_URL`.
// Note that we only recommend to use `public` folder as an escape hatch
// for files like `favicon.ico`, `manifest.json`, and libraries that are
// for some reason broken when imported through webpack. If you just want to
// use an image, put it in `src` and `import` it from JavaScript instead.
contentBase: paths.appPublic,
contentBasePublicPath: paths.publicUrlOrPath,
// By default files from `contentBase` will not trigger a page reload.
watchContentBase: true,
// Enable hot reloading server. It will provide WDS_SOCKET_PATH endpoint
// for the WebpackDevServer client so it can learn when the files were
// updated. The WebpackDevServer client is included as an entry point
// in the webpack development configuration. Note that only changes
// to CSS are currently hot reloaded. JS changes will refresh the browser.
hot: true,
// Use 'ws' instead of 'sockjs-node' on server since we're using native
// websockets in `webpackHotDevClient`.
transportMode: 'ws',
// Prevent a WS client from getting injected as we're already including
// `webpackHotDevClient`.
injectClient: false,
// Enable custom sockjs pathname for websocket connection to hot reloading server.
// Enable custom sockjs hostname, pathname and port for websocket connection
// to hot reloading server.
sockHost,
sockPath,
sockPort,
// It is important to tell WebpackDevServer to use the same "publicPath" path as
// we specified in the webpack config. When homepage is '.', default to serving
// from the root.
// remove last slash so user can land on `/test` instead of `/test/`
publicPath: paths.publicUrlOrPath.slice(0, -1),
// WebpackDevServer is noisy by default so we emit custom message instead
// by listening to the compiler events with `compiler.hooks[...].tap` calls above.
quiet: true,
// Reportedly, this avoids CPU overload on some systems.
// https://github.com/facebook/create-react-app/issues/293
// src/node_modules is not ignored to support absolute imports
// https://github.com/facebook/create-react-app/issues/1065
watchOptions: {
ignored: ignoredFiles(paths.appSrc),
},
https: getHttpsConfig(),
host,
overlay: false,
historyApiFallback: {
// Paths with dots should still use the history fallback.
// See https://github.com/facebook/create-react-app/issues/387.
disableDotRule: true,
index: paths.publicUrlOrPath,
},
public: allowedHost,
// `proxy` is run between `before` and `after` `webpack-dev-server` hooks
proxy,
before(app, server) {
// Keep `evalSourceMapMiddleware` and `errorOverlayMiddleware`
// middlewares before `redirectServedPath` otherwise will not have any effect
// This lets us fetch source contents from webpack for the error overlay
app.use(evalSourceMapMiddleware(server));
// This lets us open files from the runtime error overlay.
app.use(errorOverlayMiddleware());
if (fs.existsSync(paths.proxySetup)) {
// This registers user provided middleware for proxy reasons
require(paths.proxySetup)(app);
}
},
after(app) {
// Redirect to `PUBLIC_URL` or `homepage` from `package.json` if url not match
app.use(redirectServedPath(paths.publicUrlOrPath));
// This service worker file is effectively a 'no-op' that will reset any
// previous service worker registered for the same host:port combination.
// We do this in development to avoid hitting the production cache if
// it used the same host and port.
// https://github.com/facebook/create-react-app/issues/2272#issuecomment-302832432
app.use(noopServiceWorkerMiddleware(paths.publicUrlOrPath));
},
};
};
This diff could not be displayed because it is too large.
{
"name": "dfreact",
"version": "0.1.0",
"private": true,
"dependencies": {
"@babel/core": "7.9.0",
"@svgr/webpack": "4.3.3",
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.3.2",
"@testing-library/user-event": "^7.1.2",
"@toast-ui/react-chart": "^1.0.2",
"@typescript-eslint/eslint-plugin": "^2.10.0",
"@typescript-eslint/parser": "^2.10.0",
"axios": "^0.19.2",
"babel-eslint": "10.1.0",
"babel-jest": "^24.9.0",
"babel-loader": "8.1.0",
"babel-plugin-named-asset-import": "^0.3.6",
"babel-preset-react-app": "^9.1.2",
"bootstrap": "^4.5.0",
"camelcase": "^5.3.1",
"case-sensitive-paths-webpack-plugin": "2.3.0",
"css-loader": "3.4.2",
"dotenv": "8.2.0",
"dotenv-expand": "5.1.0",
"eslint": "^6.6.0",
"eslint-config-react-app": "^5.2.1",
"eslint-loader": "3.0.3",
"eslint-plugin-flowtype": "4.6.0",
"eslint-plugin-import": "2.20.1",
"eslint-plugin-jsx-a11y": "6.2.3",
"eslint-plugin-react": "7.19.0",
"eslint-plugin-react-hooks": "^1.6.1",
"express": "^4.17.1",
"file-loader": "4.3.0",
"fs-extra": "^8.1.0",
"html-webpack-plugin": "4.0.0-beta.11",
"identity-obj-proxy": "3.0.0",
"jest": "24.9.0",
"jest-environment-jsdom-fourteen": "1.0.1",
"jest-resolve": "24.9.0",
"jest-watch-typeahead": "0.4.2",
"mdbreact": "^4.27.0",
"mini-css-extract-plugin": "0.9.0",
"mysql": "^2.18.1",
"mysql2": "^2.1.0",
"optimize-css-assets-webpack-plugin": "5.0.3",
"path": "^0.12.7",
"pnp-webpack-plugin": "1.6.4",
"postcss-flexbugs-fixes": "4.1.0",
"postcss-loader": "3.0.0",
"postcss-normalize": "8.0.1",
"postcss-preset-env": "6.7.0",
"postcss-safe-parser": "4.0.1",
"react": "^16.13.1",
"react-app-polyfill": "^1.0.6",
"react-bootstrap": "^1.0.1",
"react-bootstrap-table": "^4.3.1",
"react-dev-utils": "^10.2.1",
"react-dom": "^16.13.1",
"react-router-dom": "^5.2.0",
"resolve": "1.15.0",
"resolve-url-loader": "3.1.1",
"sass-loader": "8.0.2",
"semver": "6.3.0",
"sequelize": "^5.21.10",
"sequelize-auto": "^0.4.29",
"style-loader": "0.23.1",
"terser-webpack-plugin": "2.3.5",
"ts-pnp": "1.1.6",
"url-loader": "2.3.0",
"webpack": "4.42.0",
"webpack-dev-server": "3.10.3",
"webpack-manifest-plugin": "2.2.0",
"workbox-webpack-plugin": "4.3.1"
},
"scripts": {
"start": "node scripts/start.js",
"build": "node scripts/build.js",
"server": "nodemon server/server.js",
"dev": "concurrently \"nodemon server/server.js\" \"node scripts/start.js\"",
"test": "node scripts/test.js"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"jest": {
"roots": [
"<rootDir>/src"
],
"collectCoverageFrom": [
"src/**/*.{js,jsx,ts,tsx}",
"!src/**/*.d.ts"
],
"setupFiles": [
"react-app-polyfill/jsdom"
],
"setupFilesAfterEnv": [
"<rootDir>/src/setupTests.js"
],
"testMatch": [
"<rootDir>/src/**/__tests__/**/*.{js,jsx,ts,tsx}",
"<rootDir>/src/**/*.{spec,test}.{js,jsx,ts,tsx}"
],
"testEnvironment": "jest-environment-jsdom-fourteen",
"transform": {
"^.+\\.(js|jsx|ts|tsx)$": "<rootDir>/node_modules/babel-jest",
"^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
"^(?!.*\\.(js|jsx|ts|tsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
},
"transformIgnorePatterns": [
"[/\\\\]node_modules[/\\\\].+\\.(js|jsx|ts|tsx)$",
"^.+\\.module\\.(css|sass|scss)$"
],
"modulePaths": [],
"moduleNameMapper": {
"^react-native$": "react-native-web",
"^.+\\.module\\.(css|sass|scss)$": "identity-obj-proxy"
},
"moduleFileExtensions": [
"web.js",
"js",
"web.ts",
"ts",
"web.tsx",
"tsx",
"json",
"web.jsx",
"jsx",
"node"
],
"watchPlugins": [
"jest-watch-typeahead/filename",
"jest-watch-typeahead/testname"
]
},
"babel": {
"presets": [
"react-app"
]
},
"proxy": "http://localhost:4000",
"devDependencies": {
"concurrently": "^5.2.0",
"nodemon": "^2.0.4"
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:
'use strict';
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'production';
process.env.NODE_ENV = 'production';
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
throw err;
});
// Ensure environment variables are read.
require('../config/env');
const path = require('path');
const chalk = require('react-dev-utils/chalk');
const fs = require('fs-extra');
const webpack = require('webpack');
const configFactory = require('../config/webpack.config');
const paths = require('../config/paths');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
const printHostingInstructions = require('react-dev-utils/printHostingInstructions');
const FileSizeReporter = require('react-dev-utils/FileSizeReporter');
const printBuildError = require('react-dev-utils/printBuildError');
const measureFileSizesBeforeBuild =
FileSizeReporter.measureFileSizesBeforeBuild;
const printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild;
const useYarn = fs.existsSync(paths.yarnLockFile);
// These sizes are pretty large. We'll warn for bundles exceeding them.
const WARN_AFTER_BUNDLE_GZIP_SIZE = 512 * 1024;
const WARN_AFTER_CHUNK_GZIP_SIZE = 1024 * 1024;
const isInteractive = process.stdout.isTTY;
// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
process.exit(1);
}
// Generate configuration
const config = configFactory('production');
// We require that you explicitly set browsers and do not fall back to
// browserslist defaults.
const { checkBrowsers } = require('react-dev-utils/browsersHelper');
checkBrowsers(paths.appPath, isInteractive)
.then(() => {
// First, read the current file sizes in build directory.
// This lets us display how much they changed later.
return measureFileSizesBeforeBuild(paths.appBuild);
})
.then(previousFileSizes => {
// Remove all content but keep the directory so that
// if you're in it, you don't end up in Trash
fs.emptyDirSync(paths.appBuild);
// Merge with the public folder
copyPublicFolder();
// Start the webpack build
return build(previousFileSizes);
})
.then(
({ stats, previousFileSizes, warnings }) => {
if (warnings.length) {
console.log(chalk.yellow('Compiled with warnings.\n'));
console.log(warnings.join('\n\n'));
console.log(
'\nSearch for the ' +
chalk.underline(chalk.yellow('keywords')) +
' to learn more about each warning.'
);
console.log(
'To ignore, add ' +
chalk.cyan('// eslint-disable-next-line') +
' to the line before.\n'
);
} else {
console.log(chalk.green('Compiled successfully.\n'));
}
console.log('File sizes after gzip:\n');
printFileSizesAfterBuild(
stats,
previousFileSizes,
paths.appBuild,
WARN_AFTER_BUNDLE_GZIP_SIZE,
WARN_AFTER_CHUNK_GZIP_SIZE
);
console.log();
const appPackage = require(paths.appPackageJson);
const publicUrl = paths.publicUrlOrPath;
const publicPath = config.output.publicPath;
const buildFolder = path.relative(process.cwd(), paths.appBuild);
printHostingInstructions(
appPackage,
publicUrl,
publicPath,
buildFolder,
useYarn
);
},
err => {
const tscCompileOnError = process.env.TSC_COMPILE_ON_ERROR === 'true';
if (tscCompileOnError) {
console.log(
chalk.yellow(
'Compiled with the following type errors (you may want to check these before deploying your app):\n'
)
);
printBuildError(err);
} else {
console.log(chalk.red('Failed to compile.\n'));
printBuildError(err);
process.exit(1);
}
}
)
.catch(err => {
if (err && err.message) {
console.log(err.message);
}
process.exit(1);
});
// Create the production build and print the deployment instructions.
function build(previousFileSizes) {
// We used to support resolving modules according to `NODE_PATH`.
// This now has been deprecated in favor of jsconfig/tsconfig.json
// This lets you use absolute paths in imports inside large monorepos:
if (process.env.NODE_PATH) {
console.log(
chalk.yellow(
'Setting NODE_PATH to resolve modules absolutely has been deprecated in favor of setting baseUrl in jsconfig.json (or tsconfig.json if you are using TypeScript) and will be removed in a future major release of create-react-app.'
)
);
console.log();
}
console.log('Creating an optimized production build...');
const compiler = webpack(config);
return new Promise((resolve, reject) => {
compiler.run((err, stats) => {
let messages;
if (err) {
if (!err.message) {
return reject(err);
}
let errMessage = err.message;
// Add additional information for postcss errors
if (Object.prototype.hasOwnProperty.call(err, 'postcssNode')) {
errMessage +=
'\nCompileError: Begins at CSS selector ' +
err['postcssNode'].selector;
}
messages = formatWebpackMessages({
errors: [errMessage],
warnings: [],
});
} else {
messages = formatWebpackMessages(
stats.toJson({ all: false, warnings: true, errors: true })
);
}
if (messages.errors.length) {
// Only keep the first error. Others are often indicative
// of the same problem, but confuse the reader with noise.
if (messages.errors.length > 1) {
messages.errors.length = 1;
}
return reject(new Error(messages.errors.join('\n\n')));
}
if (
process.env.CI &&
(typeof process.env.CI !== 'string' ||
process.env.CI.toLowerCase() !== 'false') &&
messages.warnings.length
) {
console.log(
chalk.yellow(
'\nTreating warnings as errors because process.env.CI = true.\n' +
'Most CI servers set it automatically.\n'
)
);
return reject(new Error(messages.warnings.join('\n\n')));
}
return resolve({
stats,
previousFileSizes,
warnings: messages.warnings,
});
});
});
}
function copyPublicFolder() {
fs.copySync(paths.appPublic, paths.appBuild, {
dereference: true,
filter: file => file !== paths.appHtml,
});
}
'use strict';
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'development';
process.env.NODE_ENV = 'development';
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
throw err;
});
// Ensure environment variables are read.
require('../config/env');
const fs = require('fs');
const chalk = require('react-dev-utils/chalk');
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const clearConsole = require('react-dev-utils/clearConsole');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
const {
choosePort,
createCompiler,
prepareProxy,
prepareUrls,
} = require('react-dev-utils/WebpackDevServerUtils');
const openBrowser = require('react-dev-utils/openBrowser');
const paths = require('../config/paths');
const configFactory = require('../config/webpack.config');
const createDevServerConfig = require('../config/webpackDevServer.config');
const useYarn = fs.existsSync(paths.yarnLockFile);
const isInteractive = process.stdout.isTTY;
// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
process.exit(1);
}
// Tools like Cloud9 rely on this.
const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000;
const HOST = process.env.HOST || '0.0.0.0';
if (process.env.HOST) {
console.log(
chalk.cyan(
`Attempting to bind to HOST environment variable: ${chalk.yellow(
chalk.bold(process.env.HOST)
)}`
)
);
console.log(
`If this was unintentional, check that you haven't mistakenly set it in your shell.`
);
console.log(
`Learn more here: ${chalk.yellow('https://bit.ly/CRA-advanced-config')}`
);
console.log();
}
// We require that you explicitly set browsers and do not fall back to
// browserslist defaults.
const { checkBrowsers } = require('react-dev-utils/browsersHelper');
checkBrowsers(paths.appPath, isInteractive)
.then(() => {
// We attempt to use the default port but if it is busy, we offer the user to
// run on a different port. `choosePort()` Promise resolves to the next free port.
return choosePort(HOST, DEFAULT_PORT);
})
.then(port => {
if (port == null) {
// We have not found a port.
return;
}
const config = configFactory('development');
const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
const appName = require(paths.appPackageJson).name;
const useTypeScript = fs.existsSync(paths.appTsConfig);
const tscCompileOnError = process.env.TSC_COMPILE_ON_ERROR === 'true';
const urls = prepareUrls(
protocol,
HOST,
port,
paths.publicUrlOrPath.slice(0, -1)
);
const devSocket = {
warnings: warnings =>
devServer.sockWrite(devServer.sockets, 'warnings', warnings),
errors: errors =>
devServer.sockWrite(devServer.sockets, 'errors', errors),
};
// Create a webpack compiler that is configured with custom messages.
const compiler = createCompiler({
appName,
config,
devSocket,
urls,
useYarn,
useTypeScript,
tscCompileOnError,
webpack,
});
// Load proxy config
const proxySetting = require(paths.appPackageJson).proxy;
const proxyConfig = prepareProxy(
proxySetting,
paths.appPublic,
paths.publicUrlOrPath
);
// Serve webpack assets generated by the compiler over a web server.
const serverConfig = createDevServerConfig(
proxyConfig,
urls.lanUrlForConfig
);
const devServer = new WebpackDevServer(compiler, serverConfig);
// Launch WebpackDevServer.
devServer.listen(port, HOST, err => {
if (err) {
return console.log(err);
}
if (isInteractive) {
clearConsole();
}
// We used to support resolving modules according to `NODE_PATH`.
// This now has been deprecated in favor of jsconfig/tsconfig.json
// This lets you use absolute paths in imports inside large monorepos:
if (process.env.NODE_PATH) {
console.log(
chalk.yellow(
'Setting NODE_PATH to resolve modules absolutely has been deprecated in favor of setting baseUrl in jsconfig.json (or tsconfig.json if you are using TypeScript) and will be removed in a future major release of create-react-app.'
)
);
console.log();
}
console.log(chalk.cyan('Starting the development server...\n'));
openBrowser(urls.localUrlForBrowser);
});
['SIGINT', 'SIGTERM'].forEach(function(sig) {
process.on(sig, function() {
devServer.close();
process.exit();
});
});
if (isInteractive || process.env.CI !== 'true') {
// Gracefully exit when stdin ends
process.stdin.on('end', function() {
devServer.close();
process.exit();
});
process.stdin.resume();
}
})
.catch(err => {
if (err && err.message) {
console.log(err.message);
}
process.exit(1);
});
'use strict';
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'test';
process.env.NODE_ENV = 'test';
process.env.PUBLIC_URL = '';
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
throw err;
});
// Ensure environment variables are read.
require('../config/env');
const jest = require('jest');
const execSync = require('child_process').execSync;
let argv = process.argv.slice(2);
function isInGitRepository() {
try {
execSync('git rev-parse --is-inside-work-tree', { stdio: 'ignore' });
return true;
} catch (e) {
return false;
}
}
function isInMercurialRepository() {
try {
execSync('hg --cwd . root', { stdio: 'ignore' });
return true;
} catch (e) {
return false;
}
}
// Watch unless on CI or explicitly running all tests
if (
!process.env.CI &&
argv.indexOf('--watchAll') === -1 &&
argv.indexOf('--watchAll=false') === -1
) {
// https://github.com/facebook/create-react-app/issues/5210
const hasSourceControl = isInGitRepository() || isInMercurialRepository();
argv.push(hasSourceControl ? '--watch' : '--watchAll');
}
jest.run(argv);
const mysql = require('mysql');
const db = mysql.createPool({
host: 'localhost',
port: '3307',
user: 'root',
password: 'yj',
database: 'projectdf'
});
module.exports = db;
\ No newline at end of file
const express = require('express');
const app = express();
const PORT = process.env.PORT || 4000;
const db = require('./config/db');
app.get('/api/host', (req, res) => {
res.send({ host : 'Rekrow' });
})
app.get('/api/home_most_epic', (req, res) => {
db.query("SELECT * FROM (SELECT ROW_NUMBER() over(order by temp.value desc)NUM, PICTURE,NAME, VALUE FROM (SELECT itemId, count(itemId) AS VALUE, date(droped_at) FROM item_drop_exception WHERE date(droped_at) = DATE(NOW()) GROUP BY itemid) temp join item_exception ie ON ie.itemId = temp.itemid) t WHERE t.NUM <=5", (err, data) => {
if(!err) {
res.send(data);
} else {
console.log(err);
res.send(err);
}
})
})
app.get('/api/home_most_channel', (req, res) => {
db.query("SELECT * from(SELECT * , ROW_NUMBER() over(order by temp.value desc)NUM from(select channel_name, channel_number, count(itemId) AS VALUE FROM item_drop_exception WHERE date(droped_at) = DATE(NOW()) GROUP BY CHANNEL_Name, Channel_NUMBER) temp) t WHERE num<=5",
(err, data) => {
if(!err) {
res.send(data);
} else {
console.log(err);
res.send(err);
}
})
})
app.get('/api/most_channel', (req, res) => {
db.query("SELECT channel_name, channel_number, count(itemId) AS VALUE, ROW_NUMBER() OVER (ORDER BY value desc) as NUM FROM item_drop_exception WHERE date(droped_at) = DATE(NOW()) GROUP BY CHANNEL_Name, Channel_NUMBER order BY VALUE desc",
(err, data) => {
if(!err) {
res.send(data);
} else {
console.log(err);
res.send(err);
}
})
})
app.get('/api/week_most_channel', (req, res) => {
db.query("SELECT *, ROW_NUMBER() OVER (ORDER BY T.value desc) as NUM FROM(SELECT channel_name, channel_number,COUNT(id) AS VALUE FROM item_drop_exception WHERE droped_at BETWEEN DATE_ADD(NOW(),INTERVAL - 1 week) AND NOW() GROUP BY CHANNEL_NAME, CHANNEL_NUMBER) T",
(err, data) => {
if(!err) {
res.send(data);
} else {
console.log(err);
res.send(err);
}
})
})
app.get('/api/most_epic', (req, res) => {
db.query("SELECT NAME, PICTURE,VALUE, ROW_NUMBER() OVER (ORDER BY value desc) as NUM FROM (SELECT itemId, count(itemId) AS VALUE, date(droped_at) FROM item_drop_exception WHERE date(droped_at) = DATE(NOW()) GROUP BY itemid) temp join item_exception ie ON ie.itemId = temp.itemid",
(err, data) => {
if(!err) {
res.send(data);
} else {
console.log(err);
res.send(err);
}
})
})
app.get('/api/week_most_epic', (req, res) => {
db.query("SELECT NAME, PICTURE,VALUE, ROW_NUMBER() OVER (ORDER BY T.value desc) as NUM FROM(SELECT itemId, COUNT(itemId) AS VALUE FROM item_drop_exception WHERE droped_at BETWEEN DATE_ADD(NOW(),INTERVAL - 1 week) AND NOW() GROUP BY itemId) T JOIN item_exception i ON i.itemId = T.itemId",
(err, data) => {
if(!err) {
res.send(data);
} else {
console.log(err);
res.send(err);
}
})
})
//search data
app.get('/api/search_data/:searchTag', (req, res) => {
const searchTag = req.params.searchTag;
//console.log(searchTag);
res.json({searchTag});
})
app.get('/api/getImage/:searchName', (req, res) => {
const searchName =req.params.searchName;
let id;
let valueSql = `SELECT itemId as keyValue, name, picture FROM item_exception WHERE NAME LIKE '${searchName}'`;
db.query(valueSql,searchName,(err, data) => {
if(!err) {
res.send(data);
} else {
console.log(err);
res.send(err);
}
})
})
app.get('/api/search_epic1/:searchName', (req, res) => {
const searchName =req.params.searchName;
let id;
let valueSql = `SELECT itemId as keyValue FROM item_exception WHERE NAME LIKE '${searchName}'`;
db.query(valueSql,searchName,(err, data) => {
if(!err) {
id = data[0].keyValue;
let resultSql =`SELECT T.channel_name, T.channel_number, T.VALUE, T.num from(SELECT itemId, channel_name, channel_number, COUNT(*) AS VALUE, ROW_NUMBER() over(order by value DESC) NUM FROM item_drop_exception WHERE itemId = (SELECT itemId FROM item_exception WHERE itemid = '${id}') AND date(droped_at) = DATE(NOW()) GROUP BY channel_name, channel_number) T WHERE T.NUM<=5 ORDER BY T.NUM`
//console.log("id: "+ id);
db.query( resultSql,id,(err, data) => {
if(!err) {
//console.log("data : " + data)
res.send(data);
} else {
//console.log(err);
res.send(err);
}
})
} else {
//console.log(err);
res.send(err);
}
})
})
//원그래프 용 쿼리
app.get('/api/search_epic2/:searchName', (req, res) => {
const searchName =req.params.searchName;
let id;
let valueSql = `SELECT itemId as keyValue FROM item_exception WHERE NAME LIKE '${searchName}'`;
db.query(valueSql,searchName,(err, data) => {
if(!err) {
id=data[0].keyValue;
console.log("dataLog2: "+ JSON.stringify(data))
var resultSql =`SELECT T.channel_name, T.channel_number, T.VALUE, T.num from(SELECT itemId, channel_name, channel_number, COUNT(*) AS VALUE, ROW_NUMBER() over(order by value DESC) NUM FROM item_drop_exception WHERE itemId = (SELECT itemId FROM item_exception WHERE itemid = '${id}') AND date(droped_at) = DATE(NOW()) GROUP BY channel_name, channel_number) T WHERE T.NUM<=7 ORDER BY T.NUM`
db.query( resultSql,id,(err, data) => {
if(!err) {
res.send(data);
} else {
console.log(err);
res.send(err);
}
})
} else {
//console.log(err);
res.send(err);
}
})
})
app.get('/api/search_epic3/:searchName', (req, res) => {
const searchName =req.params.searchName;
var id;
var i =0;
var list1 = [];
var valueSql = `SELECT itemId as keyValue FROM item_exception WHERE NAME LIKE '${searchName}'`;
db.query(valueSql,searchName,(err, data) => {
if(!err) {
id=data[0].keyValue;
//반복문으로 진행?
while(i<7)
{
//console.log("iterator: "+i)
var resultSql1 =`SELECT T.channel_name, T.channel_number, T.VALUE, T.num from(SELECT itemId, channel_name, channel_number, COUNT(*) AS VALUE, ROW_NUMBER() over(order by value DESC) NUM FROM item_drop_exception WHERE itemId = (SELECT itemId FROM item_exception WHERE itemid = '${id}') AND date(droped_at) = date(date_add(now(),interval -${i} DAY)) GROUP BY channel_name, channel_number) T WHERE T.NUM<=3 ORDER BY T.num`
db.query( resultSql1,id,(err, result) => {
if(!err) {
list1.push(result);
console.log(i+"번째 리스트 push, 내용: "+JSON.stringify(result));
if(list1.length==7)
{
res.send(list1);
}
}
else {
// console.log(err);
res.send(err);
}
})
i++;
}
} else {
console.log(err);
res.send(err);
}
})
})
app.listen(PORT, () => {
console.log(`Server On : http://localhost:${PORT}/`);
})
@charset "utf-8";
@import url('https://fonts.googleapis.com/css?family=Nanum+Gothic');
*{
margin:0 auto;
text-align: center;
padding: 0;
}
.active-cyan-4 input[type=text]:focus:not([readonly]) {
border: 1px solid #1ABC9C;
box-shadow: 0 0 0 1px #1ABC9C;
width: 60%;
margin: auto;
}
.active-cyan-4 input[type=text] {
width: 60%;
margin: auto;
}
body{
font: 22px 'Nanum Gothic', sans-serif;
}
a{
text-decoration: none;
color: #404040;
}
li{
list-style: none;
}
#menu{ /*백그라운드 컬러만 지정*/
padding-top: 5px;
padding-bottom: 5px;
font: 20px 'Nanum Gothic', sans-serif;
background: #1ABC9C;
}
#menu ul{
width:100%;
height:70%;
margin: 0 auto;
overflow: hidden;
}
#menu ul li{
float: left;
width: 25%;
line-height: 50px;
text-align: center;
background: #1ABC9C;
}
#menu ul li a{
display:block;
font-weight: 500;
color: rgba(255,255,255,0.6);
text-decoration: "none";
}
#menu ul li a:hover{
text-decoration: "none";
background: rgb(21, 150, 124);
font-weight: bold;
color: #fff;
}
.App {
text-align: center;
}
.App-logo {
height: 40vmin;
pointer-events: none;
}
@media (prefers-reduced-motion: no-preference) {
.App-logo {
animation: App-logo-spin infinite 20s linear;
}
}
.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.App-link {
color: #61dafb;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
/* src/app.js */
import ReactDOM from 'react-dom';
import { Route, BrowserRouter, Switch, Link, useHistory} from 'react-router-dom';
import React, { Component } from 'react';
import Home from './home';
//import {navigate} from "@reach/router"
import TodayChannel from './TodayChannel';
import TodayEpic from './TodayEpic';
import WeekChannel from './WeekChannel';
import WeekEpic from './WeekEpic'
import Search from './Search'
import App2 from './App2'
import './App.css'
import axios from 'axios';
const TestPage = ({data}) => {
const history = useHistory();
React.useEffect(()=>{
console.log(data)
if(data.length > 0)
history.push('/searchList/result')
}, [data])
return (
<></>
)
}
class App extends Component {
constructor(props) {
super(props)
this.state = {
searchList: [], //검색 결과
screenWidth: 0, //보여지는 윈도우 가로길이
}
}
onKeyDownMethod = async(e)=>
{
if(e.keyCode===13)//엔터 입력시
{
const searchTag = document.querySelector("#searchInput").value;
const res = await axios.get(`/api/search_data/${searchTag}`);
console.log(res.data);
this.setState({searchList: [res.data]})
}
}
render() {
const sStyle={
margin: "0 auto",
}
const lStyle ={
color: "black",
top: "30px",
height: "100%",
fontSize: "50px",
fontWeight: "bold",
color: "black",
textDecoration: "none",
}
return (
<BrowserRouter>
<div>
<div style={{height: "50px"}}></div>
<div id = "menu">
<ul>
<li><Link to='/todayEpic'>오늘 가장 많이 나온 에픽</Link></li>
<li><Link to='/todayChannel'>오늘 가장 많이 나온 채널</Link></li>
<li><Link to='/WeekEpic'>지난 1주간 가장 많이 나온 에픽</Link></li>
<li><Link to='/WeekChannel'>지난 1주간 가장 많이 나온 채널</Link></li>
{/* <li><Link to='/searchList'>테스트</Link></li>*/}
</ul>
</div>
<TestPage data={this.state.searchList} />
<div style={{height: "50px"}}></div>
<div id ="HomeLogo">
<Link style={lStyle}to='/'>D&F Epic</Link>
</div>
<div style={{height: "50px"}}></div>
<div class="active-cyan-4">
<input id="searchInput" onKeyDown={this.onKeyDownMethod} class="form-control" type="text" placeholder="Search" aria-label="Search"/>
</div>
<div style={{height: "50px"}}></div>
<Switch>
<Route exact path='/'><Home></Home></Route>
<Route path='/todayChannel'><TodayChannel></TodayChannel></Route>
<Route path='/todayEpic'><TodayEpic></TodayEpic></Route>
<Route path='/WeekEpic'><WeekEpic></WeekEpic></Route>
<Route path='/WeekChannel'><WeekChannel></WeekChannel></Route>
{/*<Route exact path='/searchList'><App2 searchList={this.state.searchList}></App2></Route>*/}
<Route path='/searchList/result'><Search searchList={this.state.searchList}></Search></Route>
<Route path ='/'>Not Found</Route>
</Switch>
</div>
</BrowserRouter>
);
}
}
ReactDOM.render(<BrowserRouter><App/></BrowserRouter>,document.getElementById('root'));
export default App;
import React from 'react';
import { render } from '@testing-library/react';
import App from './App';
test('renders learn react link', () => {
const { getByText } = render(<App />);
const linkElement = getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});
import React, { Component } from 'react';
import './App.css';
import axios from 'axios';
import 'bootstrap/dist/css/bootstrap.min.css';
import 'tui-chart/dist/tui-chart.css'
import {ColumnChart} from '@toast-ui/react-chart'
const data = {
categories: ['월', '화','수', '목', '금','토','일'],
series: [
{
name: ['심연 1채'],
data: [20, 15, 50, 7, 40, 40,100]
},
{
name: '2위',
data: [8, 10, 7, 20, 50, 30,80]
},
{
name: '3위',
data: [20, 15, 50, 7, 40, 40,4]
},
{
name: '4위',
data: [8, 10, 7, 20, 50, 30,5]
}
]
};
const options = {
chart: {
width: 1160,
height: 650,
title: 'Monthly Revenue',
format: '1,000'
},
yAxis: {
title: '아이템 드롭 갯수',
min: 0,
max: 100,
suffix: '개'
},
xAxis: {
title: '날짜',
},
series: {
showLabel: true
},
legend: {
align: 'top'
}
};
class App2 extends Component{
constructor(props) {
super(props)
this.state = {
host : '',
searchList: this.props.searchList,
myEpicData: [],
myChannelData: [],
screenWidth: 0, //보여지는 윈도우 가로길이
}
}
componentDidUpdate(){
}
render() {
return(
<div>
</div>
);
}
}
export default App2;
\ No newline at end of file
import React, { Component } from 'react';
import './App.css';
import axios from 'axios';
import 'bootstrap/dist/css/bootstrap.min.css';
import * as ReactBootStrap from "react-bootstrap";
import {PieChart,ColumnChart} from '@toast-ui/react-chart'
let today = new Date();
let date = today.getDate();// 요일
let count =0;
let controll =1;
let swit = 0;
let test = [];
let testV =[];
let coltest=[];
let coltestV=[];
let tdata ={
categories:['채널 이름'],
series:[]
};
let colData1 ={
categories:[String(date+'일')],
series:[]
};
let colData2 ={
categories:[String(date-1+'일')],
series:[]
};
let colData3 ={
categories:[String(date-2+'일')],
series:[]
};
let colData4 ={
categories:[String(date-3+'일')],
series:[]
};
let colData5 ={
categories:[String(date-4+'일')],
series:[]
};
let colData6 ={
categories:[String(date-5+'일')],
series:[]
};
let colData7 ={
categories:[String(date-6+'일')],
series:[]
};
const tdataPush = (test1,test2,result) =>
{
let tSeries =[]
result.series =[];
for(let i =0;i<test1.length;i++)
{
tSeries.push({name: String(test1[i]), data: Number(test2[i])})
}
result.series=tSeries;
console.log("tdata: "+JSON.stringify(result));
console.log("tdata: "+JSON.stringify(result.series[0]));
swit++;
}
const colDataPush = (test1,test2,result) =>
{
let tSeries =[]
result.series =[];
for(let i = count ;(i<(controll*3))&&(count<22);i++)
{
// console.log("coldata: "+JSON.stringify(test2[i]));
console.log("count: "+count);
console.log("controll: "+controll+" & "+controll*3);
tSeries.push({name: String(test1[i]), data: Number(test2[i])})
count++;
}
controll++;
console.log("count: "+count);
result.series=tSeries;
console.log("coldatag: "+JSON.stringify(result));
console.log("coldataf: "+JSON.stringify(result.series[0]));
swit++;
}
var theme = {
series: {
colors: [
'#83b14e', '#458a3f', '#295ba0', '#2a4175', '#289399',
'#289399', '#617178', '#8a9a9a', '#516f7d', '#dddddd'
]
}
};
const renderChannelData = (data1, index) =>{
return(
<tr key = {index}>
<td><img src={`/images/${data1.num}.jpg`} width="50px"></img></td>
<td>{data1.channel_name} {data1.channel_number}</td>
<td>{data1.VALUE}</td>
</tr>
)
}
const renderInfo = (data1, index) =>{
return(
<div>
<img src={`/images/${data1.picture}.png`} width="50px"></img> {data1.name}
</div>
)
}
class Search extends Component{
constructor(props) {
super(props)
this.state = {
searchList: [{searchTag: ''}],
searchID : '',
EpicInfo:[],
searchEpicData: [],
searchDayChannelData: [],
searchweekChannelData: [],
colOptions:{
chart: {
width: 550,
height: 550,
format: '1,000'
},
yAxis: {
title: '드랍 갯수',
min: 0,
max: 70
},
xAxis: {
title: '드랍 채널 top 3'
},
legend: {
align: 'top'
}
},
cOptions:{
chart: {
width: 660,
height: 560,
title: '오늘의 드랍 채널(Top 7)'
},
tooltip: {
suffix: '개'
}
},
isFinish: false,
screenWidth: 0, //보여지는 윈도우 가로길이
}
}
_getImage= async(data) =>{
const res = await axios.get(`/api/getImage/${data[0].searchTag}`);
this.setState({EpicInfo: res.data})
}
_getSearch1 = async(data) => {//검색시 최상단 3~5개 채널 나오는 것
console.log(data[0].searchTag)
const res = await axios.get(`/api/search_epic1/${data[0].searchTag}`);
this.setState({searchEpicData : res.data})
//console.log("search:"+ JSON.stringify(this.state.searchEpicData))
//console.log(this.state.myEpicData)
}
_getSearch2 = async(data) => {//검색시 나오는 원형 차트용 데이터
swit=0;
test =[];
testV =[];
const res = await axios.get(`/api/search_epic2/${data[0].searchTag}`);
this.setState({searchDayChannelData : res.data})
for(const dataObj of this.state.searchDayChannelData)
{
test.push(dataObj.channel_name+' '+dataObj.channel_number);
testV.push(parseInt(dataObj.VALUE))
}
tdataPush(test,testV,tdata);
}
_getSearch3 = async(data) => {//검색시 나오는 막대 차트용 데이터
coltest =[]; //[{3}{3} 3 3 3 3 3 ]
coltestV =[];
console.log("before colt: "+ JSON.stringify(coltest));
console.log("before colv: "+ JSON.stringify(coltestV));
this.setState({isFinish: false});
const res = await axios.get(`/api/search_epic3/${data[0].searchTag}`);
this.setState({searchweekChannelData : res.data})
for(const dataObj of this.state.searchweekChannelData)
{
for(let i = 0; i< dataObj.length; i++)
{
coltest.push(dataObj[i].channel_name+' '+dataObj[i].channel_number);
coltestV.push(parseInt(dataObj[i].VALUE));
//console.log("dataOBJ "+i+": "+JSON.stringify(dataObj[i]))
}
}
console.log("colt: "+ JSON.stringify(coltest));
console.log("colv: "+ JSON.stringify(coltestV));
controll=1; count =0;
colData1.series=[];
colData2.series=[];
colData3.series=[];
colData4.series=[];
colData5.series=[];
colData6.series=[];
colData7.series=[];
colDataPush(coltest,coltestV,colData1);
console.log("c1"+colData1.series);
colDataPush(coltest,coltestV,colData2);
colDataPush(coltest,coltestV,colData3);
colDataPush(coltest,coltestV,colData4);
colDataPush(coltest,coltestV,colData5);
colDataPush(coltest,coltestV,colData6);
colDataPush(coltest,coltestV,colData7);
this.setState({isFinish: true});
}
_getSearch4 = ()=>{ //검색시 나오는 세트용 데이터
}
componentDidMount() {
try{
if(this.state.searchList[0]!=this.props.searchList[0])
{
this.setState({searchList: this.props.searchList})
this._getSearch1(this.props.searchList)
this._getSearch2(this.props.searchList)
this._getSearch3(this.props.searchList)
this._getImage(this.props.searchList)
}
this._setWidth()
}
catch(e)
{
console.log(e)
}
}
componentDidUpdate(){
if(this.state.searchList[0]!=this.props.searchList[0])
{
this.setState({searchList: this.props.searchList})
this._getSearch1(this.props.searchList)
this._getSearch2(this.props.searchList)
this._getSearch3(this.props.searchList)
this._getImage(this.props.searchList)
}
}
render() {
const lStyle ={
color: "black",
top: "30px",
height: "100%",
fontSize: "50px",
fontWeight: "bold",
color: "black",
textDecoration: "none",
}
if(this.state.isFinish)
{
return(
<div>
<h1>{this.state.EpicInfo.map(renderInfo)}</h1>
<span>
<ReactBootStrap.Table striped bordered hover>
<thead>
<tr>
<th>순위</th>
<th>채널</th>
<th>나온 횟수</th>
</tr>
</thead>
<tbody>
{this.state.searchEpicData.map(renderChannelData)}
</tbody>
</ReactBootStrap.Table>
</span>
<div>
<PieChart
data={tdata}
options={this.state.cOptions}
/>
</div>
<div>
<div>
<ColumnChart
data={colData1}
options={this.state.colOptions}
/>
</div><div>
<ColumnChart
data={colData2}
options={this.state.colOptions}
/>
</div><div>
<ColumnChart
data={colData3}
options={this.state.colOptions}
/>
</div><div>
<ColumnChart
data={colData4}
options={this.state.colOptions}
/>
</div><div>
<ColumnChart
data={colData5}
options={this.state.colOptions}
/></div><div>
<ColumnChart
data={colData6}
options={this.state.colOptions}
/></div><div>
<ColumnChart
data={colData7}
options={this.state.colOptions}
/></div>
</div>
</div>
);
}
else{
return(<div>로딩중입니다.</div>);
}
}
}
export default Search;
\ No newline at end of file
import React, { Component } from 'react';
import './App.css';
import axios from 'axios';
import 'bootstrap/dist/css/bootstrap.min.css';
import * as ReactBootStrap from "react-bootstrap";
const renderChannelData = (data1, index) =>{
return(
<tr key = {index}>
<td>{data1.NUM}</td>
<td>{data1.channel_name} {data1.channel_number}</td>
<td>{data1.VALUE}</td>
</tr>
)
}
class TodayChannel extends Component{
constructor(props) {
super(props)
this.state = {
host : '',
myChannelData: [],
}
}
_getMostChannel = async() => {
const res = await axios.get('/api/most_channel');
console.log(res.data)
this.setState({myChannelData : res.data})
console.log(this.state.myChannelData)
}
_getHost = async() => {
const res = await axios.get('/api/host');
console.log(res.data.host)
this.setState({ host : res.data.host })
}
componentDidMount() {
this._getHost();
this._getMostChannel();
}
render() {
return(
this.state.myChannelData.length === 0 ? (<div>로딩중입니다.</div>):(
<div>
<br></br>
<br></br>
<br></br>
<div className='todayChannel'>
<div>
<div>
<br></br>
<h3>오늘 에픽이 가장 많이 나온 채널</h3>
</div>
</div>
</div>
<div>
<ReactBootStrap.Table striped bordered hover>
<thead>
<tr>
<th>순위</th>
<th>채널</th>
<th>나온 횟수</th>
</tr>
</thead>
<tbody>
{this.state.myChannelData.map(renderChannelData)}
</tbody>
</ReactBootStrap.Table>
</div>
</div>)
);
}
}
export default TodayChannel;
\ No newline at end of file
import React, { Component } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import * as ReactBootStrap from "react-bootstrap";
import axios from 'axios';
const renderEpicData = (data1, index) =>{
return(
<tr key = {index}>
<td>{data1.NUM}</td>
<td><img width="40%" src={`/images/${data1.PICTURE}.png`}></img></td>
<td>{data1.NAME}</td>
<td>{data1.VALUE}</td>
</tr>
)
}
class TodayEpic extends Component {
constructor(props) {
super(props)
this.state = {
host : '',
myEpicData: [],
}
}
componentDidMount() {
this._getHost();
this._getMostEpic();
}
_getMostEpic = async() => {
const res = await axios.get('/api/most_epic');
this.setState({myEpicData : res.data})
}
_getHost = async() => {
const res = await axios.get('/api/host');
this.setState({ host : res.data.host })
}
render() {
return(
this.state.myEpicData.length === 0? (<div>로딩중입니다.</div>):(
<div>
<br></br>
<br></br>
<br></br>
<div className='todayEpic'>
<h3>오늘 가장 많이 나온 에픽 아이템</h3>
<div>
<ReactBootStrap.Table striped bordered hover>
<thead>
<tr>
<th>순위</th>
<th colSpan='2'>에픽 아이템</th>
<th>나온 횟수</th>
</tr>
</thead>
<tbody>
{this.state.myEpicData.map(renderEpicData)}
</tbody>
</ReactBootStrap.Table>
</div>
</div>
</div>
)
);
}
}
export default TodayEpic;
\ No newline at end of file
import React, { Component } from 'react';
import './App.css';
import axios from 'axios';
import 'bootstrap/dist/css/bootstrap.min.css';
import * as ReactBootStrap from "react-bootstrap";
const renderChannelData = (data1, index) =>{
return(
<tr key = {index}>
<td>{data1.NUM}</td>
<td>{data1.channel_name} {data1.channel_number}</td>
<td>{data1.VALUE}</td>
</tr>
)
}
class WeekChannel extends Component{
constructor(props) {
super(props)
this.state = {
host : '',
myChannelData: [],
}
}
_getMostChannel = async() => {
const res = await axios.get('/api/week_most_channel');
this.setState({myChannelData : res.data})
}
_getHost = async() => {
const res = await axios.get('/api/host');
this.setState({ host : res.data.host })
}
componentDidMount() {
this._getHost();
this._getMostChannel();
}
render() {
return(
this.state.myChannelData.length === 0? (<div>로딩중입니다.</div>):(
<div>
<br></br>
<br></br>
<br></br>
<div className='Home'>
<div>
<div>
<br></br>
<h3>지난 1주일간 에픽이 가장 많이 나온 채널</h3>
</div>
</div>
</div>
<div>
<ReactBootStrap.Table striped bordered hover>
<thead>
<tr>
<th>순위</th>
<th>채널</th>
<th>나온 횟수</th>
</tr>
</thead>
<tbody>
{this.state.myChannelData.map(renderChannelData)}
</tbody>
</ReactBootStrap.Table>
</div>
</div>
)
);
}
}
export default WeekChannel;
\ No newline at end of file
import React, { Component } from 'react';
import './App.css';
import axios from 'axios';
import 'bootstrap/dist/css/bootstrap.min.css';
import * as ReactBootStrap from "react-bootstrap";
const renderEpicData = (data1, index) =>{
return(
<tr key = {index}>
<td>{data1.NUM}</td>
<td><img width="45%" src={`/images/${data1.PICTURE}.png`}></img></td>
<td>{data1.NAME}</td>
<td>{data1.VALUE}</td>
</tr>
)
}
class WeekEpic extends Component{
constructor(props) {
super(props)
this.state = {
host : '',
myEpicData: [],
}
}
_getMostEpic = async() => {
const res = await axios.get('/api/week_most_epic');
this.setState({myEpicData : res.data})
}
_getHost = async() => {
const res = await axios.get('/api/host');
this.setState({ host : res.data.host })
}
componentDidMount() {
this._getHost();
this._getMostEpic();
}
render() {
return(
this.state.myEpicData.length === 0? (<div>로딩중입니다.</div>):(
<div>
<br></br>
<br></br>
<br></br>
<div className='Home'>
<h3>지난 1주일간 가장 많이 나온 에픽 아이템</h3>
<div>
<ReactBootStrap.Table striped bordered hover>
<thead>
<tr>
<th>순위</th>
<th colSpan='2'>에픽 아이템</th>
<th>나온 횟수</th>
</tr>
</thead>
<tbody>
{this.state.myEpicData.map(renderEpicData)}
</tbody>
</ReactBootStrap.Table>
</div>
</div>
</div>
)
);
}
}
export default WeekEpic;
\ No newline at end of file
import React, { Component } from 'react';
import './App.css';
import axios from 'axios';
import 'bootstrap/dist/css/bootstrap.min.css';
import * as ReactBootStrap from "react-bootstrap";
const renderChannelData = (data1, index) =>{
return(
<tr key = {index}>
<td>{data1.NUM}</td>
<td>{data1.channel_name} {data1.channel_number}</td>
<td>{data1.VALUE}</td>
</tr>
)
}
const renderEpicData = (data1, index) =>{
return(
<tr key = {index}>
<td>{data1.NUM}</td>
<td><img src={`/images/${data1.PICTURE}.png`} width="80%"></img></td>
<td> {data1.NAME}</td>
<td>{data1.VALUE}</td>
</tr>
)
}
class Home extends Component{
constructor(props) {
super(props)
this.state = {
host : '',
myEpicData: [],
myChannelData: [],
screenWidth: 0, //보여지는 윈도우 가로길이
}
}
_getMostEpic = async() => {
const res = await axios.get('/api/home_most_epic');
console.log(res.data)
this.setState({myEpicData : res.data})
console.log(this.state.myEpicData)
}
_getMostChannel = async() => {
const res = await axios.get('/api/home_most_channel');
console.log(res.data)
this.setState({myChannelData : res.data})
console.log(this.state.myChannelData)
}
_getHost = async() => {
const res = await axios.get('/api/host');
console.log(res.data.host)
this.setState({ host : res.data.host })
}
_setWidth = ()=>{
this.setState({screenWidth: window.innerWidth})
}
componentDidMount() {
try{
this._getMostChannel()
this._getMostEpic()
this._setWidth()
}
catch(e)
{
console.log(e)
}
}
componentDidUpdate(){
}
render() {
return(
this.state.myEpicData.length === 0 || this.state.myChannelData.length === 0 ? (<div>로딩중입니다.</div>):(
<div>
<br></br>
<br></br>
<br></br>
<div className='Home' style={{textAilgn:"center"}}>
<div style={{width: "500px", marginLeft: `${(this.state.screenWidth-1040)/2}px`, marginRight: "20px",float : "left"}}>
<h3>오늘 가장 많이 나온 에픽 아이템</h3>
<div>
<ReactBootStrap.Table striped bordered hover>
<thead>
<tr>
<th>순위</th>
<th colSpan='2'>에픽 아이템</th>
<th>나온 횟수</th>
</tr>
</thead>
<tbody>
{this.state.myEpicData.map(renderEpicData)}
</tbody>
</ReactBootStrap.Table>
</div>
<div>
<br></br>
</div>
</div>
<div>
<div style={{width: "500px",marginLeft:"20px",display: "inline-block",float : "left"}}>
<h3>오늘 에픽이 가장 많이 나온 채널</h3>
<ReactBootStrap.Table striped bordered hover>
<thead>
<tr>
<th>순위</th>
<th>채널</th>
<th>나온 횟수</th>
</tr>
</thead>
<tbody>
{this.state.myChannelData.map(renderChannelData)}
</tbody>
</ReactBootStrap.Table>
</div>
</div>
</div>
</div>
)
);
}
}
export default Home;
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<React.StrictMode>
<App/>
</React.StrictMode>,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3">
<g fill="#61DAFB">
<path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/>
<circle cx="420.9" cy="296.5" r="45.7"/>
<path d="M520.5 78.1z"/>
</g>
</svg>
// This optional code is used to register a service worker.
// register() is not called by default.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.
// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://bit.ly/CRA-PWA
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.0/8 are considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export function register(config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://bit.ly/CRA-PWA'
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
}
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
);
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl, {
headers: { 'Service-Worker': 'script' },
})
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready
.then(registration => {
registration.unregister();
})
.catch(error => {
console.error(error.message);
});
}
}
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom/extend-expect';
import React, { Component } from 'react';
import {BootstrapTable,
TableHeaderColumn} from 'react-bootstrap-table';
import 'bootstrap/dist/css/bootstrap.min.css';
// import '../css/Table.css';
// import '../../node_modules/react-bootstrap-table/css/react-bootstrap-table.css'
class Table extends Component {
render(){
return (
<div className="Table">
<tr>
<td>{}
</td>
</tr>
</div>
);
}
}
export default Table;
\ No newline at end of file
This diff could not be displayed because it is too large.