@@ -28,6 +28,8 @@ import { REST_API_TYPE } from '../apitypes'
2828import {
2929 EXPORT_FORMAT_TO_FILE_FORMAT ,
3030 fromBase64 ,
31+ getDocumentTitle ,
32+ getFileExtension ,
3133 removeFirstSlash ,
3234 slugify ,
3335 takeIfDefined ,
@@ -39,6 +41,7 @@ import { VersionRestDocument } from '../apitypes/rest/rest.types'
3941import { INLINE_REFS_FLAG , NORMALIZE_OPTIONS } from '../consts'
4042import { normalize } from '@netcracker/qubership-apihub-api-unifier'
4143import { calculateSpecRefs , extractCommonPathItemProperties } from '../apitypes/rest/rest.operation'
44+ import { groupBy } from 'graphql/jsutils/groupBy'
4245
4346async function getTransformedDocument ( document : ResolvedDocument , format : FileFormat ) : Promise < VersionRestDocument > {
4447 const versionDocument = toVersionDocument ( document , format )
@@ -94,15 +97,36 @@ export class DocumentGroupStrategy implements BuilderStrategy {
9497 }
9598
9699 const transformedDocuments = await Promise . all ( transformTasks )
100+ const transformedDocumentsWithoutCollisions = ( [ 'fileId' , 'filename' ] as const ) . reduce ( resolveCollisionsByField , transformedDocuments )
97101
98- for ( const transformedDocument of transformedDocuments ) {
99- buildResult . documents . set ( transformedDocument . fileId , transformedDocument )
102+ for ( const document of transformedDocumentsWithoutCollisions ) {
103+ buildResult . documents . set ( document . fileId , document )
100104 }
101105
102106 return buildResult
103107 }
104108}
105109
110+ // there is a chance that the renamed document will be the same as another document (this case has not been fixed yet)
111+ function resolveCollisionsByField ( docs : VersionRestDocument [ ] , field : 'fileId' | 'filename' ) : VersionRestDocument [ ] {
112+ const fileIdMap = groupBy ( docs , ( document ) => document [ field ] )
113+ return ( [ ...fileIdMap . values ( ) ] as VersionRestDocument [ ] [ ] ) . reduce ( ( acc , docs ) => {
114+ const [ _ , ...duplicates ] = docs
115+ duplicates . forEach ( ( document , index ) => { document [ field ] = renameDuplicate ( document [ field ] , index ) } )
116+ return [ ...acc , ...docs ]
117+ } , [ ] as VersionRestDocument [ ] )
118+ }
119+
120+ function renameDuplicate ( fileName : string , index : number ) : string {
121+ const extension = getFileExtension ( fileName )
122+ const nameWithPostfix = `${ getDocumentTitle ( fileName ) } -${ index + 1 } `
123+
124+ if ( extension ) {
125+ return `${ nameWithPostfix } .${ extension } `
126+ }
127+ return nameWithPostfix
128+ }
129+
106130function parseBase64String ( value : string ) : object {
107131 return JSON . parse ( fromBase64 ( value ) )
108132}
0 commit comments