-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
288 lines (275 loc) · 10.1 KB
/
server.js
File metadata and controls
288 lines (275 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
import express from "express";
import bodyParser from "body-parser";
import { createConnection } from "mysql";
import broker from "./Mymojito/Mymojito.js";
import fs from "fs";
import {} from "./symbol_fetch/symbol_fetch.js";
const stock_1m_columns = [
"stck_bsop_date",
"stck_cntg_hour",
"stck_prpr",
"stck_oprc",
"stck_hgpr",
"stck_lwpr",
"cntg_vol",
"acml_tr_pbmn",
];
const css_list = [
fs.readFileSync("./css/title.css", "utf8"),
fs.readFileSync("./css/underbox.css", "utf8"),
];
/**미리읽은 css */
var css = "";
css_list.map((css_element) => {
css += `<style>${css_element}</style>`;
});
/**hhmmss */
var time_list = fs.readFileSync("./date.txt", "utf8").split(",");
const server = express();
const port = 3000;
//서버 3000번 사용
server.listen(port, (err) => {
if (err) return console.log(err);
console.log(`The server is listening on port ${port}`);
});
server.use(bodyParser.urlencoded({ extended: true }));
//html 템플릿 생성
var html = {
/** Dom부터 nav까지 */
top : `<!DOCTYPE html>
<html lang="en">
<head>
${css}
<title>Winter-Project</title>
<meta charset="UTF-8">
<script src="https://code.highcharts.com/highcharts.js"></script>
</head>
<body>
<!-- 제목과 검색창이있는 top태그 -->
<nav class="top">
<!-- 제목이 적혀있는 h1태그 -->
<a href="/" class="title__box__name">Stock File<br>Stockholm
<line class="title__line"></line>
</a>
<!-- 검색창이 있는 form태그 -->
<form class="title__search" method="post">
<input name="stock" type="text" placeholder="enter the stock name">
</form>
</nav>`,
bottom : `</body>
</html>`,
not_found_div : `<div class="underbox_not">없는 종목을 입력하였습니다.</div>`,
underbox : (stock_data,stock_info_data,stock_1m_data)=>{
return `
<underbox class="underbox">
<div class="underbox__main__index">
<div class="underbox_stock-name">${stock_data[0]}</div>
<div class="underbox_stock">
<span class="underbox_stock_price">${stock_data[1]}</span>
</div>
</div>
<div class="underbox__main__graph" id="container">
</div>
<div class="underbox_main_info">
<div class="underbox_stock_info" id="first_info">
<p class="stock_info_keys">전일대비 퍼센트</p>
<p class="stock_info_values">${stock_info_data[0]}</p>
</div>
<div class="underbox_stock_info">
<p class="stock_info_keys">주식 시가</p>
<p class="stock_info_values">${stock_info_data[1]}</p>
</div>
<div class="underbox_stock_info">
<p class="stock_info_keys">주식 최고가</p>
<p class="stock_info_values">${stock_info_data[2]}</p>
</div>
<div class="underbox_stock_info">
<p class="stock_info_keys">주식 최저가</p>
<p class="stock_info_values">${stock_info_data[3]}</p>
</div>
</div>
</underbox>
<script>Highcharts.chart('container', {
title:{
text : '${stock_data[0]} 분봉데이터'
},
chart: {
backgroundColor: '#FFFFFF',
type: 'line',
},
legend: {
enabled:false
},
xAxis: {
title : {
enabled : false
},
categories: [${time_list}],
},
yAxis: {
title : {
enabled : false
}
},
series: [{
name : '분봉데이터',
data: [${stock_1m_data}]
}]
});</script>`
},
/**홈페이지는 top, bottom을 반환한다. */
hompage: function(){
return `${this.top}${this.bottom}`;
},
/**
* @param {Array} stock_data [종목이름,종목현재가] 리스트
* @param {Array} stock_info_data 4가지 정보가 들어있는 리스트
* @param {Array} stock_1m_data 분봉데이터가 들어있는 리스트
*/
serch_page: function (
stock_data = [],
stock_info_data = [],
stock_1m_data = [])
{
return `${this.top}${this.underbox(stock_data,stock_info_data,stock_1m_data)}
${this.bottom}`;
},
/** 못찾았을때 */
not_found_page:function(){
return `${this.top}
${this.not_found_div}
${this.bottom}`
}
};
//초기 화면 불러오기
server.get("/", (req, res) => {
res.send(html.hompage());
});
// post로 검색창의 입력값 받아오기
server.post("/", (req, res) => {
/** 종목 한글명 */
const stock_kr_string = req.body.stock;
const conn = JSON.parse(fs.readFileSync("SoloData/SoloData.json"));
let connection = createConnection(conn); // DB 커넥션 생성
connection.connect((err) => {
if (err) console.log(err);
else console.log("Connected successfully");
});
/**입력정보로 종목코드를 뽑아오는 sql 명령문*/
var select_sql = `SELECT 단축코드 FROM stock WHERE 한글명="${stock_kr_string}";`;
connection.query(select_sql, function (err, respone) {
if (err) {
console.log(err);
console.log("SELECT 단축코드 FROM stock WHERE 한글명= 실패!!!");
} else {
//사용자가 없는 종목을 입력했을때 == select문의 결과가 빈배열일때
if (respone.length == 0) {
console.log(respone);
res.send(html.not_found_page());
} else {
/** 종목코드 */
const stock_code = respone[0]["단축코드"];
console.log(stock_code);
//검색한 종목의 정보를 데이터 베이스에 저장하기
broker
.fetch_price(stock_code)
.then(
/** @param {Object} stock_info fetch_price로 가져온 Object형 변수*/
function (stock_info) {
// 여러 사용자가 데이터를 입력할 때 한 테이블에 쓰면 충돌이 발생할 것이기 때문에
// 주식마다 주식정보, 분봉 테이블을 생성시킨다. 존재할 시 데이터 바로 입력
let create_sql = `CREATE TABLE ${stock_kr_string}정보 (
${Object.keys(stock_info).join(` VARCHAR(20),
`)} VARCHAR(20)
);`;
//테이블 생성
connection.query(create_sql, function (err, results) {
//만약 create문이 에러라면 테이블을 초기화(삭제)한다.
if (err) {
// 원래 테이블을 초기화 시키는 명령문
let del_sql = `DELETE FROM ${stock_kr_string}정보; `;
connection.query(del_sql, function (err, results) {
if (err) console.log(err);
else console.log("delete succesfully");
});
} else console.log("create table succesfully");
//테이블 생성,초기화 이후 데이터 저장
let insert_sql = `INSERT INTO ${stock_kr_string}정보 SET ?;`;
connection.query(
insert_sql,
stock_info,
function (err, results) {
if (err) console.log(err);
else console.log("save succesfully");
}
);
});
}
)
.then(() => {
//검색한 종목의 분봉데이터를 데이터 베이스에 저장하기
broker
.fetch_today_1m_ohlcv(stock_code)
.then(
/** @param {Array<Array<string>>} mindata 분봉데이터 2차원배열*/
function (mindata) {
let create_sql = `CREATE TABLE ${stock_kr_string}분봉 (
${stock_1m_columns.join(` VARCHAR(20),
`)} VARCHAR(20)
);`;
//테이블 생성
connection.query(create_sql, function (err, results) {
//create문이 에러라면 테이블 초기화
if (err) {
// 원래 테이블을 초기화 시키는 명령문
let del_sql = `DELETE FROM ${stock_kr_string}분봉; `;
connection.query(del_sql, function (err, results) {
if (err) console.log(err);
else console.log("delete succesfully");
});
} else console.log("create table succesfully");
//테이블 생성,초기화 이후 데이터 저장
var insert_sql = `INSERT INTO ${stock_kr_string}분봉 values ?;`;
//db에 데이터 저장
connection.query(
insert_sql,
[mindata],
function (err, results) {
if (err) console.log(err);
else console.log("save succesfully");
connection.end();
}
);
});
}
)
.then(() => {
var select_sql = `SELECT prdy_ctrt,stck_oprc,stck_hgpr,stck_lwpr FROM ${stock_kr_string}정보`;
connection.query(select_sql, function (err, respone) {
if (err) console.log(err);
else {
var stock_info_data = Object.values(respone[0]);
var select_sql = `SELECT stck_cntg_hour,stck_prpr FROM ${stock_kr_string}분봉 order by stck_cntg_hour`;
connection.query(select_sql, function (err, respone) {
if (err) console.log(err);
else {
var stock_1m_data = respone.map((element) => {
return Number(element.stck_prpr);
});
res.send(
html.serch_page(
[stock_kr_string, stock_1m_data.at(-1)],
stock_info_data,
stock_1m_data
)
);
}
});
}
});
});
});
}
}
});
});