Skip to content

Commit

Permalink
feat: add flag moveAllToComponents
Browse files Browse the repository at this point in the history
  • Loading branch information
aeworxet committed Apr 4, 2024
1 parent 8225cdd commit d81adbd
Show file tree
Hide file tree
Showing 5 changed files with 83 additions and 77 deletions.
37 changes: 13 additions & 24 deletions examples/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,32 +3,21 @@ const { Optimizer } = require('../lib/Optimizer')

// read input.yaml file synconously and store it as an string
const input = require('fs').readFileSync('./examples/input.yaml', 'utf8')
const optimizer = new Optimizer(input
, {
output: 'YAML',
rules: {
reuseComponents: true,
removeComponents: true,
moveAllToComponents: true,
moveDuplicatesToComponents: false,
schemas: false,
},
}
)
const optimizer = new Optimizer(input)
optimizer.getReport().then((report) => {
console.log(report)
const optimizedDocument = optimizer.getOptimizedDocument(
// {
// output: 'YAML',
// rules: {
// reuseComponents: true,
// removeComponents: true,
// moveAllToComponents: true,
// moveDuplicatesToComponents: false,
// schemas: false,
// },
// }
)
const optimizedDocument = optimizer.getOptimizedDocument({
output: 'YAML',
rules: {
reuseComponents: true,
removeComponents: true,
moveAllToComponents: true,
moveDuplicatesToComponents: false,
},
disableOptimizationFor: {
schema: true,
},
})
//store optimizedDocument as to output.yaml
require('fs').writeFileSync('./examples/output.yaml', optimizedDocument)
})
Expand Down
11 changes: 1 addition & 10 deletions src/ComponentProvider.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* eslint-disable @typescript-eslint/ban-ts-comment */
/* eslint-disable security/detect-object-injection */
import type { AsyncAPIDocumentInterface } from '@asyncapi/parser'
import { OptimizableComponentGroup, OptimizableComponent, Options } from 'index.d'
import { OptimizableComponentGroup, OptimizableComponent } from 'index.d'

