From fd6b3630a53a0d2db871002b4613436624b0c56c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Mockers?= Date: Fri, 23 Aug 2024 21:11:45 +0200 Subject: [PATCH] extract basic OpenAPI links (#2624) --- .../src/utils/importers/openapi-collection.js | 40 ++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/packages/bruno-app/src/utils/importers/openapi-collection.js b/packages/bruno-app/src/utils/importers/openapi-collection.js index 01fb66c01..524c434d5 100644 --- a/packages/bruno-app/src/utils/importers/openapi-collection.js +++ b/packages/bruno-app/src/utils/importers/openapi-collection.js @@ -59,12 +59,15 @@ const transformOpenapiRequestItem = (request) => { operationName = `${request.method} ${request.path}`; } + // replace OpenAPI links in path by Bruno variables + let path = request.path.replace(/{([a-zA-Z]+)}/g, `{{${_operationObject.operationId}_$1}}`); + const brunoRequestItem = { uid: uuid(), name: operationName, type: 'http-request', request: { - url: ensureUrl(request.global.server + '/' + request.path), + url: ensureUrl(request.global.server + '/' + path), method: request.method.toUpperCase(), auth: { mode: 'none', @@ -81,6 +84,9 @@ const transformOpenapiRequestItem = (request) => { xml: null, formUrlEncoded: [], multipartForm: [] + }, + script: { + res: null } } }; @@ -195,6 +201,26 @@ const transformOpenapiRequestItem = (request) => { } } + // build the extraction scripts from responses that have links + // https://swagger.io/docs/specification/links/ + let script = []; + each(_operationObject.responses || [], (response, responseStatus) => { + if (Object.hasOwn(response, 'links')) { + // only extract if the status code matches the response + script.push(`if (res.status === ${responseStatus}) {`); + each(response.links, (link) => { + each(link.parameters || [], (expression, parameter) => { + let value = openAPIRuntimeExpressionToScript(expression); + script.push(` bru.setVar('${link.operationId}_${parameter}', ${value});`); + }); + }); + script.push(`}`); + } + }); + if (script.length > 0) { + brunoRequestItem.request.script.res = script.join('\n'); + } + return brunoRequestItem; }; @@ -305,6 +331,18 @@ const getSecurity = (apiSpec) => { }; }; +const openAPIRuntimeExpressionToScript = (expression) => { + // see https://swagger.io/docs/specification/links/#runtime-expressions + if (expression === '$response.body') { + return 'res.body'; + } else if (expression.startsWith('$response.body#')) { + let pointer = expression.substring(15); + // could use https://www.npmjs.com/package/json-pointer for better support + return `res.body${pointer.replace('/', '.')}`; + } + return expression; +}; + const parseOpenApiCollection = (data) => { const brunoCollection = { name: '',