TODO
ORM?과제코드 복습
Object Relational Mapping, 객체-관계 매핑
sequelize는 Node.js의 모듈로 sql작업을 쉽게 할 수 있도록 도와주는 ORM 라이브러리이다.
시퀄라이즈를 사용하면 자바스크립트 코드로 sql을 제어가능하다.
시퀄라이즈로 MySQL, MariaDB, PostgreSQL, SQLite, MSSQL 등 다양한 RDBMS와 호환된다.
// 유저 고유번호, 1day
const accessToken = jwt.sign(
{
userId: user.userId,
},
"sparta-secret-key",
{ expiresIn: "1d" }
);
// Access Token in Cookie
res.cookie("accessToken", accessToken);
return res
.status(200)
.json({ message: "로그인에 성공했습니다!", token: accessToken });
const { userId } = res.locals.user.dataValues;
=> 결과
//console.log(res.locals.user.dataValues)
{
userId: 2,
nickname: 'zzz',
password: '1234',
createdAt: 2022-12-25T12:48:22.000Z,
updatedAt: 2022-12-25T12:48:22.000Z
}
//테이블 조인
const posts = await Post.findAll({
include: [
{
model: User,
attributes: ["nickname"],
required: true,
},
],
});
=> 결과
//response
{
"postId": 6,
"title": "qwer",
"content": "qwer",
"likes": 0,
"createdAt": "2022-12-25T13:17:07.000Z",
"updatedAt": "2022-12-25T13:17:07.000Z",
"userId": 2,
"User": {
"nickname": "zzz"
}
const post = await Post.findOne({
where: { postId },
include: [
{
model: User,
attributes: ["nickname"],
require: true,
},
{
model: Comment,
attributes: ["comment", "createdAt"],
include: [
{
model: User,
attributes: ["nickname"],
},
],
},
],
});
=> 결과
//response
{
"post": {
"postId": 6,
"title": "qwer",
"content": "qwer",
"likes": 0,
"createdAt": "2022-12-25T13:17:07.000Z",
"updatedAt": "2022-12-25T13:17:07.000Z",
"userId": 2,
"User": {
"nickname": "zzz"
},
"Comments": []
}
}