Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 | import { Injectable, Logger } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Model } from 'mongoose'; import { SearchProvider } from './search-provider.interface'; import { RecentSearch } from './schemas/recent-search.schema'; import { SavedSearch } from './schemas/saved-search.schema'; import { SearchAnalytics } from './schemas/search-analytics.schema'; import { User } from '../user/schemas/user.schema'; @Injectable() export class GlobalSearchService { private readonly logger = new Logger(GlobalSearchService.name); private readonly providers = new Map<string, SearchProvider>(); constructor( @InjectModel(RecentSearch.name) private readonly recentModel: Model<RecentSearch>, @InjectModel(SavedSearch.name) private readonly savedModel: Model<SavedSearch>, @InjectModel(SearchAnalytics.name) private readonly analyticsModel: Model<SearchAnalytics>, @InjectModel(User.name) private readonly userModel: Model<User>, ) { // Register User search provider automatically as a local fallback this.registerProvider({ entityType: 'User', search: async (query, filters, tenantId) => { const where: any = { tenantId }; if (query) { where.$or = [ { firstName: { $regex: query, $options: 'i' } }, { lastName: { $regex: query, $options: 'i' } }, { email: { $regex: query, $options: 'i' } }, ]; } const results = await this.userModel .find(where) .limit(20) .lean() .exec(); return results.map((r) => ({ id: (r as any)._id.toString(), title: `${r.firstName} ${r.lastName}`, subtitle: r.email, entityType: 'User', })); }, suggest: async (query, tenantId) => { const results = await this.userModel .find({ tenantId, $or: [ { firstName: { $regex: query, $options: 'i' } }, { email: { $regex: query, $options: 'i' } }, ], }) .limit(5) .lean() .exec(); return results.map((r) => `${r.firstName} ${r.lastName}`); }, }); } registerProvider(provider: SearchProvider) { this.providers.set(provider.entityType, provider); this.logger.log(`Registered search provider for: ${provider.entityType}`); } async search(params: { query: string; entityTypes?: string[]; tenantId: string; userId: string; filters?: any; page?: number; limit?: number; }): Promise<any> { const startTime = Date.now(); const limit = params.limit || 50; const entityTypes = params.entityTypes || Array.from(this.providers.keys()); const activeProviders = entityTypes .map((type) => this.providers.get(type)) .filter(Boolean) as SearchProvider[]; const searchPromises = activeProviders.map(async (provider) => { try { const results = await provider.search( params.query, params.filters || {}, params.tenantId, ); return { entityType: provider.entityType, results }; } catch (err) { this.logger.error( `Search failed for provider ${provider.entityType}`, err, ); return { entityType: provider.entityType, results: [] }; } }); const providerResults = await Promise.all(searchPromises); const grouped: any = {}; let totalCount = 0; for (const res of providerResults) { grouped[res.entityType] = res.results.slice(0, limit); totalCount += res.results.length; } const duration = Date.now() - startTime; // Async record analytics and recent query this.analyticsModel .create({ tenantId: params.tenantId, query: params.query, resultCount: totalCount, executionTimeMs: duration, }) .catch((err) => this.logger.error('Failed logging search analytics', err), ); if (params.query) { this.recentModel .create({ tenantId: params.tenantId, userId: params.userId, query: params.query, entityTypes, }) .catch((err) => this.logger.error('Failed saving recent search', err)); } return { grouped, meta: { query: params.query, executionTimeMs: duration, totalResults: totalCount, }, }; } async suggest(query: string, tenantId: string): Promise<string[]> { const promises = Array.from(this.providers.values()).map((provider) => provider.suggest(query, tenantId).catch(() => []), ); const suggestions = await Promise.all(promises); return Array.from(new Set(suggestions.flat())).slice(0, 10); } async getRecent(tenantId: string, userId: string): Promise<any[]> { return this.recentModel .find({ tenantId, userId }) .sort({ createdAt: -1 }) .limit(10) .lean() .exec(); } async clearRecent(tenantId: string, userId: string): Promise<any> { return this.recentModel.deleteMany({ tenantId, userId }).exec(); } async getSaved(tenantId: string, userId: string): Promise<any[]> { return this.savedModel.find({ tenantId, userId }).lean().exec(); } async saveSearch(params: { tenantId: string; userId: string; name: string; query: string; filters?: any; entityTypes?: string[]; }): Promise<any> { return this.savedModel.create(params); } async deleteSaved( id: string, tenantId: string, userId: string, ): Promise<any> { return this.savedModel.deleteOne({ _id: id, tenantId, userId }).exec(); } } |