Skip to content

Commit

Permalink
feat: add tags enhancer
Browse files Browse the repository at this point in the history
add tags enhancer

Signed-off-by: Douglas McConnachie <[email protected]>
  • Loading branch information
dougal83 committed Jan 29, 2020
1 parent 5271b8c commit 933b0b2
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 0 deletions.
2 changes: 2 additions & 0 deletions packages/openapi-v3/src/enhancers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,6 @@ export * from './default-deprecate-schema.enhancer';
export * from './keys';
export * from './prune-schema.enhancer';
export * from './spec-enhancer.service';
export * from './tags-schema.enhancer';
export * from './types';

48 changes: 48 additions & 0 deletions packages/openapi-v3/src/enhancers/tags-schema.enhancer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import {bind} from '@loopback/core';
import {OperationObject} from 'openapi3-ts';
import {OpenApiSpec} from '../types';
import {asSpecEnhancer, OASEnhancer} from './types';

/**
* A spec enhancer to combine OperationObject Tags OpenApiSpec into spec.tags
*
*/
@bind(asSpecEnhancer)
export class TagsEnhancer implements OASEnhancer {
name = 'tags';

modifySpec(spec: OpenApiSpec): OpenApiSpec {
try {
return this.tagsConsolidate(spec);
} catch {
console.log('Tags Enhancer failed, returned original spec.');
return spec;
}
}

/**
* Combine OperationObject Tags OpenApiSpec into spec.tags
*
*/
private tagsConsolidate(spec: OpenApiSpec): OpenApiSpec {
Object.keys(spec.paths).forEach(path =>
Object.keys(spec.paths[path]).forEach(op => {
const OpObj = spec.paths[path][op] as OperationObject;
if (OpObj.tags) this.patchTags(OpObj.tags, spec);
}),
);

return spec;
}

// TODO(dougal83) desc. resolution
private patchTags(tags: Array<string>, spec: OpenApiSpec) {
if (!spec.tags) {
spec.tags = [];
}
tags.forEach(name => {
if (spec.tags!.findIndex(tag => tag.name === name) <= 0)
spec.tags!.push({name, description: ''});
});
}
}
3 changes: 3 additions & 0 deletions packages/rest/src/rest.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
OperationObject,
PruneEnhancer,
ServerObject,
TagsEnhancer,
} from '@loopback/openapi-v3';
import {AssertionError} from 'assert';
import cors from 'cors';
Expand Down Expand Up @@ -723,6 +724,8 @@ export class RestServer extends Context implements Server, HttpServerLike {
spec = consolidationEnhancer.modifySpec(spec);
const pruneEnhancer = new PruneEnhancer();
spec = pruneEnhancer.modifySpec(spec);
const tagsEnhancer = new TagsEnhancer();
spec = tagsEnhancer.modifySpec(spec);
const defaultDeprecateEnhancer = new DefaultDeprecateEnhancer();
spec = defaultDeprecateEnhancer.modifySpec(spec);

Expand Down

0 comments on commit 933b0b2

Please sign in to comment.