1 import { OpenAPIObject, TagObject } from "openapi3-ts"
2
3 export function mergeBaseIntoOAS(
4 targetOAS: OpenAPIObject,
5 sourceOAS: OpenAPIObject
6 ): void {
7 /**
8 * replace strategy for OpenAPIObject properties
9 */
10 targetOAS.openapi = sourceOAS.openapi ?? targetOAS.openapi
11 targetOAS.info = sourceOAS.info ?? targetOAS.info
12 targetOAS.servers = sourceOAS.servers ?? targetOAS.servers
13 targetOAS.security = sourceOAS.security ?? targetOAS.security
14 targetOAS.externalDocs = sourceOAS.externalDocs ?? targetOAS.externalDocs
15 targetOAS.webhooks = sourceOAS.webhooks ?? targetOAS.webhooks
16 /**
17 * merge + concat strategy for tags
18 */
19 const targetTags = targetOAS.tags ?? []
20 const sourceTags = sourceOAS.tags ?? []
21 const combinedTags: TagObject[] = []
22 const sourceIndexes: number[] = []
23 for (const targetTag of targetTags) {
24 for (const [sourceTagIndex, sourceTag] of sourceTags.entries()) {
25 if (targetTag.name === sourceTag.name) {
26 combinedTags.push(sourceTag)
27 sourceIndexes.push(sourceTagIndex)
28 continue
29 }
30 combinedTags.push(targetTag)
31 }
32 }
33 for (const [sourceTagIndex, sourceTag] of sourceTags.entries()) {
34 if (!sourceIndexes.includes(sourceTagIndex)) {
35 combinedTags.push(sourceTag)
36 }
37 }
38 targetOAS.tags = combinedTags
39 /**
40 * merge strategy for paths
41 */
42 targetOAS.paths = Object.assign(targetOAS.paths ?? {}, sourceOAS.paths ?? {})
43 /**
44 * merge strategy for components
45 */
46 if (!sourceOAS.components) {
47 return
48 }
49 if (!targetOAS.components) {
50 targetOAS.components = {}
51 }
52 for (const componentGroup of [
53 "callbacks",
54 "examples",
55 "headers",
56 "links",
57 "parameters",
58 "requestBodies",
59 "responses",
60 "schemas",
61 "securitySchemes",
62 ]) {
63 if (Object.keys(sourceOAS.components).includes(componentGroup)) {
64 targetOAS.components[componentGroup] = Object.assign(
65 targetOAS.components[componentGroup] ?? {},
66 sourceOAS.components[componentGroup]
67 )
68 }
69 }
70 }
71
72 export function mergePathsAndSchemasIntoOAS(
73 targetOAS: OpenAPIObject,
74 sourceOAS: OpenAPIObject
75 ): void {
76 /**
77 * merge paths
78 */
79 Object.assign(targetOAS.paths, sourceOAS.paths)
80
81 /**
82 * merge components.schemas
83 */
84 if (sourceOAS.components?.schemas) {
85 if (!targetOAS.components) {
86 targetOAS.components = {}
87 }
88 if (!targetOAS.components.schemas) {
89 targetOAS.components.schemas = {}
90 }
91 Object.assign(targetOAS.components.schemas, sourceOAS.components.schemas)
92 }
93 }