Jeongmin Seo

Update version before last connection error

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