Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: enhance user search functionality with multi-term support #2574

Merged
merged 2 commits into from
Dec 31, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 22 additions & 12 deletions nestjs/src/users/users.service.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { User } from '@entities/user';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { In, Repository } from 'typeorm';
import { Brackets, In, Repository } from 'typeorm';

@Injectable()
export class UsersService {
Expand Down Expand Up @@ -58,22 +58,32 @@ export class UsersService {
return result.join(' ');
}

public async searchUsers(query?: string) {
if (!query) {
public async searchUsers(reqQuery?: string) {
if (!reqQuery) {
return [];
}

const search = `${query.trim()}%`;
const search = `${reqQuery.trim()}%`;

// Search by full name, githubId, discord username
const userIds = await this.userRepository
.createQueryBuilder()
.where(`CONCAT("firstName", ' ', "lastName") ILIKE :search`, { search })
.orWhere('"githubId" ILIKE :search', { search })
.orWhere(`CAST(discord AS jsonb)->>'username' ILIKE :search`, { search })
.select(['id'])
.limit(20)
.getRawMany();
const searchTerms = search.split(' ');

const query = this.userRepository.createQueryBuilder().select(['id']).limit(20);

searchTerms.forEach((term, index) => {
query.andWhere(
new Brackets(qb => {
qb.where(`"firstName" ILIKE :searchText${index}`, { [`searchText${index}`]: `%${term}%` })
.orWhere(`"lastName" ILIKE :searchText${index}`, { [`searchText${index}`]: `%${term}%` })
.orWhere(`"githubId" ILIKE :searchText${index}`, { [`searchText${index}`]: `%${term}%` })
.orWhere(`CAST("discord" AS jsonb)->>'username' ILIKE :searchText${index}`, {
[`searchText${index}`]: `%${term}%`,
});
}),
);
});

const userIds = await query.getRawMany();

if (userIds.length === 0) {
return [];
Expand Down
Loading