import { JSONPath } from 'jsonpath-plus'
import _ from 'lodash'
Expand Down Expand Up @@ -54,7 +54,6 @@ export const parseComponentsFromPath = (

export const getOptimizableComponents = (
asyncAPIDocument: AsyncAPIDocumentInterface,
options?: Options
): OptimizableComponentGroup[] => {
const optimizeableComponents: OptimizableComponentGroup[] = []
const getAllComponents = (type: string) => {
Expand Down Expand Up @@ -84,14 +83,6 @@ export const getOptimizableComponents = (
operationBindings: getAllComponents('operationBindings'),
messageBindings: getAllComponents('messageBindings'),
}
// In the case of `if (!options?.rules?.schemas)`, if `schemas` property is
// simply absent in the `options` object, the program's behavior will not turn
// to default `schemas: true`, but the absence of `schemas` will be considered
// `schemas: false`, due to `undefined` being considered `false` in JS. Thus,
// explicit check is performed.
if (options?.rules?.schemas === false) {
delete optimizableComponents.schemas
}
for (const [type, components] of Object.entries(optimizableComponents)) {
if (components.length === 0) continue
optimizeableComponents.push({
Expand Down
20 changes: 13 additions & 7 deletions src/Optimizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,17 +45,16 @@ export class Optimizer {
/**
* @param {any} YAMLorJSON - YAML or JSON document that you want to optimize. You can pass Object, YAML or JSON version of your AsyncAPI document here.
*/
constructor(private YAMLorJSON: any, private options?: Options) {
constructor(private YAMLorJSON: any) {
this.outputObject = toJS(this.YAMLorJSON)
this.reporters = [
removeComponents,
reuseComponents,
moveAllToComponents,
moveDuplicatesToComponents,
]
this.options = options
}

/**
* @returns {Report} an object containing all of the optimizations that the library can do.
*
Expand All @@ -68,14 +67,15 @@ export class Optimizer {
console.error(parsedDocument.diagnostics)
throw new Error('Parsing failed.')
}
this.components = getOptimizableComponents(parsedDocument.document, this.options)
this.components = getOptimizableComponents(parsedDocument.document)
const rawReports = this.reporters.map((reporter) => reporter(this.components))
const reportsWithParents = rawReports.map((report) => ({
type: report.type,
elements: report.elements.filter((reportElement) =>
hasParent(reportElement, this.outputObject)
),
}))

const filteredReports = filterReportElements(reportsWithParents)
const sortedReports = filteredReports.map((report) => sortReportElements(report))
this.reports = sortedReports
Expand All @@ -90,7 +90,6 @@ export class Optimizer {
* @property {Boolean=} removeComponents - whether to remove un-used components from `components` section or not. Defaults to `true`.
* @property {Boolean=} moveAllToComponents - whether to move all AsyncAPI Specification-valid components to the `components` section or not.
* @property {Boolean=} moveDuplicatesToComponents - whether to move duplicated components to the `components` section or not. Defaults to `true`.
* @property {Boolean=} schemas - whether to add calculated `schemas` to the optimized AsyncAPI Document or not. Defaults to `true`.
*/

/**
Expand All @@ -112,17 +111,24 @@ export class Optimizer {
removeComponents: true,
moveAllToComponents: true,
moveDuplicatesToComponents: false, // there is no need to move duplicates if `moveAllToComponents` is `true`
schemas: true,
},
output: Output.YAML,
disableOptimizationFor: {
schema: false,
},
}
options = merge(defaultOptions, this.options)
options = merge(defaultOptions, options)
if (!this.reports) {
throw new Error(
'No report has been generated. please first generate a report by calling getReport method.'
)
}
for (const report of this.reports) {
if (options.disableOptimizationFor?.schema === true) {
report.elements = report.elements.filter(
(element) => !element.target?.includes('.schemas.')
)
}
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
if (options.rules[report.type] === true) {
Expand Down
6 changes: 5 additions & 1 deletion src/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,15 @@ interface Rules {
removeComponents?: boolean
moveAllToComponents?: boolean
moveDuplicatesToComponents?: boolean
schemas?: boolean
}

export interface DisableOptimizationFor {
schema?: boolean
}
export interface Options {
rules?: Rules
output?: Output
disableOptimizationFor?: DisableOptimizationFor // non-approved type
}

export interface IOptimizer {
Expand Down
86 changes: 51 additions & 35 deletions test/Optimizer.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,49 +4,65 @@ import { Output } from '../src/Optimizer'

describe('Optimizer', () => {
it('should produce the correct optimized file with YAML input.', async () => {
const optimizer = new Optimizer(inputYAML, {
output: Output.YAML,
rules: {
reuseComponents: true,
removeComponents: true,
moveAllToComponents: false,
moveDuplicatesToComponents: true,
schemas: true,
},
})
const optimizer = new Optimizer(inputYAML)
await optimizer.getReport()
expect(optimizer.getOptimizedDocument().trim()).toEqual(outputYAML.trim())
expect(
optimizer
.getOptimizedDocument({
output: Output.YAML,
rules: {
reuseComponents: true,
removeComponents: true,
moveAllToComponents: false,
moveDuplicatesToComponents: true,
},
disableOptimizationFor: {
schema: false,
},
})
.trim()
).toEqual(outputYAML.trim())
})

it('should produce the correct optimized file with JSON input.', async () => {
const optimizer = new Optimizer(inputJSON, {
output: Output.YAML,
rules: {
reuseComponents: true,
removeComponents: true,
moveAllToComponents: false,
moveDuplicatesToComponents: true,
schemas: true,
},
})
const optimizer = new Optimizer(inputJSON)
await optimizer.getReport()
expect(optimizer.getOptimizedDocument().trim()).toEqual(outputYAML.trim())
expect(
optimizer
.getOptimizedDocument({
output: Output.YAML,
rules: {
reuseComponents: true,
removeComponents: true,
moveAllToComponents: false,
moveDuplicatesToComponents: true,
},
disableOptimizationFor: {
schema: false,
},
})
.trim()
).toEqual(outputYAML.trim())
})

it('should produce the correct JSON output.', async () => {
const optimizer = new Optimizer(inputYAML, {
output: Output.JSON,
rules: {
reuseComponents: true,
removeComponents: true,
moveAllToComponents: false,
moveDuplicatesToComponents: true,
schemas: true,
},
})
const optimizer = new Optimizer(inputYAML)
await optimizer.getReport()
expect(optimizer.getOptimizedDocument({ output: Output.JSON }).trim()).toEqual(
outputJSON.trim()
)
expect(
optimizer
.getOptimizedDocument({
output: Output.JSON,
rules: {
reuseComponents: true,
removeComponents: true,
moveAllToComponents: false,
moveDuplicatesToComponents: true,
},
disableOptimizationFor: {
schema: false,
},
})
.trim()
).toEqual(outputJSON.trim())
})
})

0 comments on commit d81adbd

Please sign in to comment.