Try importing Swagger even if validation fails (Fixes #1354) (#1462)

This commit is contained in:
Gregory Schier 2019-04-25 21:27:01 -07:00 committed by GitHub
parent 035f5fb075
commit c2b4b373b9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 116 additions and 17 deletions

View File

@ -6,7 +6,7 @@ import * as har from './har';
import type { BaseModel } from '../models/index';
import * as models from '../models/index';
import { getAppVersion } from './constants';
import { showModal } from '../ui/components/modals/index';
import { showModal, showError } from '../ui/components/modals/index';
import AlertModal from '../ui/components/modals/alert-modal';
import fs from 'fs';
import type { Workspace } from '../models/workspace';
@ -49,7 +49,11 @@ export async function importUri(workspaceId: string | null, uri: string): Promis
const { summary, error } = result;
if (error) {
showModal(AlertModal, { title: 'Import Failed', message: error });
showError({
title: 'Failed to import',
error: error.message,
message: 'Import failed',
});
return;
}
@ -76,17 +80,16 @@ export async function importRaw(
generateNewIds: boolean = false,
): Promise<{
source: string,
error: string | null,
error: Error | null,
summary: { [string]: Array<BaseModel> },
}> {
let results;
try {
results = await convert(rawContent);
} catch (e) {
console.warn('Failed to import data', e);
} catch (err) {
return {
source: 'not found',
error: 'No importers found for file',
error: err,
summary: {},
};
}

View File

@ -52,7 +52,7 @@ class ErrorModal extends PureComponent {
{message ? <div className="notice error">{message}</div> : null}
{error && (
<pre className="pad-top-sm force-wrap selectable">
<code>{error.stack}</code>
<code>{error.stack || error}</code>
</pre>
)}
</ModalBody>

View File

@ -0,0 +1,41 @@
{
"swagger": "2.0",
"info": {
"version": "v1",
"title": "docs"
},
"paths": {
"/api/list": {
"get": {
"tags": ["Document"],
"summary": "Some list",
"operationId": "ApiId",
"consumes": [],
"produces": ["text/plain", "application/json", "text/json"],
"parameters": [],
"responses": {
"200": {
"description": "Success",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/Dto.Document.DocumetnDto"
}
}
},
"401": {
"description": "Unauthorized"
},
"403": {
"description": "Forbidden"
}
},
"security": [
{
"Bearer": [null, "Role"]
}
]
}
}
}
}

View File

@ -0,0 +1,47 @@
{
"__export_date": "2019-04-26T04:04:46.087Z",
"__export_format": 4,
"__export_source": "insomnia.importers:v0.1.0",
"_type": "export",
"resources": [
{
"_id": "__WORKSPACE_1__",
"_type": "workspace",
"description": "",
"name": "docs v1",
"parentId": null
},
{
"_id": "__ENV_1__",
"_type": "environment",
"data": {
"base_url": "{{ scheme }}://{{ host }}{{ base_path }}"
},
"name": "Base environment",
"parentId": "__WORKSPACE_1__"
},
{
"_id": "__ENV_2__",
"_type": "environment",
"data": {
"base_path": "",
"host": "",
"scheme": "http"
},
"name": "Swagger env",
"parentId": "__ENV_1__"
},
{
"_id": "ApiId",
"_type": "request",
"authentication": {},
"body": {},
"headers": [],
"method": "GET",
"name": "Some list",
"parameters": [],
"parentId": "__WORKSPACE_1__",
"url": "{{ base_url }}/api/list"
}
]
}

View File

@ -18,11 +18,20 @@ module.exports.convert = async function(rawData) {
requestGroupCount = 1;
// Validate
const api = await parseDocument(rawData);
let api = await parseDocument(rawData);
if (!api || api.swagger !== SUPPORTED_SWAGGER_VERSION) {
return null;
}
// Await here so we catch any exceptions
try {
api = await SwaggerParser.validate(api);
} catch (err) {
// We already know it's a Swagger doc so we will try to import it anyway instead
// of bailing out here.
console.log('[swagger] Import file validation failed', err);
}
// Import
const workspace = {
_type: 'workspace',
@ -68,13 +77,7 @@ module.exports.convert = async function(rawData) {
*/
async function parseDocument(rawData) {
try {
const api = utils.unthrowableParseJson(rawData) || SwaggerParser.YAML.parse(rawData);
if (!api) {
return null;
}
// Await here so we catch any exceptions
return await SwaggerParser.validate(api);
return utils.unthrowableParseJson(rawData) || SwaggerParser.YAML.parse(rawData);
} catch (err) {
return null;
}
@ -101,7 +104,7 @@ function parseEndpoints(document) {
.filter(method => method !== 'parameters')
.map(method => Object.assign({}, schemasPerMethod[method], { path, method }));
})
.reduce((flat, arr) => flat.concat(arr), []); //flat single array
.reduce((flat, arr) => flat.concat(arr), []); // flat single array
const tags = document.tags || [];
const folders = tags.map(tag => {
@ -113,7 +116,7 @@ function parseEndpoints(document) {
const requests = [];
endpointsSchemas.map(endpointSchema => {
let { tags } = endpointSchema;
if (!tags || tags.length == 0) tags = [''];
if (!tags || tags.length === 0) tags = [''];
tags.forEach((tag, index) => {
let id = endpointSchema.operationId
? `${endpointSchema.operationId}${index > 0 ? index : ''}`
@ -322,6 +325,11 @@ function generateParameterExample(schema) {
}
const factory = typeExamples[`${type}_${format}`] || typeExamples[type];
if (!factory) {
return null;
}
return factory(schema);
}
}