I have below method in nestjs
.
async findOne(userId: string) {
const user = await this.userRepository.find({userId});
if (user) {
throw new NotFoundException(`User does not exist`);
}
return user;
}
this method retunrn an array of object
. if value not found in DB it return [{}]
.
I need to throw exception when it return empty array
I mean [{}]
. for that I need to put condition
in if
block
when I write user
, or user==null
or user.length==o
in if
block , in all the case it is not going inside the if
what modification I need to do in if
block?
CodePudding user response:
It looks like you need to check if user
is an array with length = 1 where the first element is an empty object. You can do something like this:
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;
You will need to look into your userRepositoy.find()
function to see if there are any other possible values it could return. From your description, it either returns an array of users or an array with a single empty object. However, there may be other failure cases where it returns something different. That part is up to you to make sure you handle those cases properly.
CodePudding user response:
I was wondering why you actually need to use find
method.
You are trying to get a user based on userId
in usersRepository, isn't userId supposed to be unique?
If it's unique then you are getting either an empty array as you described or with only one object in it. Not sure what DB you are using but in any case, findOne
method should be there.
It this applies to your case findOne
should do the trick
const user = await this.userRepository.findOne({ userId });
if (!user) throw new NotFoundException(`User does not exist`);
return user;
Or if you have to use find
and you want to make if statement more readable I suggest using Ramda, lodash or any similar library to keep it cleaner.
With Ramda you could do as following
const [firstUser = {}, ...others] = await this.userRepository.find({ userId });
if(R.isEmpty(firstUser)) throw new NotFoundException(`User does not exist`);
return [firstUser, ...others];
I highly assume that fetched data based on userId
is just one record so I believe you can use just like this
const [user = {}] = await this.userRepository.find({ userId });
if(R.isEmpty(user)) throw new NotFoundException(`User does not exist`);
return user;