Skip to content

Commit

Permalink
add filters
Browse files Browse the repository at this point in the history
  • Loading branch information
Prakharnagore committed Aug 24, 2024
1 parent e327646 commit ae79c0b
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 1 deletion.
23 changes: 22 additions & 1 deletion src/services/UserService.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Repository } from "typeorm";
import { Brackets, Repository } from "typeorm";
import { User } from "../entity/User";
import { LimitedUserData, UserData, UserQueryParams } from "../types";
import createHttpError from "http-errors";
Expand Down Expand Up @@ -84,11 +84,32 @@ export class UserService {
}
async getAll(validateQuery: UserQueryParams) {
const queryBuilder = this.userRepository.createQueryBuilder("user");

if (validateQuery.q) {
const searchTerm = `%${validateQuery.q}%`;
queryBuilder.where(
new Brackets((qb) => {
qb.where(
"CONCAT(user.firstName, ' ', user.lastName) ILike :q",
{ q: searchTerm },
).orWhere("user.email ILike :q", { q: searchTerm });
}),
);
}

if (validateQuery.role) {
queryBuilder.andWhere("user.role = :role", {
role: validateQuery.role,
});
}

const result = await queryBuilder
.skip((validateQuery.currentPage - 1) * validateQuery.perPage)
.take(validateQuery.perPage)
.orderBy("user.id", "DESC")
.getManyAndCount();

// console.log("Query", queryBuilder.getSql());
return result;
}

Expand Down
2 changes: 2 additions & 0 deletions src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,4 +56,6 @@ export interface UpdateUserRequest extends Request {
export interface UserQueryParams {
perPage: number;
currentPage: number;
q: string;
role: string;
}
15 changes: 15 additions & 0 deletions src/validators/list-users-validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,21 @@ import { checkSchema } from "express-validator";

export default checkSchema(
{
q: {
trim: true,
customSanitizer: {
options: (value: unknown) => {
return value ? value : "";
},
},
},
role: {
customSanitizer: {
options: (value: unknown) => {
return value ? value : "";
},
},
},
currentPage: {
customSanitizer: {
options: (value) => {
Expand Down

0 comments on commit ae79c0b

Please sign in to comment.