I want to enforce uniqueness so I would like to see if there are any other emails and usernames that are similar to the one posted to this route. How do I do that through the repository, it keeps on asking about a filter which I see but cannot get my head around it.
@post('/users', {
responses: {
'200': {
description: 'User model instance',
content: {'application/json': {schema: {'x-ts-type': User}}},
},
},
})
async create(@requestBody() user: User): Promise<User> {
//check : User= await this.userRepository.create(user);
//@param.query.object('filter', getFilterSchemaFor(User)) filter?: Filter;
// var check:any=await this.userRepository.find(filter);
//filter: Filter;
var check: User = await this.userRepository.find({email:user.email});
var isNotPresent: boolean = true;
// check.forEach(function(val){
// });
// if(isNotPresent)
return await this.userRepository.create(user);
}
A Filter
object has the following properties that can be used to define a query and it's response:
where
: Used to define a query. In your case, you would like to find existing users with the same email and username as provided in the request body. fields
: To specify fields that you would like to include or exclude in the response of your query. Every object in the array returned by find()
will have only those fields which are set to true
in the fields
object. offset
, skip
, limit
and order
: Used for pagination.So, in your case, assuming a 'user' has an 'email' and an 'username', the filter object would look like the following:
const filter: Filter = {
where: {
'email': user.email,
'username': user.username
},
fields: {
email: true,
username: true
},
offset: 0,
limit: 10,
skip: 0,
order: [],
};
And your call to the repository method would look like the following:
var check: User = await this.userRepository.find(filter);
My first SO answer. Hope this helps.