과거 프로그래밍 자료들/프로젝트
req.user.id = undefined 일 때 조건(로그인/비로그인일 경우)
평부
2022. 9. 5. 15:22
* 상황 : Word의 값을 찾을 때 UserId값이 필요(SQL : select * from word from UserId = req.user.id)
* req.user.id값은 로그인 하지 않았을 경우 계속 undefined로 표시
* 로그인이 됬을 때만 req.user.id값으로 찾는 정보들이 표시되고 아닐 경우 Word 값 표시되지 않게 하기
const express = require("express");
const { isLoggedIn, isNotLoggedIn } = require("./middlewares");
const { Post, User, Hashtag, Word } = require("../../models");
const { Op, fn, col, literal } = require("sequelize");
const sequelize = require("sequelize");
const router = express.Router();
router.use((req, res, next) => {
//공통으로 쓰임
res.locals.user = req.user;
res.locals.followerCount = req.user ? req.user.Followers.length : 0;
res.locals.followingCount = req.user ? req.user.Followings.length : 0;
res.locals.followerIdList = req.user
? req.user.Followings.map((f) => f.id)
: [];
next();
});
//영단어
router.get("/index", async (req, res, next) => {
try {
if (req.user) { //이 부분을 조건으로 둠
const words = await Word.findAll({
include: {
model: User,
attributes: ["id", "nickname"],
},
order: [["createdAt", "DESC"]],
});
const wordsEasy = await Word.findAll({
include: {
model: User,
attributes: ["id"],
},
attributes: ["id", "english", "korean", "status", "UserId"],
where: {
[Op.or]: [{ status: "A" }, { status: "C" }],
type: "easy",
},
order: [["createdAt", "DESC"]],
});
const wordsMiddle = await Word.findAll({
include: {
model: User,
attributes: ["id"],
},
attributes: ["id", "english", "korean", "status", "UserId"],
where: {
[Op.or]: [{ status: "A" }, { status: "C" }],
type: "middle",
},
order: [["createdAt", "DESC"]],
});
const wordsAdvance = await Word.findAll({
include: {
model: User,
attributes: ["id"],
},
attributes: ["id", "english", "korean", "status", "UserId"],
where: {
[Op.or]: [{ status: "A" }, { status: "C" }],
type: "advance",
},
order: [["createdAt", "DESC"]],
});
const total = await Word.count({
include: {
model: User,
attributes: ["id"],
},
where: {
UserId: req.user.id,
},
});
const counting = await Word.count({
include: {
model: User,
attributes: ["id"],
},
where: {
status: "C",
UserId: req.user.id,
},
});
const deletedWord = await Word.findAll({
include: {
model: User,
attributes: ["id"],
},
attributes: ["id", "english", "korean", "type"],
where: {
status: "D",
},
order: [["createdAt", "DESC"]],
});
res.render("index", {
title: "engWord",
words: words,
wordsEasy: wordsEasy,
wordsMiddle: wordsMiddle,
wordsAdvance: wordsAdvance,
total: total,
counting: counting,
deletedWord: deletedWord,
});
} else {
const words = await Word.findAll({
include: {
model: User,
attributes: ["id", "nickname"],
},
order: [["createdAt", "DESC"]],
});
res.render("index", {
title: "engWord",
words: words,
});
}
} catch (error) {
console.error(error);
next(error);
}
});
* 참고
https://velog.io/@zero_mountain/Error-Log-passport-%EB%A1%9C%EA%B7%B8%EC%9D%B8-%EC%9C%A0%EC%A7%80