Skip to content

Instantly share code, notes, and snippets.

@kluu1
Last active March 19, 2020 04:03
Show Gist options
  • Select an option

  • Save kluu1/2028b22ca8cb2ced8f56cb0900f8b62c to your computer and use it in GitHub Desktop.

Select an option

Save kluu1/2028b22ca8cb2ced8f56cb0900f8b62c to your computer and use it in GitHub Desktop.
const Users = require('../models/users');
const resolvers = {
Query: {
getUsers: async (_, args) => {
// destrcture search, page, limit, and set default values
const { search = null, page = 1, limit = 20 } = args;
let searchQuery = {};
// run if search is provided
if (search) {
// update the search query
searchQuery = {
$or: [
{ firstName: { $regex: search, $options: 'i' } },
{ lastName: { $regex: search, $options: 'i' } },
{ userName: { $regex: search, $options: 'i' } },
{ email: { $regex: search, $options: 'i' } },
{ jobTitle: { $regex: search, $options: 'i' } }
]
};
}
// execute query to search users
const users = await Users.find(searchQuery)
.limit(limit)
.skip((page - 1) * limit)
.lean();
// get total documents
const count = await Users.countDocuments(searchQuery);
return {
users,
totalPages: Math.ceil(count / limit),
currentPage: page
}
}
}
};
module.exports = resolvers;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment