我有以下方法nestjs。
async findOne(userId: string) {
const user = await this.userRepository.find({userId});
if (user) {
throw new NotFoundException(`User does not exist`);
}
return user;
}
此方法回傳一個array of object. 如果在 DB 中找不到值,則回傳[{}]。empty array我的意思是當它回傳時我需要拋出例外[{}]。因為我需要在我寫的時候放入塊condition中,或者在塊中,在所有情況下它都不會進入ifuseruser==nulluser.length==oifif
我需要在if塊中進行哪些修改?
uj5u.com熱心網友回復:
我想知道為什么你實際上需要使用find方法。
您正在嘗試根據userIdusersRepository 獲取用戶,userId 不應該是唯一的嗎?
如果它是唯一的,那么您將得到一個如您所描述的空陣列或其中只有一個物件。不確定您使用的是什么資料庫,但無論如何,findOne方法應該在那里。
這適用于您的情況findOne應該可以解決問題
const user = await this.userRepository.findOne({ userId });
if (!user) throw new NotFoundException(`User does not exist`);
return user;
或者如果你必須使用find并且你想讓 if 陳述句更具可讀性,我建議使用Ramda、lodash或任何類似的庫來保持它更干凈。
使用 Ramda,您可以執行以下操作
const [firstUser = {}, ...others] = await this.userRepository.find({ userId });
if(R.isEmpty(firstUser)) throw new NotFoundException(`User does not exist`);
return [firstUser, ...others];
我高度假設基于的獲取資料userId只是一條記錄,所以我相信您可以像這樣使用
const [user = {}] = await this.userRepository.find({ userId });
if(R.isEmpty(user)) throw new NotFoundException(`User does not exist`);
return user;
uj5u.com熱心網友回復:
看起來您需要檢查是否user是一個長度 = 1 的陣列,其中第一個元素是一個空物件。你可以這樣做:
const user = await this.userRepository.find({ userId });
if (
!user ||
user.length === 0 ||
(user.length === 1 && Object.keys(user[0]).length === 0)
) {
throw new NotFoundException(`User does not exist`);
}
return user;
您將需要查看您的userRepositoy.find()函式以查看它是否可以回傳任何其他可能的值。根據您的描述,它要么回傳一個用戶陣列,要么回傳一個帶有單個空物件的陣列。但是,可能還有其他失敗情況,它回傳不同的東西。這部分由您決定,以確保您正確處理這些案件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/431568.html
標籤:javascript 数组 用户界面 开玩笑的 巢穴
上一篇:由于DefaultTableModelgetColumnClass覆寫,即使另行指定,JTable也會變得不透明
