mediatype is properly picked and stuff like uuid in uri is also properly handlled,

This commit is contained in:
Harjeet Singh 2018-07-06 10:59:31 -07:00
parent 07ad2ccecf
commit b1dc621212
8 changed files with 84 additions and 23 deletions

View File

@ -22,13 +22,16 @@ const big = window.location.search.indexOf('big') > -1;
const swagger = window.location.search.indexOf('swagger') > -1; // compatibility mode ?
let specUrl = swagger ? 'swagger.yaml' : big ? 'big-openapi.json' : 'openapi.yaml';
// specUrl = 'intent.json';
specUrl = 'intent.json';
// specUrl = 'swagger.yaml';
specUrl = 'petstore.json';
// specUrl = 'petstore.json';
let store;
const options: RedocRawOptions = { nativeScrollbars: false, enableConsole: true, providedByName: 'Intent ApiDocs by Nutanix', providedByUri: 'http://www.nutanix.com' };
const headers = {
'x-nutanix-client': 'ui',
};
const options: RedocRawOptions = { nativeScrollbars: false, enableConsole: true, providedByName: 'Intent ApiDocs by Nutanix', providedByUri: 'http://www.nutanix.com', additionalHeaders: headers };
async function init() {
const spec = await loadAndBundleSpec(specUrl);

View File

@ -2,7 +2,7 @@ import { observer } from 'mobx-react';
import * as React from 'react';
import { SendButton } from '../../common-elements/buttons';
import { ConsoleActionsRow } from '../../common-elements/panels';
import { OperationModel } from '../../services/models';
import { FieldModel, OperationModel } from '../../services/models';
import { OpenAPISchema } from '../../types';
import { PayloadSamples } from '../PayloadSamples/PayloadSamples';
import { SourceCodeWithCopy } from '../SourceCode/SourceCode';
@ -12,6 +12,9 @@ const qs = require('qs');
export interface ConsoleViewerProps {
operation: OperationModel;
additionalHeaders?: object;
queryParamPrefix?: string;
queryParamSuffix?: string;
}
export interface ConsoleViewerState {
@ -26,6 +29,7 @@ export interface Schema {
@observer
export class ConsoleViewer extends React.Component<ConsoleViewerProps, ConsoleViewerState> {
operation: OperationModel;
additionalHeaders: object;
visited = new Set();
private consoleEditor: ConsoleEditor;
@ -39,46 +43,77 @@ export class ConsoleViewer extends React.Component<ConsoleViewerProps, ConsoleVi
const ace = this.consoleEditor && this.consoleEditor.editor;
// const value = ace && ace.editor &&
const schema = this.getSchema();
const { operation } = this.props;
const { operation, additionalHeaders = {} } = this.props;
// console.log('Schema: ' + JSON.stringify(schema, null, 2));
let value = ace && ace.editor.getValue();
const ref = schema && schema._$ref;
// var valid = window && window.ajv.validate({ $ref: `specs.json${ref}` }, value);
// console.log(JSON.stringify(window.ajv.errors));
// if (!valid) {
// console.warn('INVALID REQUEST!');
// }
const content = operation.requestBody && operation.requestBody.content;
const mediaType = content && content.mediaTypes[content.activeMimeIdx];
const endpoint = {
method: operation.httpVerb,
path: operation.servers[0].url + operation.path,
};
console.log('Value: ' + value);
// console.log('Value: ' + value);
if (value) {
value = JSON.parse(value);
}
const contentType = mediaType && mediaType.name || 'application/json';
const contentTypeHeader = { 'Content-Type': contentType };
const headers = { ...additionalHeaders, ...contentTypeHeader };
let result;
try {
result = await this.invoke(endpoint, value, headers);
this.setState({
result,
});
} catch (error) {
this.setState({
result: error,
});
}
};
const result = await this.invoke(endpoint, value);
console.log('Result: ' + JSON.stringify(result));
this.setState({
result,
});
/*
* If we have a url like foo/bar/{uuid} uuid will be replaced with what user has typed in.
*/
addParamsToUrl(url: string, params: Array<FieldModel>) {
const queryParamPrefix = '{';
const queryParamSuffix = '}';
for (const fieldModel of params) {
console.log(fieldModel.name + ' ' + url);
console.log(fieldModel.$value);
if (url.indexOf(`${queryParamPrefix}${fieldModel.name}${queryParamSuffix}`) > -1 && fieldModel.$value.length > 0) {
url = url.replace(`${queryParamPrefix}${fieldModel.name}${queryParamSuffix}`, fieldModel.$value);
}
}
if (url.split(queryParamPrefix).length > 1) {
console.error('** we have missing query params ** ', url);
throw Error(`** we have missing query params ** ${url}`);
}
return url;
};
async invoke(endpoint, body) {
const headers = { 'Content-Type': 'application/json' };
async invoke(endpoint, body, headers = {}) {
try {
let url = endpoint.path;
const { operation } = this.props;
let url = this.addParamsToUrl(endpoint.path, operation.parameters || []);
if (endpoint.method.toLocaleLowerCase() === 'get') {
url = url + '?' + qs.stringify(body || '');
}
const myHeaders = new Headers();
myHeaders.append('Content-Type', 'application/json');
for (const [key, value] of Object.entries(headers)) {
myHeaders.append(key, `${value}`);
}
const request = new Request(url, {
method: endpoint.method,

View File

@ -41,6 +41,9 @@ export class Endpoint extends React.Component<EndpointProps, EndpointState> {
const { operation, inverted, hideHostname } = this.props;
const { expanded } = this.state;
if (operation && operation.parameters && operation.parameters.length > 0) {
console.log('USER INPUT VALUE:: ' + operation.parameters[0]['$value']);
}
// TODO: highlight server variables, e.g. https://{user}.test.com
return (
<OptionsContext.Consumer>

View File

@ -30,6 +30,12 @@ export class Field extends React.PureComponent<FieldProps> {
toggle = () => {
this.props.field.toggle();
};
onFieldChange = (e) => {
console.log('Textfield value is ' + e.target.placeholder + ' - ' + e.target.value);
this.props.field.setValue(e.target.value);
};
render() {
const { className, field, isLast } = this.props;
const { name, expanded, deprecated, required, kind } = field;
@ -63,7 +69,7 @@ export class Field extends React.PureComponent<FieldProps> {
<FieldDetails {...this.props} />
</PropertyDetailsCell>
{field && field.in === 'path' &&
<td><TextField placeholder="foo" /></td>
<td><TextField placeholder={field.name} onChange={this.onFieldChange} /></td>
}
</tr>
{field.expanded &&

View File

@ -100,7 +100,7 @@ export class Operation extends React.Component<OperationProps, OperationState> {
{!options.pathInMiddlePanel && <Endpoint operation={operation} />}
{executeMode &&
<div>
<ConsoleViewer operation={operation} />
<ConsoleViewer operation={operation} additionalHeaders={options.additionalHeaders} queryParamPrefix={options.queryParamPrefix} queryParamSuffix={options.queryParamSuffix} />
</div>
}
{!executeMode &&

View File

@ -7,6 +7,7 @@ export interface RedocRawOptions {
scrollYOffset?: number | string | (() => number);
hideHostname?: boolean | string;
enableConsole?: boolean;
additionalHeaders?: object;
expandResponses?: string | 'all';
requiredPropsFirst?: boolean | string;
noAutoAuth?: boolean | string;
@ -18,6 +19,8 @@ export interface RedocRawOptions {
providedByName?: string;
providedByUri?: string;
queryParamPrefix?: string;
queryParamSuffix?: string;
unstable_ignoreMimeParameters?: boolean;
}
@ -98,8 +101,11 @@ export class RedocNormalizedOptions {
untrustedSpec: boolean;
hideDownloadButton: boolean;
enableConsole: boolean;
additionalHeaders: object;
providedByName: string;
providedByUri: string;
queryParamPrefix: string;
queryParamSuffix: string;
/* tslint:disable-next-line */
unstable_ignoreMimeParameters: boolean;
@ -116,8 +122,11 @@ export class RedocNormalizedOptions {
this.untrustedSpec = argValueToBoolean(raw.untrustedSpec);
this.hideDownloadButton = argValueToBoolean(raw.hideDownloadButton);
this.enableConsole = argValueToBoolean(raw.enableConsole);
this.additionalHeaders = raw.additionalHeaders || {};
this.providedByName = raw.providedByName || 'Documentation Powered by ReDoc';
this.providedByUri = raw.providedByUri || 'https://github.com/Rebilly/ReDoc';
this.queryParamPrefix = raw.queryParamPrefix || '{';
this.queryParamSuffix = raw.queryParamSuffix || '}';
this.unstable_ignoreMimeParameters = argValueToBoolean(raw.unstable_ignoreMimeParameters);
}

View File

@ -11,7 +11,7 @@ import { SchemaModel } from './Schema';
*/
export class FieldModel {
@observable expanded: boolean = false;
@observable $value: string = '';
schema: SchemaModel;
name: string;
required: boolean;
@ -46,4 +46,9 @@ export class FieldModel {
toggle() {
this.expanded = !this.expanded;
}
@action
setValue(value: string) {
this.$value = value;
}
}

View File

@ -1 +1 @@
parseparseFetchFetch
//parseparseFetchFetch