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 Mar 14, 2024
1 parent 29f5879 commit ad47136
Show file tree
Hide file tree
Showing 5 changed files with 76 additions and 26 deletions.
34 changes: 24 additions & 10 deletions examples/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,32 @@ 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)
const optimizer = new Optimizer(input, {
output: 'YAML',
rules: {
reuseComponents: true,
removeComponents: true,
moveAllToComponents: true,
moveDuplicatesToComponents: false,
schemas: false,
},
})
optimizer.getReport().then((report) => {
console.log(report)
const optimizedDocument = optimizer.getOptimizedDocument({
output: 'YAML',
rules: {
reuseComponents: true,
removeComponents: true,
moveAllToComponents: true,
moveDuplicatesToComponents: false,
},
})
const optimizedDocument = optimizer.getOptimizedDocument(
// {
// output: 'YAML',
// rules: {
// reuseComponents: true,
// removeComponents: true,
// moveAllToComponents: true,
// moveDuplicatesToComponents: false,
// schemas: false,
// },
// }
)
//store optimizedDocument as to output.yaml
require('fs').writeFileSync('./examples/output.yaml', optimizedDocument)
})

// , { rules: { schemas: false } }
21 changes: 13 additions & 8 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 } from 'index.d'
import { OptimizableComponentGroup, OptimizableComponent, Options } from 'index.d'

import { JSONPath } from 'jsonpath-plus'
import _ from 'lodash'
Expand Down Expand Up @@ -53,15 +53,16 @@ export const parseComponentsFromPath = (
}

export const getOptimizableComponents = (
asyncAPIDocument: AsyncAPIDocumentInterface
asyncAPIDocument: AsyncAPIDocumentInterface,
options?: Options
): OptimizableComponentGroup[] => {
const optimizeableComponents: OptimizableComponentGroup[] = []
const getAllComponents = (type: string) => {
// @ts-ignore
if (typeof asyncAPIDocument[type] !== 'function') return []
// @ts-ignore
return asyncAPIDocument[type]().all().concat(asyncAPIDocument.components()[type]().all());
};
return asyncAPIDocument[type]().all().concat(asyncAPIDocument.components()[type]().all())
}
const optimizableComponents = {
servers: getAllComponents('servers'),
messages: getAllComponents('messages'),
Expand All @@ -83,10 +84,14 @@ export const getOptimizableComponents = (
operationBindings: getAllComponents('operationBindings'),
messageBindings: getAllComponents('messageBindings'),
}
// to remove `schemas` from the optimized AsyncAPI Document, uncomment the next line
// delete optimizableComponents.schemas
// const options = { includeSchemas: true }
// !options.includeSchemas && delete optimizableComponents.schemas
// 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 absence of `schemas` will be considered
// `schemas: false`, due to `undefined` being considered `false`. 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
13 changes: 8 additions & 5 deletions src/Optimizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,14 +45,15 @@ 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) {
constructor(private YAMLorJSON: any, private options?: Options) {
this.outputObject = toJS(this.YAMLorJSON)
this.reporters = [
removeComponents,
reuseComponents,
moveAllToComponents,
moveDuplicatesToComponents,
]
this.options = options
}

/**
Expand All @@ -67,7 +68,7 @@ export class Optimizer {
console.error(parsedDocument.diagnostics)
throw new Error('Parsing failed.')
}
this.components = getOptimizableComponents(parsedDocument.document)
this.components = getOptimizableComponents(parsedDocument.document, this.options)
const rawReports = this.reporters.map((reporter) => reporter(this.components))
const reportsWithParents = rawReports.map((report) => ({
type: report.type,
Expand All @@ -89,6 +90,7 @@ 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. Defaults to `true`.
*/

/**
Expand All @@ -108,12 +110,13 @@ export class Optimizer {
rules: {
reuseComponents: true,
removeComponents: true,
moveAllToComponents: false,
moveDuplicatesToComponents: true, // there is no need to move duplicates if `moveAllToComponents` is true
moveAllToComponents: true,
moveDuplicatesToComponents: false, // there is no need to move duplicates if `moveAllToComponents` is `true`
schemas: true,
},
output: Output.YAML,
}
options = merge(defaultOptions, options)
options = merge(defaultOptions, this.options)
if (!this.reports) {
throw new Error(
'No report has been generated. please first generate a report by calling getReport method.'
Expand Down
1 change: 1 addition & 0 deletions src/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ interface Rules {
removeComponents?: boolean
moveAllToComponents?: boolean
moveDuplicatesToComponents?: boolean
schemas?: boolean
}
export interface Options {
rules?: Rules
Expand Down
33 changes: 30 additions & 3 deletions test/Optimizer.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,46 @@ import { Output } from '../src/Optimizer'

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

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

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

0 comments on commit ad47136

Please sign in to comment.