ORM: Sequelize: 오류
조회수 871회
작업환경은 NodeJS v8, KoaJS, SequelizeJS(MySQL)입니다.
우선 첫번째 와 같이 코드를 작성했습니다. .getUserByUserId()
는 아이디 중복체크하는 메서드입니다. 여기서 이미 중복돼서 생성된 아이디가 있다면 if
문을 통해 body
에 중복된 아이디가 있다고 반환합니다. 그리고 중복이 없다면 .addUser()
를 통해 새로운 계정을 생성하는 프로세스입니다.
하지만
.addUser()
가 없고, 아이디가 중복되었을때는success: false
를 반환합니다. 하지만 있으면body
에는 404에러와 함께 콘솔에는ValidationError
가 뜨더군요.- 다시 .
addUser()
를 넣고, 아이디가 중복되지 않았을때는success: true
가 잘 반환됩니다.
첫번째
exports.localJoin = async (ctx) => {
let body = ctx.request.body;
await userService.getUserByUserId(body.userId || '').then(exists => {
if (exists) {
ctx.body = { success: false, message: `${exists.dataValues.userId} is already registered.` };
}
});
let user = { userId: body.userId, firstName: body.firstName, lastName: body.lastName, password: bcrypt.hashSync(body.password, 10) };
await userService.addUser(user).then(() => {
ctx.body = { success: true, password: user.password };
});
};
이대론 안될 것 같아서 두번째 와 같은 코드로 변경했습니다.
두번째
exports.localJoin = async (ctx) => {
let body = ctx.request.body;
await userService.getUserByUserId(body.userId || '').then(exists => {
if (exists || '') {
ctx.body = { success: false, message: `${exists.dataValues.userId} is already registered.` };
} else {
let user = { userId: body.userId, firstName: body.firstName, lastName: body.lastName, password: bcrypt.hashSync(body.password, 10) };
return userService.addUser(user).then(() => {
ctx.body = { success: true };
});
}
});
};
잘 작동합니다. 여기서 궁금한 점이
else
안쪽에서는 왜return
이await
으로 변경이 안되는지 알고 싶습니다.- 두번째 와 같은 코드가 최선인가요?
-
(•́ ✖ •̀)
알 수 없는 사용자
1 답변
-
일단 작성하신
async - await
의 사용 방식의 문제인 듯하여 아래와 같이 수정하여 시도해 보시고 다시 질문해주세요.exports.localJoin = async (ctx) => { let body = ctx.request.body; let exists = await userService.getUserByUserId(body.userId || ''); if (exists) { ctx.body = { success: false, message: `${exists.dataValues.userId} is already registered.` }; } else { let user = { userId: body.userId, firstName: body.firstName, lastName: body.lastName, password: bcrypt.hashSync(body.password, 10) }; // I don't know about returns of the method `addUser`. // but it may work... let isAdded = await userService.addUser(user); if (isAdded) { ctx.body = { success: true, password: user.password }; } else { // exception handling... } } }
댓글 입력