From 609b51b8a40056be18cc2b7fe39674c1db463c48 Mon Sep 17 00:00:00 2001
From: Hugo SUBTIL <ext.sopra.husubtil@grandlyon.com>
Date: Mon, 23 Nov 2020 18:08:32 +0100
Subject: [PATCH] feat: add full text search

---
 src/structures/schemas/structure.schema.ts | 2 ++
 src/structures/structures.controller.ts    | 7 ++++++-
 src/structures/structures.service.ts       | 4 ++++
 3 files changed, 12 insertions(+), 1 deletion(-)

diff --git a/src/structures/schemas/structure.schema.ts b/src/structures/schemas/structure.schema.ts
index 254774be3..aaebe759f 100644
--- a/src/structures/schemas/structure.schema.ts
+++ b/src/structures/schemas/structure.schema.ts
@@ -161,3 +161,5 @@ export class Structure {
 }
 
 export const StructureSchema = SchemaFactory.createForClass(Structure);
+
+StructureSchema.index({ '$**': 'text' });
diff --git a/src/structures/structures.controller.ts b/src/structures/structures.controller.ts
index 462e4adf2..a60dea001 100644
--- a/src/structures/structures.controller.ts
+++ b/src/structures/structures.controller.ts
@@ -1,4 +1,4 @@
-import { Body, Controller, Get, Post } from '@nestjs/common';
+import { Body, Controller, Get, Param, Post } from '@nestjs/common';
 import { CreateStructureDto } from './dto/create-structure.dto';
 import { Structure } from './schemas/structure.schema';
 import { StructuresService } from './structures.service';
@@ -17,6 +17,11 @@ export class StructuresController {
     return this.structureService.findAll();
   }
 
+  @Get(':text')
+  async search(@Param('text') text: string): Promise<Structure[]> {
+    return this.structureService.search(text);
+  }
+
   @Get('count')
   async countCategories(): Promise<Array<{ id: string; count: number }>> {
     const data = await Promise.all([
diff --git a/src/structures/structures.service.ts b/src/structures/structures.service.ts
index 5526a29fb..bd3f4f968 100644
--- a/src/structures/structures.service.ts
+++ b/src/structures/structures.service.ts
@@ -13,6 +13,10 @@ export class StructuresService {
     return createdStructure.save();
   }
 
+  async search(searchString: string): Promise<Structure[]> {
+    return this.structureModel.find({ $text: { $search: searchString } }).exec();
+  }
+
   async findAll(): Promise<Structure[]> {
     return this.structureModel.find().exec();
   }
-- 
GitLab