@@ -2,6 +2,7 @@ import { Inject, Logger } from '@nestjs/common';
22import { ITeamsRepository } from './teams.repository.interface' ;
33import { DATABASE_SERVICE , DatabaseService } from '@libs/database' ;
44import * as schema from '../entities' ;
5+ import { asc , count , eq , ilike , inArray } from 'drizzle-orm' ;
56
67export class TeamsRepository implements ITeamsRepository {
78 private logger = new Logger ( TeamsRepository . name ) ;
@@ -29,9 +30,30 @@ export class TeamsRepository implements ITeamsRepository {
2930 return [ ] ;
3031 } ;
3132
32- public findAllTags = async ( search ?: string ) => {
33- this . logger . log ( search ) ;
34- return [ ] ;
33+ public findAllTags = async ( options : { search ?: string ; limit ?: number ; offset ?: number } ) => {
34+ const cleanSearch = options . search ?. trim ( ) ;
35+ const escapedSearch = cleanSearch ?. replace ( / ( [ % _ \\ ] ) / g, '\\$1' ) ;
36+
37+ const whereCondition = escapedSearch
38+ ? ilike ( schema . tags . name , `%${ escapedSearch } %` )
39+ : undefined ;
40+
41+ const [ data , [ { total } ] ] = await Promise . all ( [
42+ this . db
43+ . select ( )
44+ . from ( schema . tags )
45+ . where ( whereCondition )
46+ . limit ( options . limit )
47+ . offset ( options . offset )
48+ . orderBy ( asc ( schema . tags . name ) ) ,
49+
50+ this . db . select ( { total : count ( ) } ) . from ( schema . tags ) . where ( whereCondition ) ,
51+ ] ) ;
52+
53+ return {
54+ data,
55+ total : Number ( total ?? 0 ) ,
56+ } ;
3557 } ;
3658
3759 public findBySlug = async ( slug : string ) => {
@@ -49,9 +71,30 @@ export class TeamsRepository implements ITeamsRepository {
4971 return Promise . resolve ( true ) ;
5072 } ;
5173
52- public syncTags = async ( teamId : string , tags : string [ ] ) => {
53- this . logger . log ( teamId , tags ) ;
54- return Promise . resolve ( true ) ;
74+ public syncTags = async ( teamId : string , tagNames : string [ ] ) => {
75+ await this . db . transaction ( async ( tx ) => {
76+ await tx . delete ( schema . teamsToTags ) . where ( eq ( schema . teamsToTags . teamId , teamId ) ) ;
77+
78+ if ( tagNames . length === 0 ) {
79+ return ;
80+ }
81+
82+ await tx
83+ . insert ( schema . tags )
84+ . values ( tagNames . map ( ( name ) => ( { name } ) ) )
85+ . onConflictDoNothing ( { target : schema . tags . name } ) ;
86+
87+ const existingTags = await tx
88+ . select ( { id : schema . tags . id } )
89+ . from ( schema . tags )
90+ . where ( inArray ( schema . tags . name , tagNames ) ) ;
91+
92+ await tx
93+ . insert ( schema . teamsToTags )
94+ . values ( existingTags . map ( ( tag ) => ( { teamId, tagId : tag . id } ) ) ) ;
95+ } ) ;
96+
97+ return true ;
5598 } ;
5699
57100 public update = async ( id : string , dto : Partial < schema . Team > ) => {
0 commit comments