https://loy124.tistory.com/374 <= 블로그를 참고하였음
1-1
npx sequelize model:generate --name User --attributes nickname:string,password:string,confirm:string
npx sequelize model:generate --name Post --attributes title:string,content:string
1-2
npx sequelize db:migrate
1-3
npx sequelize migration:generate --name fk-comment
'use strict';
/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up (queryInterface, Sequelize) {
await queryInterface.addColumn('Posts', 'user_id', {
type : Sequelize.INTEGER,
allowNull: false
})
await queryInterface.addConstraint('Posts', {
fields : ['user_id'],
type : 'foreign key',
name : 'users_posts_id_fk',
references : {
table : 'Users',
field : 'userId'
},
onDelete : 'cascade',
onUpdate : 'cascade'
})
},
async down (queryInterface, Sequelize) {
await queryInterface.removeColumn('Posts', 'user_id')
}
};
2-1. models/user.js
'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class User extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
models.User.hasMany(models.Post, {foreignKey : 'user_id'})
}
}
User.init({
userId : {
primaryKey : true,
type : DataTypes.INTEGER
},
nickname: DataTypes.STRING,
password: DataTypes.STRING,
confirm: DataTypes.STRING
}, {
sequelize,
modelName: 'User',
});
return User;
};
2-2. models/post.js
'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class Post extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
models.Post.belongsTo(models.User, {foreignKey : 'user_id'})
}
}
Post.init({
postId : {
primaryKey : true,
type : DataTypes.INTEGER
},
title: DataTypes.STRING,
content: DataTypes.STRING
}, {
sequelize,
modelName: 'Post',
});
return Post;
};
3-1. 로그인 검증 미들웨어
const jwt = require('jsonwebtoken')
const {User} = require('../models')
module.exports = async (req, res, next) => {
const { authorization } = req.headers;
const [authType, authToken] = (authorization || "").split(" ");
if(authType !== 'Bearer' || !authToken) return res.status(400).json({errMessage : '로그인 후 사용이 가능한 API입니다.'})
try {
const {userId} = jwt.verify(authToken, 'my-secrect-key')
const user = await User.findByPk(userId)
res.locals.user = user.dataValues
console.log(res.locals.user)
next()
} catch (err) {
return res.status(500).json({errorMessage : err})
}
}
3-2. 게시글 작성 라우츠 폴더
const express = require('express')
const router = express.Router()
const {Post} = require('../models')
const authMiddleware = require('../middlewares/auth-middleware.js')
// 게시글 작성
router.post('/posts', authMiddleware, async (req, res) => {
const {title , content} = req.body
const currentUser = res.locals.user
if(!title || !content) return res.status(400).json({errMessage : '값을 입력해주세요'})
try {
if(currentUser) {
await Post.create({title : title, content : content, user_id : currentUser.userId})
res.status(201).json({message : '게시글 작성에 성공하였습니다.'})
}
} catch (err) {
res.status(500).json({errorMessage : err})
}
})
module.exports = router