Jeongmin Seo

Update version before last connection error

...@@ -116,6 +116,3 @@ dist ...@@ -116,6 +116,3 @@ dist
116 .yarn/build-state.yml 116 .yarn/build-state.yml
117 .yarn/install-state.gz 117 .yarn/install-state.gz
118 .pnp.* 118 .pnp.*
...\ No newline at end of file ...\ No newline at end of file
119 -
120 -#db
121 -app/src/databases/*
...\ No newline at end of file ...\ No newline at end of file
......
...@@ -31,6 +31,8 @@ app.use(express.json()); ...@@ -31,6 +31,8 @@ app.use(express.json());
31 app.use(express.urlencoded({ extended: true })); 31 app.use(express.urlencoded({ extended: true }));
32 app.use(methodOverride()); 32 app.use(methodOverride());
33 app.use(cors()); 33 app.use(cors());
34 +// app.use("/restaurants", require("../app/src/routes/home/restaurant.route"));
35 +require("../app/src/routes/home/restaurant.route")(app);
34 36
35 app.use("/", home); //미들웨어 등록해주는 method 37 app.use("/", home); //미들웨어 등록해주는 method
36 logger.info(`${process.env.NODE_ENV} - API Server Start At Port ${port}`); 38 logger.info(`${process.env.NODE_ENV} - API Server Start At Port ${port}`);
......
1 -const mysql = require("mysql"); 1 +// const mysql = require("mysql");
2 const { logger } = require("./winston"); 2 const { logger } = require("./winston");
3 const mysql2 = require("mysql2/promise"); 3 const mysql2 = require("mysql2/promise");
4 4
5 - 5 +// const db = mysql.createConnection({
6 -const db = mysql.createConnection({ 6 +// host: process.env.DB_HOST,
7 - host: process.env.DB_HOST, 7 +// user: process.env.DB_USER,
8 - user: process.env.DB_USER, 8 +// password: process.env.DB_PASSWORD,
9 - password: process.env.DB_PASSWORD, 9 +// database: process.env.DB_DATABASE, //schema
10 - database: process.env.DB_DATABASE, //schema 10 +// });
11 -});
12 11
13 const pool = mysql2.createPool({ 12 const pool = mysql2.createPool({
14 host: process.env.DB_HOST, 13 host: process.env.DB_HOST,
15 user: process.env.DB_USER, 14 user: process.env.DB_USER,
16 password: process.env.DB_PASSWORD, 15 password: process.env.DB_PASSWORD,
17 database: process.env.DB_DATABASE, //schema 16 database: process.env.DB_DATABASE, //schema
17 + connectionLimit: 10000,
18 + multipleStatements: true,
18 }); 19 });
19 20
20 -const exampleNonTransaction = async (sql, params) => { 21 +// db.connect();
21 - try {
22 - const connection = await db.getConnection(async (conn) => conn);
23 - try {
24 - const [rows] = await connection.query(sql, params);
25 - connection.release();
26 - return rows;
27 - } catch (err) {
28 - logger.error(
29 - `example non transaction Query error\n: ${JSON.stringify(err)}`
30 - );
31 - connection.release();
32 - return false;
33 - }
34 - } catch (err) {
35 - logger.error(
36 - `example non transaction DB Connection error\n: ${JSON.stringify(err)}`
37 - );
38 - return false;
39 - }
40 - };
41 -
42 - const exampleTransaction = async (sql, params) => {
43 - try {
44 - const connection = await db.getConnection(async (conn) => conn);
45 - try {
46 - await connection.beginTransaction(); // START TRANSACTION
47 - const [rows] = await connection.query(sql, params);
48 - await connection.commit(); // COMMIT
49 - connection.release();
50 - return rows;
51 - } catch (err) {
52 - await connection.rollback(); // ROLLBACK
53 - connection.release();
54 - logger.error(`example transaction Query error\n: ${JSON.stringify(err)}`);
55 - return false;
56 - }
57 -} catch (err) {
58 - logger.error(
59 - `example transaction DB Connection error\n: ${JSON.stringify(err)}`
60 - );
61 - return false;
62 - }
63 - };
64 -
65 -db.connect();
66 22
67 module.exports = { 23 module.exports = {
68 - db,
69 pool: pool, 24 pool: pool,
70 -}
...\ No newline at end of file ...\ No newline at end of file
25 +};
26 +
27 +
...\ No newline at end of file ...\ No newline at end of file
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
2 //for DB manipulate 2 //for DB manipulate
3 const RestaurantStorage = require("./RestaurantStorage"); 3 const RestaurantStorage = require("./RestaurantStorage");
4 4
5 -const { pool } = require("../config/db"); 5 +const {pool} = require("../config/db");
6 const { logger } = require("../config/winston"); 6 const { logger } = require("../config/winston");
7 const jwt = require("jsonwebtoken"); 7 const jwt = require("jsonwebtoken");
8 8
......
1 'use strict'; 1 'use strict';
2 //for DB CRUD 2 //for DB CRUD
3 -const pool = require("../config/db"); 3 +// const db = require("../config/db");
4 +const { pool } = require("../config/db");
4 5
5 exports.selectRestaurants = async function (connection, category) { 6 exports.selectRestaurants = async function (connection, category) {
6 7
...@@ -16,5 +17,3 @@ exports.selectRestaurants = async function (connection, category) { ...@@ -16,5 +17,3 @@ exports.selectRestaurants = async function (connection, category) {
16 return rows; 17 return rows;
17 18
18 } 19 }
...\ No newline at end of file ...\ No newline at end of file
19 -
20 -
...\ No newline at end of file ...\ No newline at end of file
......
1 'use strict'; 1 'use strict';
2 - 2 +//for DB manipulate
3 const UserStorage = require("./UserStorage"); 3 const UserStorage = require("./UserStorage");
4 +const {pool} = require("../config/db");
5 +const { logger } = require("../config/winston");
6 +const jwt = require("jsonwebtoken");
4 7
5 class User { 8 class User {
6 constructor(body) { 9 constructor(body) {
...@@ -9,7 +12,11 @@ class User { ...@@ -9,7 +12,11 @@ class User {
9 12
10 async login() { 13 async login() {
11 const client = this.body; 14 const client = this.body;
12 - const {id, password} = await UserStorage.getUserInfo(client.id); 15 +
16 + try {
17 + const connection = await pool.getConnection(async (conn) => conn);
18 + try {
19 + const {id, password} = await UserStorage.getUserInfo(connection, client.id);
13 // console.log(id, password); 20 // console.log(id, password);
14 21
15 if (id) { 22 if (id) {
...@@ -19,19 +26,36 @@ class User { ...@@ -19,19 +26,36 @@ class User {
19 return { success : false, msg: "비밀번호가 틀렸습니다."}; 26 return { success : false, msg: "비밀번호가 틀렸습니다."};
20 } 27 }
21 return {success: false, msg: "존재하지 않는 아이디입니다."}; 28 return {success: false, msg: "존재하지 않는 아이디입니다."};
29 + } catch (err) {
30 + return {success: false, msg: err};
31 + } finally {
32 + connection.release();
33 + }
34 + } catch (err) {
35 + logger.error(`login DB Connection error\n: ${JSON.stringify(err)}`);
36 + return false;
37 + }
22 } 38 }
23 39
24 async register() { 40 async register() {
25 const client = this.body; 41 const client = this.body;
42 +
43 + try {
44 + const connection = await pool.getConnection(async (conn) => conn);
26 try { 45 try {
27 - const response = await UserStorage.save(client); 46 + const response = await UserStorage.save(connection, client);
28 // console.log(response); 47 // console.log(response);
29 return response; 48 return response;
30 } catch (err) { 49 } catch (err) {
31 50
32 return {success: false, msg : err}; 51 return {success: false, msg : err};
52 + } finally {
53 + connection.release();
54 + }
55 + } catch (err) {
56 + logger.error(`usersaving DB Connection error\n: ${JSON.stringify(err)}`);
57 + return false;
33 } 58 }
34 } 59 }
35 } 60 }
36 -
37 module.exports = User; 61 module.exports = User;
......
1 'use strict'; 1 'use strict';
2 -//파일시스템 이용해서 파일 접근 및 DB 관리 2 + //for DB CRUD
3 -const fs = require("fs").promises; 3 +const pool = require("../config/db");
4 4
5 class UserStorage { 5 class UserStorage {
6 - 6 + constructor(body) {
7 - static #getUserInfo(data, id) { 7 + this.body = body;
8 - const users = JSON.parse(data);
9 - const idx = users.id.indexOf(id);
10 - const userKeys = Object.keys(users); // [id, password, name]
11 - const userInfo = userKeys.reduce((newUser, info) => {
12 - newUser[info] = users[info][idx];
13 - return newUser;
14 - }, {});
15 - // console.log(userInfo);
16 - return userInfo;
17 - }
18 -
19 - static #getUsers(data, isAll, fields) {
20 - const users = JSON.parse(data);
21 - if (isAll) return users;
22 -
23 - const newUsers = fields.reduce((newUsers, field) => {
24 - if (users.hasOwnProperty(field)) {
25 - newUsers[field] = users[field];
26 } 8 }
27 - return newUsers; 9 + // static getUsers(isAll, ...fields) {}
28 - }, {}); 10 + static async getUserInfo(connection, id) {
29 - return newUsers; 11 + return new Promise((resolve, reject) => {
12 + const query = "SELECT * FROM users WHERE id = ?;";
13 + connection.query(query, [id], (err, data) => {
14 + if (err) reject(`${err}`);
15 + // console.log(data[0]);
16 + resolve(data[0]);
17 + });
18 + });
30 } 19 }
31 20
32 - static getUsers(isAll, ...fields) { 21 + static async save(connection, userInfo) {
33 - return fs 22 + return new Promise((resolve, reject) => {
34 - .readFile("./src/databases/users.json") 23 + const query = "INSERT INTO users(id, name, password) VALUES(?, ?, ?);";
35 - .then((data) => { 24 + connection.query(
36 - return this.#getUsers(data, isAll, fields); 25 + query,
37 - }) 26 + [userInfo.id, userInfo.name, userInfo.password],
38 - .catch((err) => console.error); 27 + (err, data) => {
28 + if (err) reject(`${err}`);
29 + // console.log(data[0]);
30 + resolve({ success: true});
39 } 31 }
40 - 32 + );
41 - static getUserInfo(id) { 33 + });
42 - return fs
43 - .readFile("./src/databases/users.json")
44 - .then((data) => {
45 - return this.#getUserInfo(data, id);
46 - })
47 - .catch((err) => console.error);
48 } 34 }
49 35
50 - static async save(userInfo) {
51 - const users = await this.getUsers(true);
52 - //id가 없으면 회원가입 가능
53 - if (users.id.includes(userInfo.id)) {
54 - throw "이미 존재하는 아이디입니다.";
55 - }
56 - users.id.push(userInfo.id);
57 - users.name.push(userInfo.name);
58 - users.password.push(userInfo.password);
59 - fs.writeFile("./src/databases/users.json", JSON.stringify(users));
60 - return { success: true};
61 - }
62 } 36 }
37 +// static getUserInfo(id) {
38 +// return new Promise((resolve, reject) => {
39 +// const query = "SELECT * FROM users WHERE id = ?;";
40 +// pool.query(query, [id], (err, data) => {
41 +// if (err) reject(`${err}`);
42 +// // console.log(data[0]);
43 +// resolve(data[0]);
44 +// });
45 +// });
46 +// }
63 47
64 module.exports = UserStorage; 48 module.exports = UserStorage;
...\ No newline at end of file ...\ No newline at end of file
......
...@@ -18,23 +18,41 @@ ...@@ -18,23 +18,41 @@
18 * 2. 데이터 준비하기(제목, 주소, 카테고리) 18 * 2. 데이터 준비하기(제목, 주소, 카테고리)
19 */ 19 */
20 20
21 - async function getDataSet(category) { 21 +const dataSet = [
22 - let qs = category; 22 + {
23 - if(!qs) { 23 + title: "희락돈까스",
24 - qs = ""; 24 + address: "서울 영등포구 양산로 210",
25 - } 25 + category: "양식",
26 - 26 + },
27 - const dataSet = await axios({ 27 + {
28 - method: "get", // http method 28 + title: "즉석우동짜장",
29 - url: `http://localhost:3000/restaurants?category=${qs}`, 29 + address: "서울 영등포구 대방천로 260",
30 - headers: {}, 30 + category: "한식",
31 - data: {}, 31 + },
32 - }); 32 + {
33 - 33 + title: "아카사카",
34 - return dataSet.data.result; 34 + address: "서울 서초구 서초대로74길 23",
35 - } 35 + category: "일식",
36 - 36 + }
37 - getDataSet(); 37 +];
38 +
39 +// async function getDataSet(category) {
40 +// let qs = category;
41 +// if(!qs) {
42 +// qs = "";
43 +// }
44 +
45 +// const dataSet = await axios({
46 +// method: "get", // http method
47 +// url: `http://localhost:3000/restaurants?category=${qs}`,
48 +// headers: {},
49 +// data: {},
50 +// });
51 +
52 +// return dataSet.data.result;
53 +// }
54 +
55 +// getDataSet();
38 56
39 /****************************************************************************** 57 /******************************************************************************
40 * 3. 여러개 마커찍기 58 * 3. 여러개 마커찍기
...@@ -176,14 +194,16 @@ ...@@ -176,14 +194,16 @@
176 } 194 }
177 } 195 }
178 196
179 - async function setting() {
180 - try {
181 - const dataSet = await getDataSet();
182 setMap(dataSet); 197 setMap(dataSet);
183 198
184 - } catch (error) { 199 +// async function setting() {
185 - console.error(error); 200 +// try {
186 - } 201 +// const dataSet = await getDataSet();
187 - } 202 +// setMap(dataSet);
203 +
204 +// } catch (error) {
205 +// console.error(error);
206 +// }
207 +// }
188 208
189 - setting();
...\ No newline at end of file ...\ No newline at end of file
209 +// setting();
...\ No newline at end of file ...\ No newline at end of file
......
1 "use strict"; 1 "use strict";
2 2
3 const User = require("../../models/User"); 3 const User = require("../../models/User");
4 -const Restaurant = require("../../models/Restaurant"); 4 +// const Restaurant = require("../../models/Restaurant");
5 5
6 const output = { 6 const output = {
7 hello: (req, res) => { 7 hello: (req, res) => {
......
...@@ -2,16 +2,15 @@ ...@@ -2,16 +2,15 @@
2 2
3 const express = require("express"); 3 const express = require("express");
4 const router = express.Router(); 4 const router = express.Router();
5 -// const index = require("../../controllers/indexController");
6 const jwtMiddleware = require("../../config/jwtMiddleware"); 5 const jwtMiddleware = require("../../config/jwtMiddleware");
7 -const Restaurant = require("../../models/Restaurant"); 6 +// const Restaurant = require("../../models/Restaurant");
8 7
9 const ctrl = require("./home.ctrl"); 8 const ctrl = require("./home.ctrl");
10 9
11 router.get("/", ctrl.output.hello); 10 router.get("/", ctrl.output.hello);
12 router.get("/login", ctrl.output.login); 11 router.get("/login", ctrl.output.login);
13 router.get("/register", ctrl.output.register); 12 router.get("/register", ctrl.output.register);
14 -router.get("/restaurants", Restaurant.readRestaurants); 13 +// router.get("/restaurants", Restaurant.restaurants);
15 // router.get("/restaurants", ctrl.output.restaurants); 14 // router.get("/restaurants", ctrl.output.restaurants);
16 15
17 router.post("/login", ctrl.process.login); 16 router.post("/login", ctrl.process.login);
......
1 +module.exports = function (app) {
2 + //controller갖고있는 모듈 생성
3 + const index = require("../../models/Restaurant");
4 + const jwtMiddleware = require("../../config/jwtMiddleware");
5 +
6 + // 식당 목록 조회
7 + app.get("/restaurants", index.readRestaurants);
8 + // const express = require("express");
9 + // const router = express.Router();
10 + // const ctrl = require("./home.ctrl");
11 +
12 + // router.get("/", ctrl.output.hello);
13 + // router.get("/login", ctrl.output.login);
14 + // router.get("/register", ctrl.output.register);
15 +
16 +
17 + // router.post("/login", ctrl.process.login);
18 + // router.post("/register", ctrl.process.register);
19 +
20 + // module.exports = router;
21 + };
22 +
...\ No newline at end of file ...\ No newline at end of file
...@@ -49,11 +49,11 @@ ...@@ -49,11 +49,11 @@
49 type="text/javascript" 49 type="text/javascript"
50 src="//dapi.kakao.com/v2/maps/sdk.js?appkey=e55f753363b95e27b799aa6286a6c398&libraries=services" 50 src="//dapi.kakao.com/v2/maps/sdk.js?appkey=e55f753363b95e27b799aa6286a6c398&libraries=services"
51 ></script> 51 ></script>
52 - <script 52 + <!-- <script
53 src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.0.0-alpha.1/axios.min.js" 53 src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.0.0-alpha.1/axios.min.js"
54 integrity="sha512-xIPqqrfvUAc/Cspuj7Bq0UtHNo/5qkdyngx6Vwt+tmbvTLDszzXM0G6c91LXmGrRx8KEPulT+AfOOez+TeVylg==" 54 integrity="sha512-xIPqqrfvUAc/Cspuj7Bq0UtHNo/5qkdyngx6Vwt+tmbvTLDszzXM0G6c91LXmGrRx8KEPulT+AfOOez+TeVylg=="
55 crossorigin="anonymous" 55 crossorigin="anonymous"
56 referrerpolicy="no-referrer" 56 referrerpolicy="no-referrer"
57 - ></script> 57 + ></script> -->
58 </body> 58 </body>
59 </html> 59 </html>
......