고병후

Connect database

1 +<회원 정보>
2 +CREATE TABLE tunnel.users(
3 +id INT NOT NULL AUTO_INCREMENT,
4 +name VARCHAR(30) NOT NULL,
5 +pw VARCHAR(30) NOT NULL,
6 +personality CHAR(4) NOT NULL,
7 +status TINYINT NOT NULL,
8 +PRIMARY KEY(id),
9 +UNIQUE INDEX name_UNIQUE (name ASC)
10 +)
11 +COMMENT = 'user information'
12 +DEFAULT CHARACTER SET = utf8
13 +ENGINE = InnoDB;
14 +
15 +<사용자 게시물>
16 +CREATE TABLE tunnel.posts(
17 +id INT NOT NULL AUTO_INCREMENT,
18 +userid VARCHAR(30) NOT NULL,
19 +post TEXT NOT NULL,
20 +created_at DATETIME NOT NULL DEFAULT now(),
21 +status TINYINT NOT NULL,
22 +PRIMARY KEY(id),
23 +INDEX userid_idx (userid ASC),
24 +CONSTRAINT commenter FOREIGN KEY (userid) REFERENCES tunnel.users (name)
25 +ON DELETE CASCADE
26 +ON UPDATE CASCADE)
27 +
28 +COMMENT = 'post information'
29 +DEFAULT CHARACTER SET = utf8
30 +ENGINE = InnoDB;
31 +
32 +<후 처리>
33 +ALTER TABLE tunnel.posts MODIFY post TEXT CHARACTER SET utf8mb4;
34 +:게시물에 이모지 사용가능하게 칼럼 수정.
35 +
36 +<댓글>
37 +CREATE TABLE tunnel.comments(
38 +id INT NOT NULL AUTO_INCREMENT,
39 +postid INT NOT NULL,
40 +userid VARCHAR(30) NOT NULL,
41 +created_at DATETIME NOT NULL DEFAULT now(),
42 +comment TEXT NOT NULL,
43 +PRIMARY KEY(id),
44 +INDEX postid_idx (postid ASC),
45 +CONSTRAINT post_id FOREIGN KEY (postid) REFERENCES tunnel.posts (id)
46 +ON DELETE CASCADE
47 +ON UPDATE CASCADE,
48 +CONSTRAINT user_id FOREIGN KEY (userid) REFERENCES tunnel.users (name)
49 +ON UPDATE CASCADE
50 +)
51 +
52 +COMMENT = 'post information'
53 +DEFAULT CHARACTER SET = utf8
54 +ENGINE = InnoDB;
55 +
56 +<후 처리>
57 +ALTER TABLE tunnel.comments MODIFY comment TEXT CHARACTER SET utf8mb4;
58 +: 댓글에 이모지 사용가능하게 칼럼 수정.
59 +
60 +
61 +
62 +<명령어>
63 +show databases;
64 +use tunnel;
65 +show tables;
66 +DESC tunnel.users ; #유저테이블 자세히 보기
67 +DROP TABLE tunnel.users; #유저테이블 지우기
...\ No newline at end of file ...\ No newline at end of file
1 +{
2 + "development": {
3 + "username": "root",
4 + "password": "tunnel",
5 + "database": "tunnel",
6 + "host": "127.0.0.1",
7 + "dialect": "mysql"
8 + },
9 + "test": {
10 + "username": "root",
11 + "password": null,
12 + "database": "database_test",
13 + "host": "127.0.0.1",
14 + "dialect": "mysql"
15 + },
16 + "production": {
17 + "username": "root",
18 + "password": "tunnel",
19 + "database": "tunnel",
20 + "host": "127.0.0.1",
21 + "dialect": "mysql"
22 + }
23 +}
1 +//mysql사용을 위한 sequelize 세팅 파일
2 +const Sequelize = require('sequelize');
3 +
4 +//table(모델)과 연결
5 +const User = require("./user.js");
6 +
7 +const env = process.env.NODE_ENV || 'development'; //개발버전
8 +const config = require('../config/config.json')[env];
9 +const db = {};
10 +
11 +const sequelize = new Sequelize(config.database, config.username, config.password, config);
12 +
13 +
14 +db.sequelize = sequelize;
15 +
16 +db.User = User;
17 +User.init(sequelize);
18 +User.associate(db);
19 +
20 +
21 +module.exports = db;
1 +const Sequelize = require('sequelize');
2 +
3 +module.exports = class User extends Sequelize.Model {
4 + static init(sequelize) {
5 + return super.init({
6 + name:{
7 + type: Sequelize.STRING(30),
8 + allowNull: false,
9 + unique:true,
10 + },
11 + pw:{
12 + type: Sequelize.STRING(30),
13 + allowNull: false,
14 + },
15 + personality:{
16 + type: Sequelize.CHAR(4),
17 + allowNull: false,
18 + },
19 + status:{
20 + type: Sequelize.BOOLEAN,
21 + allowNull: false,
22 + },
23 + },{
24 + sequelize,
25 + timestamps:false,
26 + underscored:false,
27 + modelName: 'User',
28 + tableName:'users',
29 + paranoid:false,
30 + charset:'utf8',
31 + collate:'utf8_general_ci',
32 + });
33 + }
34 +
35 +
36 + static associate(db) {}
37 +};
...\ No newline at end of file ...\ No newline at end of file
This diff is collapsed. Click to expand it.
...@@ -9,7 +9,10 @@ ...@@ -9,7 +9,10 @@
9 "dotenv": "^10.0.0", 9 "dotenv": "^10.0.0",
10 "express": "^4.17.1", 10 "express": "^4.17.1",
11 "express-session": "^1.17.2", 11 "express-session": "^1.17.2",
12 - "morgan": "^1.10.0" 12 + "morgan": "^1.10.0",
13 + "mysql2": "^2.3.3",
14 + "sequelize": "^6.12.0-beta.1",
15 + "sequelize-cli": "^6.3.0"
13 }, 16 },
14 "devDependencies": { 17 "devDependencies": {
15 "nodemon": "^2.0.15" 18 "nodemon": "^2.0.15"
......
...@@ -2,11 +2,21 @@ const express = require("express"); ...@@ -2,11 +2,21 @@ const express = require("express");
2 const bodyParser = require("body-parser"); 2 const bodyParser = require("body-parser");
3 const router = express.Router(); 3 const router = express.Router();
4 4
5 +/////////////
6 +const {User}=require('../models');
7 +//////////
8 +
5 router.get('/',(req,res)=>{ 9 router.get('/',(req,res)=>{
6 res.send('회원가입 페이지'); 10 res.send('회원가입 페이지');
7 }); 11 });
8 12
9 router.post('/',(req,res)=>{ 13 router.post('/',(req,res)=>{
14 + User.create({
15 + name: '고병후',
16 + pw:'1234',
17 + personality:'infj',
18 + status:0
19 + })
10 console.log(req.body); 20 console.log(req.body);
11 return res.json({a: "hi"}); 21 return res.json({a: "hi"});
12 }); 22 });
......
1 +// 사용 모듈 import
1 const express = require("express"); 2 const express = require("express");
2 const path = require("path"); 3 const path = require("path");
3 const morgan = require("morgan"); 4 const morgan = require("morgan");
...@@ -6,6 +7,8 @@ const session = require("express-session"); ...@@ -6,6 +7,8 @@ const session = require("express-session");
6 const dotenv = require("dotenv"); 7 const dotenv = require("dotenv");
7 const bodyParser = require("body-parser"); 8 const bodyParser = require("body-parser");
8 9
10 +const {sequelize}=require('./models/index.js');
11 +
9 dotenv.config(); 12 dotenv.config();
10 const indexRouter = require('./routes/index.js'); 13 const indexRouter = require('./routes/index.js');
11 const loginRouter = require('./routes/login.js'); 14 const loginRouter = require('./routes/login.js');
...@@ -15,6 +18,15 @@ const app = express(); ...@@ -15,6 +18,15 @@ const app = express();
15 app.set('port', process.env.PORT || 3001); 18 app.set('port', process.env.PORT || 3001);
16 const port = app.get('port'); 19 const port = app.get('port');
17 20
21 +//DB연결
22 +sequelize.sync({force: false})
23 +.then(()=>{
24 + console.log("DB연결 완료")
25 +})
26 +.catch((err)=>{
27 + console.log(err);
28 +});
29 +
18 //미들웨어 설정 30 //미들웨어 설정
19 app.use(morgan('dev')); 31 app.use(morgan('dev'));
20 app.use(express.json()); //json형식으로 데이터 전달 32 app.use(express.json()); //json형식으로 데이터 전달
...@@ -33,10 +45,6 @@ app.use(session({ ...@@ -33,10 +45,6 @@ app.use(session({
33 45
34 46
35 //라우팅 47 //라우팅
36 -//app.use('/',indexRouter);
37 -//app.use('/login',loginRouter);
38 -
39 -
40 app.use('/api/register',registerRouter); // 회원가입 페이지 48 app.use('/api/register',registerRouter); // 회원가입 페이지
41 app.use('/api/login',loginRouter); //로그인 페이지 49 app.use('/api/login',loginRouter); //로그인 페이지
42 50
...@@ -53,176 +61,3 @@ app.use((req,res,next)=>{ ...@@ -53,176 +61,3 @@ app.use((req,res,next)=>{
53 app.listen(port, ()=>{ 61 app.listen(port, ()=>{
54 console.log(port,"번 포트로 대기중"); 62 console.log(port,"번 포트로 대기중");
55 }); 63 });
...\ No newline at end of file ...\ No newline at end of file
56 -
57 -//라우팅
58 -
59 -/*
60 -//루트페이지
61 -app.get('/', (req,res)=>{
62 - res.sendFile(path.join(__dirname, '/fe/index.html'));
63 -});
64 -//로그인페이지
65 -app.get('/login', (req,res)=>{
66 - res.send("로그인페이지");
67 -});
68 -
69 -app.get('/register', (req,res)=>{
70 - res.send("회원가입 페이지");
71 -});
72 -
73 -*/
74 -
75 -
76 -
77 -
78 -
79 -/* 물어볼 부분
80 -app.use(session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }}));
81 -app.use(bodyParser.urlencoded({ extended: false }));
82 -app.use(bodyParser.json());
83 -*/
84 -
85 -/*
86 -var users = new Array();
87 -users[0] = {
88 - "userId" : 1,
89 - "name" : "Oh",
90 - "password" : "abc",
91 - "isAdmin" : true
92 -}
93 -users[1] = {
94 - "userId" : 1,
95 - "name" : "Jung",
96 - "password" : "abc",
97 - "isAdmin" : true
98 -}
99 -users[2] = {
100 - "userId" : 2,
101 - "name" : "Go",
102 - "password" : "abc",
103 - "isAdmin" : true
104 -}
105 -
106 -app.put('/login', function (req, res) {
107 - var count = 0;
108 - var Found = false;
109 -
110 - while(count < users.length) {
111 - if (req.body.userId == users[count].userId
112 - && req.body.password == users[count].password) {
113 - req.session.userId = users[count].userId;
114 - req.session.isAdmin = users[count].isAdmin;
115 - Found = true;
116 - break;
117 - }
118 - else {
119 - count++;
120 - }
121 - }
122 - if(Found) {
123 - res.send("Login");
124 - }
125 - else {
126 - res.send("Failed");
127 - }
128 -});
129 -
130 -app.put('/logout', function (req, res) {
131 - if (req.session.userId == req.body.userId) {
132 - req.session.userId = null;
133 - req.session.isAdmin = false;
134 - res.send("LogOut");
135 - }
136 - else {
137 - res.send("Failed");
138 - }
139 -});
140 -
141 -var auth = function (req, res, next) {
142 - if (req.session.userId != null
143 - && req.session.isAdmin == true)
144 - next();
145 - else
146 - res.send("Error");
147 -};
148 -
149 -app.get('/users/:userId', auth,function (req, res) {
150 - var inputId = req.params.userId;
151 - var count = 0;
152 - var Found = false;
153 - while(count < users.length) {
154 - if(inputId == users[count].userId){
155 - Found = true;
156 - res.send(users[count]);
157 - break;
158 - }
159 - else {
160 - count++;
161 - }
162 - }
163 -
164 - if (!Found) {
165 - res.send("Not Found");
166 - }
167 -});
168 -
169 -app.put('/users',auth,function(req, res){
170 - var inputId = req.body.userId;
171 - var count = 0;
172 - var Found = false;
173 -
174 - while (count < users.length) {
175 - if (inputId == users[count].userId) {
176 - Found = true;
177 - users[count] = req.body;
178 - res.send(users[count]);
179 - break;
180 - }
181 - else {
182 - count++;
183 - }
184 - }
185 -
186 - if(!Found) {
187 - res.send("Not Found");
188 - }
189 -
190 -});
191 -
192 -app.post('/users',auth,function(req, res){
193 - var inputData = {
194 - "userId" : req.body.userId,
195 - "name" : req.body.name,
196 - "password" : req.body.password,
197 - "isAdmin" : req.body.isAdmin
198 - }
199 - users.push(inputData);
200 - res.send(inputData);
201 -});
202 -
203 -app.delete('/users/:userId',auth,function(req, res){
204 - var inputId = req.params.userId;
205 - var count = 0;
206 - var Found = false;
207 - var removed;
208 -
209 - while (count < users.length) {
210 - if (inputId == users[count].userId) {
211 - Found = true;
212 - removed = users.splice(count,1);
213 - console.log(users.length);
214 - res.send(removed);
215 - break;
216 - }
217 - else {
218 - count++;
219 - }
220 - }
221 -
222 - if (!Found) {
223 - res.send("Not Found");
224 - }
225 -});
226 -*/
227 -
228 -//var server = app.listen(80);
...\ No newline at end of file ...\ No newline at end of file
......