Showing
10 changed files
with
156 additions
and
97 deletions
... | @@ -10,15 +10,13 @@ const compression = require("compression"); | ... | @@ -10,15 +10,13 @@ const compression = require("compression"); |
10 | const methodOverride = require("method-override"); | 10 | const methodOverride = require("method-override"); |
11 | var cors = require("cors"); | 11 | var cors = require("cors"); |
12 | const { logger } = require("./src/config/winston"); | 12 | const { logger } = require("./src/config/winston"); |
13 | - | 13 | +//app이라는 express 객체 생성 |
14 | const app = express(); | 14 | const app = express(); |
15 | //라우팅 | 15 | //라우팅 |
16 | const home = require("./src/routes/home"); | 16 | const home = require("./src/routes/home"); |
17 | 17 | ||
18 | const port = 3000; | 18 | const port = 3000; |
19 | 19 | ||
20 | -//controller갖고있는 모듈 생성 | ||
21 | -// const index = require("../controllers/indexController"); | ||
22 | const jwtMiddleware = require("./src/config/jwtMiddleware"); | 20 | const jwtMiddleware = require("./src/config/jwtMiddleware"); |
23 | 21 | ||
24 | // 앱 세팅 | 22 | // 앱 세팅 | ... | ... |
... | @@ -26,10 +26,12 @@ | ... | @@ -26,10 +26,12 @@ |
26 | "devDependencies": {}, | 26 | "devDependencies": {}, |
27 | "scripts": { | 27 | "scripts": { |
28 | "start": "nodemon ./bin/www.js", | 28 | "start": "nodemon ./bin/www.js", |
29 | - "test": "echo \"Error: no test specified\" && exit 1" | 29 | + "test": "echo \"Error: no test specified\" && exit 1", |
30 | + "dev": "NODE_ENV=development node index.js", | ||
31 | + "prod": "NODE_ENV=production node index.js" | ||
30 | }, | 32 | }, |
31 | - "author": "", | 33 | + "author": "Jeongmin Seo, Jumi Yang", |
32 | "license": "ISC", | 34 | "license": "ISC", |
33 | "keywords": [], | 35 | "keywords": [], |
34 | - "description": "" | 36 | + "description": "Node.js API Server" |
35 | } | 37 | } | ... | ... |
1 | const mysql = require("mysql"); | 1 | const mysql = require("mysql"); |
2 | +const { logger } = require("./winston"); | ||
3 | +const mysql2 = require("mysql2/promise"); | ||
4 | + | ||
2 | 5 | ||
3 | const db = mysql.createConnection({ | 6 | const db = mysql.createConnection({ |
4 | host: process.env.DB_HOST, | 7 | host: process.env.DB_HOST, |
... | @@ -7,6 +10,61 @@ const db = mysql.createConnection({ | ... | @@ -7,6 +10,61 @@ const db = mysql.createConnection({ |
7 | database: process.env.DB_DATABASE, //schema | 10 | database: process.env.DB_DATABASE, //schema |
8 | }); | 11 | }); |
9 | 12 | ||
10 | -db.connect(); | 13 | +const pool = mysql2.createPool({ |
14 | + host: process.env.DB_HOST, | ||
15 | + user: process.env.DB_USER, | ||
16 | + password: process.env.DB_PASSWORD, | ||
17 | + database: process.env.DB_DATABASE, //schema | ||
18 | +}); | ||
11 | 19 | ||
12 | -module.exports = db; | ||
... | \ No newline at end of file | ... | \ No newline at end of file |
20 | +const exampleNonTransaction = async (sql, params) => { | ||
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 | + | ||
67 | +module.exports = { | ||
68 | + db, | ||
69 | + pool: pool, | ||
70 | +} | ||
... | \ No newline at end of file | ... | \ No newline at end of file | ... | ... |
... | @@ -2,27 +2,16 @@ | ... | @@ -2,27 +2,16 @@ |
2 | //for DB manipulate | 2 | //for DB manipulate |
3 | const RestaurantStorage = require("./RestaurantStorage"); | 3 | const RestaurantStorage = require("./RestaurantStorage"); |
4 | 4 | ||
5 | -const { db } = 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 | -//controller가 db에 접근하기 위해 Dao folder | ||
9 | -//controller 실행하다가 db 접근해야하는 일 있을 때 Dao들어가서 query 실행하고 그 값을 반환 | ||
10 | -// const indexDao = require("../dao/indexDao"); | ||
11 | 8 | ||
12 | - | 9 | +exports.readRestaurants = async function (req,res) { |
13 | -class Restaurant { | ||
14 | - constructor(body) { | ||
15 | - this.body = body; | ||
16 | - } | ||
17 | -} | ||
18 | - | ||
19 | -// ex. 식당 테이블 조회 | ||
20 | -exports.readRestaurants = async function (req, res){ | ||
21 | const {category} = req.query; | 10 | const {category} = req.query; |
22 | 11 | ||
23 | if (category) { | 12 | if (category) { |
24 | const validCategory = ["한식", "중식", "일식", "양식", "분식", "구이", "회/초밥", "기타",]; | 13 | const validCategory = ["한식", "중식", "일식", "양식", "분식", "구이", "회/초밥", "기타",]; |
25 | - | 14 | + |
26 | if (!validCategory.includes(category)) { | 15 | if (!validCategory.includes(category)) { |
27 | return res.send({ | 16 | return res.send({ |
28 | isSuccess: false, | 17 | isSuccess: false, |
... | @@ -31,15 +20,14 @@ exports.readRestaurants = async function (req, res){ | ... | @@ -31,15 +20,14 @@ exports.readRestaurants = async function (req, res){ |
31 | }); | 20 | }); |
32 | } | 21 | } |
33 | } | 22 | } |
34 | - | 23 | + |
35 | try { | 24 | try { |
36 | const connection = await pool.getConnection(async (conn) => conn); | 25 | const connection = await pool.getConnection(async (conn) => conn); |
37 | try { | 26 | try { |
38 | //mysql접속 관련 부분 정의하는 함수 | 27 | //mysql접속 관련 부분 정의하는 함수 |
39 | //es6 비구조할당 | 28 | //es6 비구조할당 |
40 | - //indexDao에 selectRestaurants 정의해줘야 함. 그리고 거기서 query문. | 29 | + const [rows] = await RestaurantStorage.selectRestaurants(connection, category); |
41 | - const [rows] = await indexDao.selectRestaurants(connection, category); | 30 | + |
42 | - | ||
43 | return res.send({ | 31 | return res.send({ |
44 | result: rows, | 32 | result: rows, |
45 | isSuccess: true, | 33 | isSuccess: true, |
... | @@ -56,5 +44,4 @@ exports.readRestaurants = async function (req, res){ | ... | @@ -56,5 +44,4 @@ exports.readRestaurants = async function (req, res){ |
56 | logger.error(`readRestaurants DB Connection error\n: ${JSON.stringify(err)}`); | 44 | logger.error(`readRestaurants DB Connection error\n: ${JSON.stringify(err)}`); |
57 | return false; | 45 | return false; |
58 | } | 46 | } |
59 | - | ||
60 | } | 47 | } |
... | \ No newline at end of file | ... | \ No newline at end of file | ... | ... |
1 | 'use strict'; | 1 | 'use strict'; |
2 | //for DB CRUD | 2 | //for DB CRUD |
3 | -const db = require("../config/db"); | 3 | +const pool = require("../config/db"); |
4 | 4 | ||
5 | +exports.selectRestaurants = async function (connection, category) { | ||
5 | 6 | ||
6 | -// class RestaurantStorage { | 7 | + const selectAllRestaurantsQuery = `select title, address, category from restaurants where status='A';`; |
8 | + const selectCategorizedRestaurantsQuery = `select title, address, category from restaurants where status='A' and category=?;`; | ||
9 | + | ||
10 | + const Params = [category]; | ||
11 | + | ||
12 | + const Query = category ? selectCategorizedRestaurantsQuery : selectAllRestaurantsQuery; | ||
13 | + | ||
14 | + const rows = await connection.query(Query, Params); | ||
15 | + | ||
16 | + return rows; | ||
7 | 17 | ||
8 | -// static getRestaurantInfo(id) { | 18 | +} |
9 | -// return new Promise((resolve, reject) => { | ||
10 | -// const query = "SELECT * FROM users WHERE id = ?;"; | ||
11 | -// db.query(query, [id], (err, data) => { | ||
12 | -// if (err) reject(`${err}`); | ||
13 | -// // console.log(data[0]); | ||
14 | -// resolve(data[0]); | ||
15 | -// }); | ||
16 | -// }); | ||
17 | -// } | ||
18 | 19 | ||
19 | -// static async save(userInfo) { | ||
20 | -// return new Promise((resolve, reject) => { | ||
21 | -// const query = "INSERT INTO users(id, name, password) VALUES(?, ?, ?);"; | ||
22 | -// db.query( | ||
23 | -// query, | ||
24 | -// [userInfo.id, userInfo.name, userInfo.password], | ||
25 | -// (err, data) => { | ||
26 | -// if (err) reject(`${err}`); | ||
27 | -// // console.log(data[0]); | ||
28 | -// resolve({ success: true}); | ||
29 | -// } | ||
30 | -// ); | ||
31 | -// }); | ||
32 | -// } | ||
33 | -// } | ||
34 | - | ||
35 | -// module.exports = UserStorage; | ||
... | \ No newline at end of file | ... | \ No newline at end of file |
20 | + | ||
... | \ No newline at end of file | ... | \ No newline at end of file | ... | ... |
1 | 'use strict'; | 1 | 'use strict'; |
2 | -//for DB manipulate | 2 | + |
3 | const UserStorage = require("./UserStorage"); | 3 | const UserStorage = require("./UserStorage"); |
4 | 4 | ||
5 | class User { | 5 | class User { |
... | @@ -9,21 +9,16 @@ class User { | ... | @@ -9,21 +9,16 @@ class User { |
9 | 9 | ||
10 | async login() { | 10 | async login() { |
11 | const client = this.body; | 11 | const client = this.body; |
12 | - try { | 12 | + const {id, password} = await UserStorage.getUserInfo(client.id); |
13 | - | 13 | + // console.log(id, password); |
14 | - const {id, password} = await UserStorage.getUserInfo(client.id); | 14 | + |
15 | - // console.log(id, password); | 15 | + if (id) { |
16 | - | 16 | + if (id === client.id && password === client.password) { |
17 | - if (id) { | 17 | + return { success: true}; |
18 | - if (id === client.id && password === client.password) { | ||
19 | - return { success: true}; | ||
20 | - } | ||
21 | - return { success : false, msg: "비밀번호가 틀렸습니다."}; | ||
22 | } | 18 | } |
23 | - return {success: false, msg: "존재하지 않는 아이디입니다."}; | 19 | + return { success : false, msg: "비밀번호가 틀렸습니다."}; |
24 | - } catch (err) { | ||
25 | - return {success: false, msg: err}; | ||
26 | } | 20 | } |
21 | + return {success: false, msg: "존재하지 않는 아이디입니다."}; | ||
27 | } | 22 | } |
28 | 23 | ||
29 | async register() { | 24 | async register() { | ... | ... |
1 | 'use strict'; | 1 | 'use strict'; |
2 | -//for DB CRUD | 2 | +//파일시스템 이용해서 파일 접근 및 DB 관리 |
3 | -const db = require("../config/db"); | 3 | +const fs = require("fs").promises; |
4 | 4 | ||
5 | +class UserStorage { | ||
5 | 6 | ||
6 | -class UserStorage { | 7 | + static #getUserInfo(data, id) { |
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 | + } | ||
27 | + return newUsers; | ||
28 | + }, {}); | ||
29 | + return newUsers; | ||
30 | + } | ||
31 | + | ||
32 | + static getUsers(isAll, ...fields) { | ||
33 | + return fs | ||
34 | + .readFile("./src/databases/users.json") | ||
35 | + .then((data) => { | ||
36 | + return this.#getUsers(data, isAll, fields); | ||
37 | + }) | ||
38 | + .catch((err) => console.error); | ||
39 | + } | ||
7 | 40 | ||
8 | static getUserInfo(id) { | 41 | static getUserInfo(id) { |
9 | - return new Promise((resolve, reject) => { | 42 | + return fs |
10 | - const query = "SELECT * FROM users WHERE id = ?;"; | 43 | + .readFile("./src/databases/users.json") |
11 | - db.query(query, [id], (err, data) => { | 44 | + .then((data) => { |
12 | - if (err) reject(`${err}`); | 45 | + return this.#getUserInfo(data, id); |
13 | - // console.log(data[0]); | 46 | + }) |
14 | - resolve(data[0]); | 47 | + .catch((err) => console.error); |
15 | - }); | ||
16 | - }); | ||
17 | } | 48 | } |
18 | 49 | ||
19 | static async save(userInfo) { | 50 | static async save(userInfo) { |
20 | - return new Promise((resolve, reject) => { | 51 | + const users = await this.getUsers(true); |
21 | - const query = "INSERT INTO users(id, name, password) VALUES(?, ?, ?);"; | 52 | + //id가 없으면 회원가입 가능 |
22 | - db.query( | 53 | + if (users.id.includes(userInfo.id)) { |
23 | - query, | 54 | + throw "이미 존재하는 아이디입니다."; |
24 | - [userInfo.id, userInfo.name, userInfo.password], | 55 | + } |
25 | - (err, data) => { | 56 | + users.id.push(userInfo.id); |
26 | - if (err) reject(`${err}`); | 57 | + users.name.push(userInfo.name); |
27 | - // console.log(data[0]); | 58 | + users.password.push(userInfo.password); |
28 | - resolve({ success: true}); | 59 | + fs.writeFile("./src/databases/users.json", JSON.stringify(users)); |
29 | - } | 60 | + return { success: true}; |
30 | - ); | ||
31 | - }); | ||
32 | } | 61 | } |
33 | } | 62 | } |
34 | 63 | ... | ... |
... | @@ -16,9 +16,9 @@ const output = { | ... | @@ -16,9 +16,9 @@ const output = { |
16 | res.render("home/register"); | 16 | res.render("home/register"); |
17 | }, | 17 | }, |
18 | 18 | ||
19 | - restaurants: (req, res) => { | 19 | + // restaurants: (req, res) => { |
20 | - res.render("home/restaurants"); | 20 | + // res.render("home/restaurants"); |
21 | - } | 21 | + // } |
22 | }; | 22 | }; |
23 | 23 | ||
24 | const process = { | 24 | const process = { | ... | ... |
... | @@ -3,13 +3,16 @@ | ... | @@ -3,13 +3,16 @@ |
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"); | 5 | // const index = require("../../controllers/indexController"); |
6 | +const jwtMiddleware = require("../../config/jwtMiddleware"); | ||
7 | +const Restaurant = require("../../models/Restaurant"); | ||
6 | 8 | ||
7 | const ctrl = require("./home.ctrl"); | 9 | const ctrl = require("./home.ctrl"); |
8 | 10 | ||
9 | router.get("/", ctrl.output.hello); | 11 | router.get("/", ctrl.output.hello); |
10 | router.get("/login", ctrl.output.login); | 12 | router.get("/login", ctrl.output.login); |
11 | router.get("/register", ctrl.output.register); | 13 | router.get("/register", ctrl.output.register); |
12 | -router.get("/restaurants", ctrl.output.restaurants); | 14 | +router.get("/restaurants", Restaurant.readRestaurants); |
15 | +// router.get("/restaurants", ctrl.output.restaurants); | ||
13 | 16 | ||
14 | router.post("/login", ctrl.process.login); | 17 | router.post("/login", ctrl.process.login); |
15 | router.post("/register", ctrl.process.register); | 18 | router.post("/register", ctrl.process.register); | ... | ... |
-
Please register or login to post a comment