@@ -39,6 +39,7 @@ import { VersionRestDocument } from '../apitypes/rest/rest.types'
3939import { INLINE_REFS_FLAG , NORMALIZE_OPTIONS } from '../consts'
4040import { normalize } from '@netcracker/qubership-apihub-api-unifier'
4141import { calculateSpecRefs , extractCommonPathItemProperties } from '../apitypes/rest/rest.operation'
42+ import { groupBy } from 'graphql/jsutils/groupBy'
4243
4344async function getTransformedDocument ( document : ResolvedDocument , format : FileFormat ) : Promise < VersionRestDocument > {
4445 const versionDocument = toVersionDocument ( document , format )
@@ -94,15 +95,37 @@ export class DocumentGroupStrategy implements BuilderStrategy {
9495 }
9596
9697 const transformedDocuments = await Promise . all ( transformTasks )
98+ const transformedDocumentsWithoutCollisions = ( [ 'fileId' , 'filename' ] as const ) . reduce ( resolveCollisions , transformedDocuments )
9799
98- for ( const transformedDocument of transformedDocuments ) {
99- buildResult . documents . set ( transformedDocument . fileId , transformedDocument )
100+ for ( const document of transformedDocumentsWithoutCollisions ) {
101+ buildResult . documents . set ( document . fileId , document )
100102 }
101103
102104 return buildResult
103105 }
104106}
105107
108+ // there is a chance that the renamed document will be the same as another document (this case has not been fixed yet)
109+ function resolveCollisions ( docs : VersionRestDocument [ ] , field : 'fileId' | 'filename' ) : VersionRestDocument [ ] {
110+ const fileIdMap = groupBy ( docs , ( document ) => document [ field ] )
111+ return ( [ ...fileIdMap . values ( ) ] as VersionRestDocument [ ] [ ] ) . reduce ( ( acc , docs ) => {
112+ const [ _ , ...rest ] = docs
113+ rest . forEach ( ( document , index ) => { document [ field ] = addPostfix ( ` ${ index + 1 } ` , document [ field ] ) } )
114+ return [ ...acc , ...docs ]
115+ } , [ ] as VersionRestDocument [ ] )
116+ }
117+
118+ function addPostfix ( postfix : string , fileName : string ) : string {
119+ const nameParts = fileName . split ( '.' )
120+ const extension = nameParts . length > 1 ? nameParts [ nameParts ?. length - 1 ] : ''
121+ const nameWithPostfix = `${ nameParts [ 0 ] } ${ postfix } `
122+
123+ if ( extension ) {
124+ return `${ nameWithPostfix } .${ extension } `
125+ }
126+ return nameWithPostfix
127+ }
128+
106129function parseBase64String ( value : string ) : object {
107130 return JSON . parse ( fromBase64 ( value ) )
108131}
0 commit comments