redoc/lib/services/schema-helper.service.ts

352 lines
12 KiB
TypeScript
Raw Normal View History

2016-06-22 21:17:48 +03:00
'use strict';
import { JsonPointer } from '../utils/JsonPointer';
import { SpecManager } from '../utils/SpecManager';
import {methods as swaggerMethods, keywordTypes} from '../utils/swagger-defs';
import { WarningsService } from './warnings.service';
2016-07-26 12:03:15 +03:00
import slugify from 'slugify';
2016-06-22 21:17:48 +03:00
interface PropertyPreprocessOptions {
childFor: string;
2016-06-30 16:42:36 +03:00
skipReadOnly?: boolean;
2016-06-22 21:17:48 +03:00
}
export interface MenuMethod {
active: boolean;
summary: string;
tag: string;
}
export interface MenuCategory {
name: string;
2016-07-26 12:03:15 +03:00
id: string;
active?: boolean;
methods?: Array<MenuMethod>;
description?: string;
empty?: string;
virtual?: boolean;
}
2016-06-22 21:17:48 +03:00
const injectors = {
notype: {
check: (propertySchema) => !propertySchema.type,
inject: (injectTo, propertySchema, pointer) => {
injectTo.type = SchemaHelper.detectType(propertySchema);
propertySchema.type = injectTo.type;
if (injectTo.type) {
let message = `No "type" specified at "${pointer}". Automatically detected: "${injectTo.type}"`;
WarningsService.warn(message);
}
}
},
2016-06-22 21:17:48 +03:00
general: {
check: () => true,
inject: (injectTo, propertySchema, pointer) => {
injectTo._pointer = propertySchema._pointer || pointer;
injectTo._displayType = propertySchema.type;
if (propertySchema.format) injectTo._displayFormat = `<${propertySchema.format}>`;
if (propertySchema.enum) {
injectTo.enum = propertySchema.enum.map((value) => {
return {val: value, type: typeof value};
});
if (propertySchema.enum && propertySchema.enum.length === 1) {
injectTo._enumItem = propertySchema.enum[0];
injectTo.enum = null;
}
2016-06-22 21:17:48 +03:00
}
}
},
discriminator: {
check: (propertySchema) => propertySchema.discriminator,
inject: (injectTo, propertySchema = injectTo, pointer) => {
injectTo._descendants = SpecManager.instance().findDerivedDefinitions(pointer);
injectTo.discriminator = propertySchema.discriminator;
}
},
2016-08-10 14:44:24 +03:00
simpleArray: {
2016-06-22 21:17:48 +03:00
check: (propertySchema) => {
2016-08-10 14:44:24 +03:00
return propertySchema.type === 'array' && !Array.isArray(propertySchema.items);
2016-06-22 21:17:48 +03:00
},
inject: (injectTo, propertySchema = injectTo, propPointer) => {
injectTo._isArray = true;
injectTo._pointer = propertySchema.items._pointer
|| JsonPointer.join(propertySchema._pointer || propPointer, ['items']);
SchemaHelper.runInjectors(injectTo, propertySchema.items, propPointer);
2016-08-10 15:22:42 +03:00
injectTo._widgetType = 'array';
2016-06-22 21:17:48 +03:00
}
},
2016-08-10 14:44:24 +03:00
tuple: {
check: (propertySchema) => {
return propertySchema.type === 'array' && Array.isArray(propertySchema.items);
},
inject: (injectTo, propertySchema = injectTo, propPointer) => {
injectTo._isTuple = true;
injectTo._displayType = '';
let itemsPtr = JsonPointer.join(propertySchema._pointer || propPointer, ['items']);
for (let i=0; i < propertySchema.items.length; i++) {
let itemSchema = propertySchema.items[i];
itemSchema._pointer = itemSchema._pointer || JsonPointer.join(itemsPtr, [i.toString()]);
}
2016-08-10 15:22:42 +03:00
injectTo._widgetType = 'tuple';
2016-08-10 14:44:24 +03:00
// SchemaHelper.runInjectors(injectTo, propertySchema.items, propPointer);
}
},
2016-06-22 21:17:48 +03:00
object: {
check: (propertySchema) => {
return propertySchema.type === 'object' && propertySchema.properties;
},
inject: (injectTo, propertySchema = injectTo) => {
let baseName = propertySchema._pointer && JsonPointer.baseName(propertySchema._pointer);
injectTo._displayType = propertySchema.title || baseName || 'object';
2016-08-10 15:22:42 +03:00
injectTo._widgetType = 'object';
2016-06-22 21:17:48 +03:00
}
},
noType: {
check: (propertySchema) => !propertySchema.type,
inject: (injectTo) => {
2016-08-10 15:22:42 +03:00
injectTo._displayType = '< anything >';
2016-06-22 21:17:48 +03:00
injectTo._displayTypeHint = 'This field may contain data of any type';
injectTo.isTrivial = true;
2016-08-10 15:22:42 +03:00
injectTo._widgetType = 'trivial';
2016-06-22 21:17:48 +03:00
}
},
simpleType: {
check: (propertySchema) => {
if (propertySchema.type === 'object') {
return (!propertySchema.properties || !Object.keys(propertySchema.properties).length)
&& (typeof propertySchema.additionalProperties !== 'object');
}
return (propertySchema.type !== 'array') && propertySchema.type;
},
inject: (injectTo, propertySchema = injectTo) => {
injectTo.isTrivial = true;
if (injectTo._pointer) {
injectTo._pointer = undefined;
injectTo._displayType = propertySchema.title ?
`${propertySchema.title} (${propertySchema.type})` : propertySchema.type;
}
2016-08-10 15:22:42 +03:00
injectTo._widgetType = 'trivial';
2016-06-22 21:17:48 +03:00
}
},
integer: {
check: (propertySchema) => (propertySchema.type === 'integer' || propertySchema.type === 'number'),
inject: (injectTo, propertySchema = injectTo) => {
var range = '';
if (propertySchema.minimum && propertySchema.maximum) {
range += propertySchema.exclusiveMinimum ? '( ' : '[ ';
range += propertySchema.minimum;
range += ' .. ';
range += propertySchema.maximum;
range += propertySchema.exclusiveMaximum ? ' )' : ' ]';
} else if (propertySchema.maximum) {
range += propertySchema.exclusiveMaximum? '< ' : '<= ';
range += propertySchema.maximum;
} else if (propertySchema.minimum) {
range += propertySchema.exclusiveMinimum ? '> ' : '>= ';
range += propertySchema.minimum;
}
if (range) {
injectTo._range = range;
}
}
},
string: {
check: propertySchema => (propertySchema.type === 'string'),
inject: (injectTo, propertySchema = injectTo) => {
var range;
if (propertySchema.minLength && propertySchema.maxLength) {
range = `[ ${propertySchema.minLength} .. ${propertySchema.maxLength} ]`;
} else if (propertySchema.maxLength) {
range = '<= ' + propertySchema.maxLength;
} else if (propertySchema.minimum) {
range = '>= ' + propertySchema.minLength;
}
if (range) {
injectTo._range = range + ' characters';
}
}
},
file: {
check: propertySchema => (propertySchema.type === 'file'),
inject: (injectTo, propertySchema = injectTo, propPointer, hostPointer) => {
injectTo.isFile = true;
let parentPtr;
if (propertySchema.in === 'formData') {
parentPtr = JsonPointer.dirName(hostPointer, 1);
} else {
parentPtr = JsonPointer.dirName(hostPointer, 3);
}
let parentParam = SpecManager.instance().byPointer(parentPtr);
let root = SpecManager.instance().schema;
injectTo._produces = parentParam && parentParam.produces || root.produces;
injectTo._consumes = parentParam && parentParam.consumes || root.consumes;
2016-08-10 15:22:42 +03:00
injectTo._widgetType = 'file';
2016-06-22 21:17:48 +03:00
}
}
};
export class SchemaHelper {
2016-06-25 13:02:13 +03:00
static preprocess(schema, pointer, hostPointer?) {
2016-06-22 21:17:48 +03:00
//propertySchema = Object.assign({}, propertySchema);
if (schema['x-redoc-schema-precompiled']) {
return schema;
}
SchemaHelper.runInjectors(schema, schema, pointer, hostPointer);
schema['x-redoc-schema-precompiled'] = true;
return schema;
}
static runInjectors(injectTo, schema, pointer, hostPointer?) {
for (var injName of Object.keys(injectors)) {
let injector = injectors[injName];
if (injector.check(schema)) {
injector.inject(injectTo, schema, pointer, hostPointer);
}
}
}
static preprocessProperties(schema:any, pointer:string, opts: PropertyPreprocessOptions) {
let requiredMap = {};
if (schema.required) {
schema.required.forEach(prop => requiredMap[prop] = true);
}
let discriminatorFieldIdx = -1;
let props = schema.properties && Object.keys(schema.properties).map((propName, idx) => {
2016-06-25 13:02:13 +03:00
let propertySchema = Object.assign({}, schema.properties[propName]);
2016-06-22 21:17:48 +03:00
let propPointer = propertySchema._pointer ||
JsonPointer.join(pointer, ['properties', propName]);
2016-06-25 13:02:13 +03:00
propertySchema = SchemaHelper.preprocess(propertySchema, propPointer);
propertySchema._name = propName;
2016-06-22 21:17:48 +03:00
// stop endless discriminator recursion
if (propertySchema._pointer === opts.childFor) {
propertySchema._pointer = null;
}
2016-06-25 13:02:13 +03:00
propertySchema._required = !!requiredMap[propName];
2016-06-22 21:17:48 +03:00
propertySchema.isDiscriminator = (schema.discriminator === propName);
if (propertySchema.isDiscriminator) {
discriminatorFieldIdx = idx;
}
return propertySchema;
});
props = props || [];
2016-06-29 22:29:05 +03:00
if (schema.additionalProperties && (typeof schema.additionalProperties === 'object')) {
2016-06-22 21:17:48 +03:00
let propsSchema = SchemaHelper.preprocessAdditionalProperties(schema, pointer);
propsSchema._additional = true;
props.push(propsSchema);
}
// Move discriminator field to the end of properties list
if (discriminatorFieldIdx > -1) {
let discrProp = props.splice(discriminatorFieldIdx, 1);
props.push(discrProp[0]);
}
// filter readOnly props for request schemas
if (opts.skipReadOnly) {
props = props.filter(prop => !prop.readOnly);
}
schema._properties = props;
}
static preprocessAdditionalProperties(schema:any, pointer:string) {
var addProps = schema.additionalProperties;
let ptr = addProps._pointer || JsonPointer.join(pointer, ['additionalProperties']);
2016-06-25 13:02:13 +03:00
let res = SchemaHelper.preprocess(addProps, ptr);
res._name = '<Additional Properties> *';
return res;
2016-06-22 21:17:48 +03:00
}
static unwrapArray(schema, pointer) {
var res = schema;
2016-08-10 14:44:24 +03:00
if (schema && schema.type === 'array' && !Array.isArray(schema.items)) {
2016-06-22 21:17:48 +03:00
let ptr = schema.items._pointer || JsonPointer.join(pointer, ['items']);
res = schema.items;
res._isArray = true;
res._pointer = ptr;
res = SchemaHelper.unwrapArray(res, ptr);
}
return res;
}
static methodSummary(method) {
return method.summary || method.operationId ||
(method.description && method.description.substring(0, 50)) || '<no description>';
}
static detectType(schema) {
let keywords = Object.keys(keywordTypes);
for (var i=0; i < keywords.length; i++) {
let keyword = keywords[i];
let type = keywordTypes[keyword];
if (schema[keyword]) {
return type;
}
}
}
static buildMenuTree(schema):Array<MenuCategory> {
let tag2MethodMapping = {};
for (let header of (<Array<string>>(schema.info && schema.info['x-redoc-markdown-headers'] || []))) {
2016-07-26 12:03:15 +03:00
let id = 'section/' + slugify(header);
tag2MethodMapping[id] = {
name: header, id: id, virtual: true, methods: []
};
}
for (let tag of schema.tags || []) {
2016-07-26 12:03:15 +03:00
let id = 'tag/' + slugify(tag.name);
tag2MethodMapping[id] = {
name: tag.name,
2016-07-26 12:03:15 +03:00
id: id,
description: tag.description,
headless: tag.name === '',
empty: !!tag['x-traitTag'],
methods: [],
};
}
let paths = schema.paths;
for (let path of Object.keys(paths)) {
let methods = Object.keys(paths[path]).filter((k) => swaggerMethods.has(k));
for (let method of methods) {
let methodInfo = paths[path][method];
let tags = methodInfo.tags;
if (!tags || !tags.length) {
tags = [''];
}
let methodPointer = JsonPointer.compile(['paths', path, method]);
let methodSummary = SchemaHelper.methodSummary(methodInfo);
for (let tag of tags) {
2016-07-26 12:03:15 +03:00
let id = 'tag/' + slugify(tag);
let tagDetails = tag2MethodMapping[id];
if (!tagDetails) {
tagDetails = {
name: tag,
2016-07-26 12:03:15 +03:00
id: id,
headless: tag === ''
};
2016-07-26 12:03:15 +03:00
tag2MethodMapping[id] = tagDetails;
}
if (tagDetails.empty) continue;
if (!tagDetails.methods) tagDetails.methods = [];
tagDetails.methods.push({
pointer: methodPointer,
summary: methodSummary,
operationId: methodInfo.operationId,
tag: tag
});
}
}
}
return Object.keys(tag2MethodMapping).map(tag => tag2MethodMapping[tag]);
}
2016-06-22 21:17:48 +03:00
}