Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added basic multipart form data support to API documentation. #1381

Merged
merged 1 commit into from
Jul 16, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions scripts.v2/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,14 +56,22 @@ async function getStorageSasToken(managementApiEndpoint, managementApiAccessToke
* @param {Object} options https options
*/
async function request(method, url, accessToken, body) {
let requestBody;

const headers = {
"If-Match": "*",
"Content-Type": "application/json",
"Authorization": accessToken
};

if (body) {
headers["Content-Length"] = Buffer.byteLength(body);
if (!body.properties) {
body = {
properties: body
}
}
requestBody = JSON.stringify(body);
headers["Content-Length"] = Buffer.byteLength(requestBody);
}

const options = {
Expand Down Expand Up @@ -105,8 +113,8 @@ async function request(method, url, accessToken, body) {
reject(e);
});

if (body) {
req.write(body);
if (requestBody) {
req.write(requestBody);
}

req.end();
Expand Down
6 changes: 4 additions & 2 deletions src/components/apis/details-of-api/ko/runtime/api-details.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Router } from "@paperbits/common/routing";
import { ApiService } from "../../../../../services/apiService";
import { Api } from "../../../../../models/api";
import { RouteHelper } from "../../../../../routing/routeHelper";
import { KnownMimeTypes } from "../../../../../models/knownMimeTypes";


@RuntimeComponent({
Expand Down Expand Up @@ -106,12 +107,12 @@ export class ApiDetails {
if (this.api() && this.api().id) {
let exportObject = await this.apiService.exportApi(this.api().id, definitionType);
let fileName = this.api().name;
let fileType = "application/json";
let fileType: string = KnownMimeTypes.Json;

switch (definitionType) {
case "wsdl":
case "wadl":
fileType = "text/xml";
fileType = KnownMimeTypes.Xml;
fileName = `${fileName}.${definitionType}.xml`;
break;
case "openapi": // yaml 3.0
Expand Down Expand Up @@ -151,6 +152,7 @@ export class ApiDetails {

private onVersionChange(selectedApiName: string): void {
const apiName = this.routeHelper.getApiName();

if (apiName !== selectedApiName) {
const apiUrl = this.routeHelper.getApiReferenceUrl(selectedApiName);
this.router.navigateTo(apiUrl);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ import template from "./operation-console.html";
import { ResponsePackage } from "./responsePackage";
import { templates } from "./templates/templates";
import { LogItem, WebsocketClient } from "./websocketClient";
import { FormDataItem } from "../../../../../models/console/formDataItem";
import { KnownMimeTypes } from "../../../../../models/knownMimeTypes";

const oauthSessionKey = "oauthSession";

Expand Down Expand Up @@ -67,13 +67,13 @@ export class OperationConsole {
public isConsumptionMode: boolean;
public templates: Object;
public backendUrl: string;

public readonly wsConnected: ko.Observable<boolean>;
public readonly wsConnecting: ko.Observable<boolean>;
public readonly wsStatus: ko.Observable<string>;
public readonly wsSending: ko.Observable<boolean>;
public readonly wsSendStatus: ko.Observable<string>;
public readonly wsPayload: ko.Observable<string|File>;
public readonly wsPayload: ko.Observable<string | File>;
public readonly wsDataFormat: ko.Observable<string>;
public readonly wsLogItems: ko.ObservableArray<LogItem>;

Expand Down Expand Up @@ -375,7 +375,7 @@ export class OperationConsole {
}

private getSubscriptionKeyHeaderName(): string {
let subscriptionKeyHeaderName = KnownHttpHeaders.OcpApimSubscriptionKey;
let subscriptionKeyHeaderName: string = KnownHttpHeaders.OcpApimSubscriptionKey;

if (this.api().subscriptionKeyParameterNames && this.api().subscriptionKeyParameterNames.header) {
subscriptionKeyHeaderName = this.api().subscriptionKeyParameterNames.header;
Expand All @@ -402,7 +402,7 @@ export class OperationConsole {
}

private setSubscriptionKeyParameter(subscriptionKey: string): void {
const subscriptionKeyParam = this.getSubscriptionKeyParam();
const subscriptionKeyParam = this.getSubscriptionKeyParam();
this.removeQueryParameter(subscriptionKeyParam);

if (!subscriptionKey) {
Expand Down Expand Up @@ -519,7 +519,7 @@ export class OperationConsole {
}

const formData = new FormData();
const requestPackage = new Blob([JSON.stringify(request)], { type: "application/json" });
const requestPackage = new Blob([JSON.stringify(request)], { type: KnownMimeTypes.Json });
formData.append("requestPackage", requestPackage);

const baseProxyUrl = this.backendUrl || "";
Expand Down Expand Up @@ -717,7 +717,7 @@ export class OperationConsole {
this.responseStatusCode(null);

const consoleOperation = this.consoleOperation();
const url = consoleOperation.wsUrl();
const url = consoleOperation.wsUrl();

this.initWebSocket();
this.wsStatus("Connecting...");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,32 @@ <h4>Request body</h4>
</type-definition>
<!-- /ko -->

<!-- ko if: representation.formParameters?.length > 0 -->
<div role="table" class="table-preset table-preset-params">
<div class="d-contents" role="rowgroup">
<div class="d-contents" role="row">
<div role="columnheader" class="table-preset-head text-truncate">Name</div>
<div role="columnheader" class="table-preset-head text-truncate">In</div>
<div role="columnheader" class="table-preset-head text-truncate">Required</div>
<div role="columnheader" class="table-preset-head text-truncate">Type</div>
<div role="columnheader" class="table-preset-head">Description</div>
</div>
</div>
<div class="d-contents" role="rowgroup">
<!-- ko foreach: { data: representation.formParameters, as: 'parameter' } -->
<div class="d-contents" role="row">
<div role="cell" class="text-truncate monospace"
data-bind="text: parameter.name, attr: { title: parameter.name }"></div>
<div role="cell" class="text-truncate" data-bind="text: parameter.in"></div>
<div role="cell" class="text-truncate" data-bind="text: parameter.required"></div>
<div role="cell" class="text-truncate monospace" data-bind="text: parameter.type"></div>
<div role="cell" data-bind="markdown: parameter.description"></div>
</div>
<!-- /ko -->
</div>
</div>
<!-- /ko -->

<!-- ko ifnot: representation.typeName -->
<!-- ko if: representation.example -->
<code-sample params="{ content: representation.example, language: representation.exampleFormat }">
Expand Down Expand Up @@ -257,7 +283,7 @@ <h3>Protocol</h3>
<span class="monospace" data-bind="text: $component.protocol"></span>
</div>
</div>

</div>
<!-- /ko -->
<!-- /ko -->
Expand Down
42 changes: 22 additions & 20 deletions src/models/console/consoleRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { ConsoleRepresentation } from "./consoleRepresentation";
import { Request } from "../request";
import { RequestBodyType } from "../../constants";
import { FormDataItem } from "./formDataItem";
import { KnownHttpHeaders } from "../knownHttpHeaders";

export class ConsoleRequest {
public readonly queryParameters: ko.ObservableArray<ConsoleParameter>;
Expand All @@ -18,7 +19,6 @@ export class ConsoleRequest {
public readonly bodyFormat: ko.Observable<RequestBodyType>;
public readonly bodyDataItems: ko.ObservableArray<FormDataItem>;
public readonly representationContentType: string;

public readonly readonlyBodyFormat: boolean;

constructor(request: Request) {
Expand All @@ -30,7 +30,7 @@ export class ConsoleRequest {

this.body = ko.observable();
this.binary = ko.observable();
this.binary.extend(<any>{ maxFileSize: 3 * 1024 * 1024 });
this.binary.extend(<any>{ maxFileSize: 3 * 1024 * 1024 });
this.bodyFormat = ko.observable(RequestBodyType.raw);
this.bodyDataItems = ko.observableArray([]);

Expand All @@ -47,44 +47,46 @@ export class ConsoleRequest {
// do not convert formParameters for contentType = application/x-www-form-urlencoded
// do not add Content-Type header for multipart/form-data
const bodyRepresentation = this.representationContentType === "multipart/form-data" && request.representations.find(r => r.formParameters?.length > 0);

if (bodyRepresentation) {
this.hasBody = true;
this.readonlyBodyFormat = true;
this.bodyFormat(RequestBodyType.form);
const dataItems = bodyRepresentation.formParameters.map(p => {

const dataItems = bodyRepresentation.formParameters.map(parameter => {
const item = new FormDataItem();
item.name(p.name);
item.type(p.type);
item.description(p.description);
item.required(p.required);
item.name(parameter.name);
item.type(parameter.type);
item.description(parameter.description);
item.required(parameter.required);
return item;
});
this.bodyDataItems(dataItems);
} else {
if (this.representationContentType && this.headers().find(h => h.name() === "Content-Type") === undefined) {
const consoleHeader = new ConsoleHeader();
consoleHeader.name("Content-Type");
consoleHeader.value(this.representationContentType);
this.headers.push(consoleHeader);
}
}

else if (this.representationContentType && this.headers().find(h => h.name() === KnownHttpHeaders.ContentType) === undefined) {
const consoleHeader = new ConsoleHeader();
consoleHeader.name(KnownHttpHeaders.ContentType);
consoleHeader.value(this.representationContentType);
this.headers.push(consoleHeader);
}
}

public getFormDataPayload(): FormData {
const formData = new FormData();
const items = this.bodyDataItems();
for (let i = 0; i < items.length; i++) {
const item = items[i];

for (const item of items) {
if (item.bodyFormat() === RequestBodyType.binary) {
const file = item.binary();

if (file) {
formData.append(item.name(), file, file.name);
} else {
}
else {
formData.append(item.name(), "");
}
} else {
}
else {
formData.append(item.name(), item.body() || "");
}
}
Expand Down
21 changes: 11 additions & 10 deletions src/models/knownHttpHeaders.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
export const KnownHttpHeaders = {
Authorization: "Authorization",
CacheControl: "Cache-Control",
ContentType: "Content-Type",
OcpApimSubscriptionKey: "Ocp-Apim-Subscription-Key",
OcpApimTrace: "Ocp-Apim-Trace",
OcpApimTraceLocation: "Ocp-Apim-Trace-Location",
OcpApimSasToken: "Ocp-Apim-Sas-Token",
SoapAction: "SOAPAction",
};
export enum KnownHttpHeaders {
Authorization = "Authorization",
CacheControl = "Cache-Control",
ContentType = "Content-Type",
OcpApimSubscriptionKey = "Ocp-Apim-Subscription-Key",
OcpApimTrace = "Ocp-Apim-Trace",
OcpApimTraceLocation = "Ocp-Apim-Trace-Location",
OcpApimSasToken = "Ocp-Apim-Sas-Token",
SoapAction = "SOAPAction",
IfMatch = "If-Match"
}
5 changes: 5 additions & 0 deletions src/models/knownMimeTypes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export enum KnownMimeTypes {
FormData = "multipart/form-data",
Json = "application/json",
Xml = "text/xml"
}
26 changes: 13 additions & 13 deletions src/models/operation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,18 @@ import { Response } from "./response";
import { Utils } from "../utils";

export class Operation {
public id: string;
public name: string;
public displayName: string;
public description: string;
public urlTemplate: string;
public templateParameters: Parameter[];
public parameters: Parameter[];
public method: string;
public version?: string;
public request?: Request;
public responses?: Response[];
public displayUrlTemplate: string;
public readonly id: string;
public readonly name: string;
public readonly displayName: string;
public readonly description: string;
public readonly urlTemplate: string;
public readonly templateParameters: Parameter[];
public readonly parameters: Parameter[];
public readonly method: string;
public readonly version: string;
public readonly request: Request;
public readonly responses: Response[];
public readonly displayUrlTemplate: string;

public getMeaningfulResponses(): Response[] {
return this.responses.filter(x => x.isMeaningful());
Expand Down Expand Up @@ -44,7 +44,7 @@ export class Operation {
: [];

let connector = this.urlTemplate.includes("?") ? "&" : "?";

const optionalQueryParameters = this.request.queryParameters
.map((parameter, index) => {
if (index > 0) {
Expand Down
14 changes: 7 additions & 7 deletions src/models/parameter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,37 +4,37 @@ export class Parameter {
/**
* Parameter name, e.g. api-version.
*/
public name: string;
public readonly name: string;

/**
* Parameter description.
*/
public description: string;
public readonly description: string;

/**
* Parameter placement, e.g. "query", "template", "header", "body".
*/
public in: string;
public readonly in: string;

/**
* Parameter type, e.g. "string", "int64", etc.
*/
public type: string;
public readonly type: string;

/**
* Parameter default value, e.g. "2018-06-01-preview".
*/
public defaultValue: string;
public readonly defaultValue: string;

/**
* Parameter value suggestions, e.g. ["2016-07-07","2016-10-10", "2018-06-01-preview"]
*/
public values: string[];
public readonly values: string[];

/**
* Indicates if the parameter is required to make a request.
*/
public required: boolean;
public readonly required: boolean;

constructor(placement: string, contract?: ParameterContract) {
this.name = contract.name;
Expand Down
18 changes: 9 additions & 9 deletions src/models/product.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ import { ProductContract } from "../contracts/product";
import { Utils } from "../utils";

export class Product {
public id: string;
public name: string;
public displayName: string;
public description: string;
public approvalRequired: boolean;
public state: string;
public subscriptionRequired: boolean;
public subscriptionsLimit?: number;
public terms: string;
public readonly id: string;
public readonly name: string;
public readonly displayName: string;
public readonly description: string;
public readonly approvalRequired: boolean;
public readonly state: string;
public readonly subscriptionRequired: boolean;
public readonly subscriptionsLimit?: number;
public readonly terms: string;

constructor(contract?: ProductContract) {
this.id = Utils.getResourceName("products", contract.id, "shortId");
Expand Down
Loading