-
-
Save friuns2/7a581a7d61dbf76b2bf945de5feaebb1 to your computer and use it in GitHub Desktop.
.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
```js | |
function openapiToFunctions(openapiSpec) { | |
function replaceRefs(obj, parent = null) { | |
if (Array.isArray(obj)) { | |
return obj.map(item => replaceRefs(item, parent)); | |
} else if (obj !== null && typeof obj === 'object') { | |
if (obj['$ref'] && typeof obj['$ref'] === 'string') { | |
const refPath = obj['$ref'].substring(2).split('/'); | |
let refObj = parent; | |
for (const key of refPath) { | |
refObj = refObj[key]; | |
} | |
return replaceRefs(refObj, parent); // Resolve reference | |
} else { | |
const newObj = {}; | |
for (const [key, value] of Object.entries(obj)) { | |
newObj[key] = replaceRefs(value, parent || obj); | |
} | |
return newObj; | |
} | |
} | |
return obj; | |
} | |
const functions = []; | |
for (const [path, methods] of Object.entries(openapiSpec.paths)) { | |
for (const [method, specWithRef] of Object.entries(methods)) { | |
// 1. Resolve JSON references. | |
const spec = replaceRefs(specWithRef, openapiSpec); | |
// 2. Extract a name for the functions. | |
const functionName = spec.operationId; | |
// 3. Extract a description and parameters. | |
const desc = spec.description || spec.summary || ''; | |
const schema = { type: 'object', properties: {} }; | |
const reqBody = spec.requestBody?.content?.['application/json']?.schema; | |
if (reqBody) { | |
schema.properties.requestBody = reqBody; | |
} | |
const params = spec.parameters || []; | |
if (params.length > 0) { | |
const paramProperties = params.reduce((acc, param) => { | |
if (param.schema) acc[param.name] = param.schema; | |
return acc; | |
}, {}); | |
schema.properties.parameters = { | |
type: 'object', | |
properties: paramProperties, | |
}; | |
} | |
functions.push({ | |
type: 'function', | |
function: { name: functionName, description: desc, parameters: schema }, | |
}); | |
} | |
} | |
return functions; | |
} | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment