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

feat(oas): add support the file type defined in Swagger 2.0 #176

Merged
Merged
Show file tree
Hide file tree
Changes from 11 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
8 changes: 6 additions & 2 deletions packages/oas/src/converter/parts/SubConverterFactory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { SubConverter } from '../SubConverter';
import { SubPart } from '../SubPart';
import { Oas2HeadersConverter, Oas3HeadersConverter } from './headers';
import { Oas2PathConverter, Oas3PathConverter } from './path';
import { PostDataConverter } from './postdata';
import { Oas2BodyConverter, Oas3RequestBodyConverter } from './postdata';
import { Oas2QueryStringConverter, Oas3QueryStringConverter } from './query';
import { Sampler } from './Sampler';
import { OpenAPI, OpenAPIV2, OpenAPIV3 } from '@har-sdk/core';
Expand All @@ -25,7 +25,11 @@ export class SubConverterFactory {
case SubPart.PATH:
return this.instantiate(spec, Oas2PathConverter, Oas3PathConverter);
case SubPart.POST_DATA:
return new PostDataConverter(spec, this.sampler);
return this.instantiate(
spec,
Oas2BodyConverter,
Oas3RequestBodyConverter
);
case SubPart.QUERY_STRING:
return this.instantiate(
spec,
Expand Down
188 changes: 188 additions & 0 deletions packages/oas/src/converter/parts/postdata/BodyConverter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
import { Sampler } from '../Sampler';
import { SubConverter } from '../../SubConverter';
import { OpenAPI, OpenAPIV3, PostData } from '@har-sdk/core';
import { toXML, XmlElement } from 'jstoxml';
import { stringify } from 'qs';

export abstract class BodyConverter<T extends OpenAPI.Document>
implements SubConverter<PostData | null>
{
private readonly JPG_IMAGE = '/9j/7g=='; // 0xff, 0xd8, 0xff, 0xee
derevnjuk marked this conversation as resolved.
Show resolved Hide resolved
private readonly PNG_IMAGE = 'iVBORw0KGgo='; // 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0A, 0x1a, 0x0a
private readonly ICO_IMAGE = 'AAABAA=='; // 0x00, 0x00, 0x01, 0x00
private readonly GIF_IMAGE = 'R0lGODdh'; // 0x47, 0x49, 0x46, 0x38, 0x37, 0x61
private readonly BOUNDARY = '956888039105887155673143';
private readonly BASE64_PATTERN =
/^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$/;

protected constructor(
protected readonly spec: T,
protected readonly sampler: Sampler
) {}

public abstract convert(path: string, method: string): PostData | null;

protected abstract getContentType(
path: string,
method: string
): string | undefined;

protected encodePayload(
data: unknown,
contentType: string,
encoding?: OpenAPIV3.EncodingObject
): { mimeType: string; text: string } {
let encodedData = data;

if (encoding) {
encodedData = this.encodeProperties(
Object.keys(encoding),
data,
encoding
);
}

return {
mimeType: contentType.includes('multipart')
? `${contentType}; boundary=${this.BOUNDARY}`
: contentType,
text: this.encodeValue(encodedData, contentType)
};
}

// eslint-disable-next-line complexity
private encodeValue(
value: unknown,
contentType: string,
encoding?: string
): string {
const [mime]: string[] = contentType
.split(',')
.map((x) => x.trim().replace(/;.+?$/, ''));

switch (mime) {
case 'application/json':
return this.encodeJson(value);
case 'application/x-www-form-urlencoded':
return this.encodeFormUrlencoded(value);
case 'application/xml':
return this.encodeXml(value);
case 'multipart/form-data':
case 'multipart/mixin':
pmstss marked this conversation as resolved.
Show resolved Hide resolved
return this.encodeMultipartFormData(value, encoding);
case 'image/x-icon':
case 'image/ico':
case 'image/vnd.microsoft.icon':
return this.ICO_IMAGE;
case 'image/jpg':
case 'image/jpeg':
return this.JPG_IMAGE;
case 'image/gif':
return this.GIF_IMAGE;
case 'image/png':
case 'image/*':
return this.PNG_IMAGE;
default:
return this.encodeOther(value);
}
}

private encodeMultipartFormData(value: unknown, encoding?: string): string {
const EOL = '\r\n';

return Object.entries(value || {})
.map(([key, val]: [string, unknown]) => {
const contentType = encoding ?? this.inferMultipartContentType(val);
const filenameRequired = this.filenameRequired(contentType);
const content = this.encodeOther(val);

const headers = [
`Content-Disposition: form-data; name="${key}"${
filenameRequired ? `; filename="${key}"` : ''
}`,
...(contentType !== 'text/plain'
? [`Content-Type: ${contentType}`]
: []),
...(this.BASE64_PATTERN.test(content) &&
contentType === 'application/octet-stream'
pmstss marked this conversation as resolved.
Show resolved Hide resolved
? [`Content-Transfer-Encoding: base64`]
: [])
];
const body = `${headers.join(EOL)}${EOL}${EOL}${content}`;

return `--${this.BOUNDARY}${EOL}${body}`;
})
.join(EOL)
.concat(`${EOL}--${this.BOUNDARY}--`);
}

private filenameRequired(contentType: string) {
return !['application/json', 'text/plain'].includes(contentType);
}

private inferMultipartContentType(value: unknown): string {
switch (typeof value) {
case 'object':
return 'application/json';
case 'string':
return this.BASE64_PATTERN.test(value)
? 'application/octet-stream'
: 'text/plain';
case 'number':
case 'boolean':
case 'bigint':
case 'symbol':
case 'undefined':
return 'text/plain';
default:
return 'application/octet-stream';
}
}

private encodeProperties(
keys: string[],
data: unknown,
encoding?: OpenAPIV3.EncodingObject
): unknown {
const sample = keys.reduce((encodedSample, encodingKey) => {
const { contentType }: OpenAPIV3.EncodingObject =
encoding?.[encodingKey] ?? {};

encodedSample[encodingKey] = this.encodeValue(
data[encodingKey],
contentType,
encodingKey
);

return encodedSample;
}, {});

return Object.assign({}, data, sample);
}

private encodeJson(value: unknown): string {
return typeof value === 'string' ? value : JSON.stringify(value);
}

private encodeFormUrlencoded(value: unknown): string {
return stringify(value, {
format: 'RFC3986',
encode: false
});
}

private encodeXml(value: unknown): string {
const xmlOptions = {
header: true,
indent: ' '
};

return toXML(value as XmlElement, xmlOptions);
}

private encodeOther(value: unknown): string {
return typeof value === 'object'
? JSON.stringify(value)
: value?.toString();
}
}
122 changes: 122 additions & 0 deletions packages/oas/src/converter/parts/postdata/Oas2BodyConverter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
import { BodyConverter } from './BodyConverter';
import { Sampler } from '../Sampler';
import { filterLocationParams, getParameters, isOASV2 } from '../../../utils';
import { OpenAPIV2, PostData } from '@har-sdk/core';

export class Oas2BodyConverter extends BodyConverter<OpenAPIV2.Document> {
constructor(spec: OpenAPIV2.Document, sampler: Sampler) {
super(spec, sampler);
}

public convert(path: string, method: string): PostData | null {
const tokens = ['paths', path, method];
const params: OpenAPIV2.ParameterObject[] = getParameters(
this.spec,
path,
method
);
const contentType = this.getContentType(path, method);

let postData = this.convertBody(params, {
tokens,
contentType
});

if (!postData) {
postData = this.convertFormData(params, {
tokens,
contentType
});
}

return postData;
}

protected getContentType(path: string, method: string): string | undefined {
const operation = this.spec.paths[path][method];

let consumes: OpenAPIV2.MimeTypes;

if (operation.consumes?.length) {
consumes = operation.consumes;
} else if (isOASV2(this.spec) && this.spec.consumes?.length) {
consumes = this.spec.consumes;
}

return this.sampler.sample({
type: 'array',
examples: consumes
});
}

private convertFormData(
params: OpenAPIV2.ParameterObject[],
{
contentType,
...sampleOptions
}: {
tokens: string[];
contentType?: string;
}
): { mimeType: string; text: string } {
const formDataParams = filterLocationParams(params, 'formdata');
if (!formDataParams.length) {
return null;
}

const data = Object.fromEntries(
formDataParams.map((param) => [
param.name,
this.sampleParam(param, { ...sampleOptions, params })
])
);

return this.encodePayload(data, contentType);
}

private convertUnsupportedParamToString(
param: OpenAPIV2.ParameterObject
): OpenAPIV2.ParameterObject {
return {
...param,
...('in' in param && 'type' in param && param.type === 'file'
? { type: 'string' }
: {})
};
}

private convertBody(
params: OpenAPIV2.ParameterObject[],
{
contentType,
...sampleOptions
}: {
tokens: string[];
contentType?: string;
}
): { mimeType: string; text: string } {
const bodyParams = filterLocationParams(params, 'body');

for (const param of bodyParams) {
if ('schema' in param) {
const value = this.sampleParam(param, { ...sampleOptions, params });

return this.encodePayload(value, contentType);
}
}
}

private sampleParam(
param: OpenAPIV2.ParameterObject,
sampleOptions: { tokens: string[]; params: OpenAPIV2.ParameterObject[] }
): unknown {
return this.sampler.sampleParam(
this.convertUnsupportedParamToString(param),
{
...sampleOptions,
idx: sampleOptions.params.indexOf(param),
spec: this.spec
}
);
}
}
Loading