redoc/src/services/models/Schema.ts

263 lines
6.9 KiB
TypeScript
Raw Normal View History

2018-01-22 21:30:53 +03:00
import { action, observable } from 'mobx';
2017-10-12 00:01:37 +03:00
import { OpenAPISchema, Referenced } from '../../types';
import { OpenAPIParser } from '../OpenAPIParser';
2017-11-21 14:24:41 +03:00
import { RedocNormalizedOptions } from '../RedocNormalizedOptions';
2018-01-22 21:30:53 +03:00
import { FieldModel } from './Field';
2017-11-21 14:24:41 +03:00
2018-01-22 21:30:53 +03:00
import { MergedOpenAPISchema } from '../';
2017-10-12 00:01:37 +03:00
import {
detectType,
humanizeConstraints,
isNamedDefinition,
isPrimitiveType,
JsonPointer,
} from '../../utils/';
// TODO: refactor this model, maybe use getters instead of copying all the values
export class SchemaModel {
_$ref: string;
type: string;
displayType: string;
typePrefix: string = '';
title: string;
description: string;
isPrimitive: boolean;
isCircular: boolean = false;
format?: string;
nullable: boolean;
deprecated: boolean;
pattern?: string;
example?: any;
enum: any[];
default?: any;
readOnly: boolean;
writeOnly: boolean;
2017-10-12 00:01:37 +03:00
constraints: string[];
fields?: FieldModel[];
items?: SchemaModel;
oneOf?: SchemaModel[];
oneOfType: string;
discriminatorProp: string;
@observable activeOneOf: number = 0;
rawSchema: OpenAPISchema;
schema: MergedOpenAPISchema;
/**
* @param isChild if schema discriminator Child
* When true forces dereferencing in allOfs even if circular
*/
constructor(
parser: OpenAPIParser,
2017-11-21 14:24:41 +03:00
schemaOrRef: Referenced<OpenAPISchema>,
$ref: string,
private options: RedocNormalizedOptions,
2017-10-12 00:01:37 +03:00
isChild: boolean = false,
) {
this._$ref = schemaOrRef.$ref || $ref || '';
this.rawSchema = parser.deref(schemaOrRef);
this.schema = parser.mergeAllOf(this.rawSchema, this._$ref, isChild);
this.init(parser, isChild);
parser.exitRef(schemaOrRef);
2018-01-22 21:30:53 +03:00
for (const parent$ref of this.schema.parentRefs || []) {
2017-10-12 00:01:37 +03:00
// exit all the refs visited during allOf traverse
2018-01-22 21:30:53 +03:00
parser.exitRef({ $ref: parent$ref });
2017-10-12 00:01:37 +03:00
}
}
/**
* Set specified alternative schema as active
* @param idx oneOf index
*/
@action
activateOneOf(idx: number) {
this.activeOneOf = idx;
}
init(parser: OpenAPIParser, isChild: boolean) {
const schema = this.schema;
this.isCircular = schema['x-circular-ref'];
this.title =
schema.title || (isNamedDefinition(this._$ref) && JsonPointer.baseName(this._$ref)) || '';
this.description = schema.description || '';
this.type = schema.type || detectType(schema);
this.format = schema.format;
this.nullable = !!schema.nullable;
this.enum = schema.enum || [];
this.example = schema.example;
this.deprecated = !!schema.deprecated;
this.pattern = schema.pattern;
this.constraints = humanizeConstraints(schema);
2017-12-07 20:12:34 +03:00
this.displayType = this.type;
2017-10-12 00:01:37 +03:00
this.isPrimitive = isPrimitiveType(schema);
this.default = schema.default;
this.readOnly = !!schema.readOnly;
this.writeOnly = !!schema.writeOnly;
2017-10-12 00:01:37 +03:00
if (this.isCircular) {
return;
}
if (!isChild && schema.discriminator !== undefined) {
this.initDiscriminator(schema, parser);
return;
}
if (schema.oneOf !== undefined) {
this.initOneOf(schema.oneOf, parser);
this.oneOfType = 'One of';
if (schema.anyOf !== undefined) {
console.warn(
`oneOf and anyOf are not supported on the same level. Skipping anyOf at ${this._$ref}`,
);
}
return;
}
if (schema.anyOf !== undefined) {
this.initOneOf(schema.anyOf, parser);
this.oneOfType = 'Any of';
return;
}
if (this.type === 'object') {
2017-11-21 14:24:41 +03:00
this.fields = buildFields(parser, schema, this._$ref, this.options);
2017-10-12 00:01:37 +03:00
} else if (this.type === 'array' && schema.items) {
2017-11-21 14:24:41 +03:00
this.items = new SchemaModel(parser, schema.items, this._$ref + '/items', this.options);
2017-10-12 00:01:37 +03:00
this.displayType = this.items.displayType;
this.typePrefix = this.items.typePrefix + 'Array of ';
this.isPrimitive = this.items.isPrimitive;
if (this.example === undefined && this.items.example !== undefined) {
this.example = [this.items.example];
}
2017-10-12 00:01:37 +03:00
if (this.items.isPrimitive) {
this.enum = this.items.enum;
}
}
}
private initOneOf(oneOf: OpenAPISchema[], parser: OpenAPIParser) {
this.oneOf = oneOf!.map(
(variant, idx) =>
new SchemaModel(
parser,
{
// merge base schema into each of oneOf's subschemas
allOf: [variant, { ...this.schema, oneOf: undefined, anyOf: undefined }],
} as OpenAPISchema,
this._$ref + '/oneOf/' + idx,
this.options,
),
2017-10-12 00:01:37 +03:00
);
this.displayType = this.oneOf.map(schema => schema.displayType).join(' or ');
}
private initDiscriminator(
schema: OpenAPISchema & {
namedParents?: string[];
},
parser: OpenAPIParser,
) {
this.discriminatorProp = schema.discriminator!.propertyName;
const derived = parser.findDerived([...(schema.namedParents || []), this._$ref]);
if (schema.oneOf) {
2018-01-22 21:30:53 +03:00
for (const variant of schema.oneOf) {
if (variant.$ref === undefined) {
continue;
}
2017-10-12 00:01:37 +03:00
const name = JsonPointer.dirName(variant.$ref);
derived[variant.$ref] = name;
}
}
const mapping = schema.discriminator!.mapping || {};
2018-01-22 21:30:53 +03:00
for (const name in mapping) {
2017-10-12 00:01:37 +03:00
derived[mapping[name]] = name;
}
const refs = Object.keys(derived);
this.oneOf = refs.map(ref => {
2018-01-22 21:30:53 +03:00
const innerSchema = new SchemaModel(parser, parser.byRef(ref)!, ref, this.options, true);
innerSchema.title = derived[ref];
return innerSchema;
2017-10-12 00:01:37 +03:00
});
}
}
2017-11-21 14:24:41 +03:00
function buildFields(
parser: OpenAPIParser,
schema: OpenAPISchema,
$ref: string,
options: RedocNormalizedOptions,
): FieldModel[] {
const props = schema.properties || {};
2017-10-12 00:01:37 +03:00
const additionalProps = schema.additionalProperties;
const defaults = schema.default || {};
const fields = Object.keys(props || []).map(fieldName => {
const required =
schema.required === undefined ? false : schema.required.indexOf(fieldName) > -1;
return new FieldModel(
parser,
{
name: fieldName,
required,
schema: {
...props[fieldName],
default: props[fieldName].default || defaults[fieldName],
},
},
$ref + '/properties/' + fieldName,
2017-11-21 14:24:41 +03:00
options,
2017-10-12 00:01:37 +03:00
);
});
2017-11-21 14:24:41 +03:00
if (options.requiredPropsFirst) {
sortFields(fields, schema.required);
}
2017-10-12 00:01:37 +03:00
if (typeof additionalProps === 'object') {
fields.push(
new FieldModel(
parser,
{
name: '[property name] *',
required: false,
schema: additionalProps,
},
$ref + '/additionalProperties',
2017-11-21 14:24:41 +03:00
options,
2017-10-12 00:01:37 +03:00
),
);
}
return fields;
}
2017-11-21 14:24:41 +03:00
function sortFields(fields: FieldModel[], order: string[] = []) {
fields.sort((a, b) => {
if (!a.required && b.required) {
return 1;
} else if (a.required && !b.required) {
return -1;
} else if (a.required && b.required) {
return order.indexOf(a.name) > order.indexOf(b.name) ? 1 : -1;
} else {
return 0;
}
});
}