UNPKG

boats

Version:

Beautiful Open / Async Template System - Write less yaml with BOATS and Nunjucks.

63 lines (62 loc) 2.14 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require("tslib"); const cloneObject_1 = tslib_1.__importDefault(require("./cloneObject")); const defaultOpenAPIOrder = [ 'tags', 'summary', 'description', 'operationId', 'security' ]; const defaultAsyncAPIChannelOrder = [ 'description', 'publish', 'subscribe' ]; class SortAttributes { forOpenAPI(bundled, pathAttrOrderMap = defaultOpenAPIOrder) { const obj = (0, cloneObject_1.default)(bundled); for (const path in obj.paths) { for (const verb in obj.paths[path]) { obj.paths[path][verb] = this.orderObjectAttributes(this.customSort(Object.keys(obj.paths[path][verb]), pathAttrOrderMap), obj.paths[path][verb]); } } return obj; } forAsyncAPI(bundled, channelAttrOrderMap = defaultAsyncAPIChannelOrder) { const obj = (0, cloneObject_1.default)(bundled); for (const channel in obj.channels) { obj.channels[channel] = this.orderObjectAttributes(this.customSort(Object.keys(obj.channels[channel]), channelAttrOrderMap), obj.channels[channel]); } return obj; } orderObjectAttributes(inputArray, inputObject) { if (!inputObject || typeof inputObject !== 'object') { return {}; } const orderedObject = {}; inputArray.forEach(attribute => { orderedObject[attribute] = inputObject[attribute]; }); return orderedObject; } customSort(input, map) { const sortedFinal = input.slice().sort(); const inputSet = new Set(input); const result = []; // Add elements in the "map" order given then add the remaining for (const item of map) { if (inputSet.has(item)) { result.push(item); } } for (const item of sortedFinal) { if (!result.includes(item) && inputSet.has(item)) { result.push(item); } } return result; } } exports.default = new SortAttributes();