Change API parser to handle nested objects (#159)

* rewrite parser to handle new format and nested objects

* add properties section also to nested properties

* update docs manually
This commit is contained in:
pascal-fischer
2024-02-29 15:24:00 +02:00
committed by GitHub
parent 69cddadbe4
commit dd08a8e07d
23 changed files with 4242 additions and 1260 deletions

View File

@@ -1,17 +1,43 @@
import template from './templates/ApiTemplate'
import { slugify, toArrayWithKey, toTitle, writeToDisk } from './helpers'
import {OpenAPIV3} from 'openapi-types'
import {OpenAPIV3, OpenAPIV3_1} from 'openapi-types'
import * as fs from 'fs'
import * as ejs from 'ejs'
import { spawn } from 'child_process';
import * as yaml from 'js-yaml';
import { merge } from 'allof-merge'
import RequestBodyObject = OpenAPIV3_1.RequestBodyObject;
const goExecutable = './generator/expandOpenAPIRef'
export default async function gen(inputFileName: string, outputDir: string) {
// const args = [inputFileName];
// const process = spawn(goExecutable, args);
// process.stdout.on('data', (data) => {
// console.log(`Output: ${data}`);
// });
// process.stderr.on('data', (data) => {
// console.error(`Error: ${data}`);
// });
// process.on('close', (code) => {
// console.log(`Process exited with code ${code}`);
// });
// const specRaw = fs.readFileSync("generator/openapi/expanded.yml", 'utf8')
const specRaw = fs.readFileSync(inputFileName, 'utf8')
const spec = JSON.parse(specRaw) as any
// const spec = JSON.parse(specRaw) as any
const specYaml = yaml.load(specRaw);
const onMergeError = (msg) => {
throw new Error(msg)
}
const merged = merge(specYaml, { onMergeError })
switch (spec.openapi || spec.swagger) {
const spec = merged as OpenAPIV3.Document
switch (spec.openapi) {
case '3.0.0':
case '3.0.1':
case '3.0.3':
case '3.1.0':
await gen_v3(spec, outputDir)
break
@@ -21,21 +47,23 @@ export default async function gen(inputFileName: string, outputDir: string) {
}
}
/**
* Versioned Generator
*/
// OPENAPI-SPEC-VERSION: 3.0.0
type v3OperationWithPath = OpenAPIV3.OperationObject & {
path: string
}
export type objectRepresentation = {
example: Object
schema: Object
}
export type enrichedOperation = OpenAPIV3.OperationObject & {
path: string
fullPath: string
operationId: string
request: objectRepresentation
response: objectRepresentation
}
export type schemaParameter = {
name: string
type: string
@@ -46,12 +74,7 @@ export type schemaParameter = {
minLength?: number
maxLength?: number
enum?: string[]
}
export type component = {
example: Object
schema: Object
parameters: schemaParameter[]
sub?: Map<string,schemaParameter>
}
async function gen_v3(spec: OpenAPIV3.Document, dest: string) {
@@ -64,6 +87,29 @@ async function gen_v3(spec: OpenAPIV3.Document, dest: string) {
toArrayWithKey(val!, 'operation').forEach((o) => {
const operation = o as v3OperationWithPath
var request = null
if (operation.requestBody && 'content' in operation.requestBody && operation.requestBody.content['application/json']) {
request = {
example: extractInfo((operation.requestBody as RequestBodyObject).content['application/json'].schema, 'example'),
schema: extractInfo((operation.requestBody as RequestBodyObject).content['application/json'].schema, 'type')
}
}
var response = null
if(operation.responses["200"] != undefined && operation.responses["200"]["content"]["application/json"] != undefined) {
response = {
example: extractInfo(operation.responses["200"]["content"]["application/json"].schema, 'example'),
schema: extractInfo(operation.responses["200"]["content"]["application/json"].schema, 'type')
}
}
// if(operation.summary == "List all Tokens") {
// console.log(response.example)
// console.log(operation.responses["200"]["content"]["application/json"].schema.items.properties)
// }
const enriched = {
...operation,
path: key,
@@ -71,6 +117,8 @@ async function gen_v3(spec: OpenAPIV3.Document, dest: string) {
operationId: slugify(operation.summary!),
responseList: toArrayWithKey(operation.responses!, 'responseCode') || [],
request: request,
response: response,
}
let tag = operation.tags.pop()
let tagOperations = tagGroups.get(tag) ?? []
@@ -78,8 +126,6 @@ async function gen_v3(spec: OpenAPIV3.Document, dest: string) {
})
})
let components = readComponents(spec.components)
tagGroups.forEach((value: enrichedOperation[], key: string) => {
const operations = value
@@ -98,121 +144,70 @@ async function gen_v3(spec: OpenAPIV3.Document, dest: string) {
tag: key,
sections,
operations,
components,
// components,
})
// Write to disk
let outputFile = dest + "/" + key.toLowerCase().replace(" ", "-") + ".mdx"
writeToDisk(outputFile, content)
// console.log('Saved: ', outputFile)
})
}
function readComponents(components: OpenAPIV3.ComponentsObject) : Map<string, component> {
let componentsOutput = new Map<string, component>()
for (const [key, value] of Object.entries(components.schemas)) {
let [schema, example, parameter] = resolveComponents(value, components)
let component = {
example: example,
schema: schema,
parameters: parameter
function extractInfo(obj, mode = 'example') {
// Handle the root level object that represents an array
if (obj.type === 'array' && obj.hasOwnProperty('items')) {
if (obj.items.hasOwnProperty('properties')) {
return [extractInfo(obj.items.properties, mode)];
} else {
return [extractInfo(obj.items, mode)];
}
componentsOutput.set(key, component)
}
return componentsOutput
}
function resolveComponents(value: OpenAPIV3.ReferenceObject | OpenAPIV3.ArraySchemaObject | OpenAPIV3.NonArraySchemaObject, components: OpenAPIV3.ComponentsObject) : [Object, Object, schemaParameter[]] {
if((value as OpenAPIV3.ReferenceObject).$ref) {
let subcomponentName = (value as OpenAPIV3.ReferenceObject).$ref.split('/').pop()
let subcomponent = components.schemas[subcomponentName]
return resolveComponents(subcomponent, components)
}
if((value as OpenAPIV3.SchemaObject).properties) {
return resolveProperties(value as OpenAPIV3.SchemaObject, components)
}
if((value as OpenAPIV3.SchemaObject).allOf) {
return resolveAllOf(value as OpenAPIV3.SchemaObject, components)
}
if((value as OpenAPIV3.SchemaObject).type || (value as OpenAPIV3.SchemaObject).example) {
return [(value as OpenAPIV3.SchemaObject).type, (value as OpenAPIV3.SchemaObject).example, null]
}
}
function resolveAllOf(object: OpenAPIV3.SchemaObject, components: OpenAPIV3.ComponentsObject) : [Object, Object, schemaParameter[]] {
let examples = new Map<string, any>()
let schemas = new Map<string, any>()
let parameters: schemaParameter[] = []
for (const [key, value] of Object.entries(object.allOf)) {
let example;
let schema;
let parameter;
if((value as OpenAPIV3.ReferenceObject).$ref) {
let subcomponentName = (value as OpenAPIV3.ReferenceObject).$ref.split('/').pop()
let subcomponent = components.schemas[subcomponentName];
[schema, example, parameter] = resolveComponents(subcomponent, components)
}
if((value as OpenAPIV3.SchemaObject).properties) {
[schema, example, parameter] = resolveProperties(value as OpenAPIV3.SchemaObject, components)
}
if(!(example instanceof Map)) {
example = new Map(Object.entries(example))
}
if(!(schema instanceof Map)) {
schema = new Map(Object.entries(schema))
}
parameters = parameters.concat(parameter)
examples = mergeMaps(examples, example)
schemas = mergeMaps(schemas, schema)
}
return [Object.fromEntries(schemas), Object.fromEntries(examples), parameters]
}
function resolveProperties(value: OpenAPIV3.SchemaObject, components: OpenAPIV3.ComponentsObject): [Object, Object, schemaParameter[]] {
let examples = new Map<string, Object>()
let schemas = new Map<string, Object>()
let parameters: schemaParameter[] = []
for(const [key, property] of Object.entries(value.properties)) {
let type: string = ""
if(property["$ref"]) {
let [schema, example, parameter] = resolveComponents(property, components)
examples.set(key, example)
schemas.set(key, schema)
parameters = parameters.concat(parameter)
continue
}
switch (property["type"]) {
case "array":
type = ((property["items"] as OpenAPIV3.SchemaObject).type || (property["items"] as OpenAPIV3.ReferenceObject).$ref.split('/').pop()) + "[]"
let [schema, example] = resolveComponents(property["items"], components)
examples.set(key, new Array(example))
schemas.set(key, new Array(schema))
break;
case "object":
default:
type = property["type"]
examples.set(key, property["example"])
schemas.set(key, property["type"])
}
let parameter: schemaParameter = {
name: key,
type: type,
description: property["description"],
required: value.required?.includes(key) || false,
minimum: property["minimum"],
maximum: property["maximum"],
minLength: property["minLength"],
maxLength: property["maxLength"],
enum: property["enum"],
}
parameters.push(parameter)
}
return [Object.fromEntries(schemas), Object.fromEntries(examples), parameters]
}
function mergeMaps(map1: Map<string, Object>, map2: Map<string, Object>) : Map<string, Object> {
return new Map([...Array.from(map1.entries()), ...Array.from(map2.entries())]);
// If mode is 'example' and the object has an 'example', return it immediately
if (mode === 'example' && obj.hasOwnProperty('example')) {
return obj.example;
}
// For an object with 'properties', check if there's an example at this level first
if (obj.type === 'object' && obj.hasOwnProperty('properties')) {
// If an example is provided at the current level, return it, avoiding deeper analysis
if (obj.hasOwnProperty('example')) {
return obj.example;
} else {
// If no example is provided, then proceed to extract info from its properties
const result = {};
for (const key in obj.properties) {
if (obj.properties.hasOwnProperty(key)) {
result[key] = extractInfo(obj.properties[key], mode);
}
}
return result;
}
}
// Return the type for elementary types if mode is 'type'
if (mode === 'type' && ['string', 'number', 'boolean', 'integer'].includes(obj.type)) {
return obj.type;
}
// Handle arrays, assuming each item might be an object with its own structure
if (Array.isArray(obj)) {
return obj.map(item => extractInfo(item, mode));
}
// Special handling for objects that represent schemas (e.g., with 'type' and 'properties')
if (typeof obj === 'object' && obj !== null) {
const result = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
result[key] = extractInfo(obj[key], mode);
}
}
return result;
}
// Return the object if it doesn't match any of the above conditions
return obj;
}

View File

@@ -0,0 +1,61 @@
package main
import (
"fmt"
"io/ioutil"
"os"
"github.com/pb33f/libopenapi/index"
"gopkg.in/yaml.v3"
)
func main() {
// if len(os.Args) != 1 {
// fmt.Printf("No input file provided!\n")
// }
// load an OpenAPI 3 specification from bytes
// petstore, _ := ioutil.ReadFile(os.Args[0])
petstore, _ := ioutil.ReadFile("openapi/openapi.yml")
// create a root node to unmarshal the spec into.
var rootNode yaml.Node
_ = yaml.Unmarshal(petstore, &rootNode)
// create a new config that does not allow lookups.
indexConfig := index.CreateClosedAPIIndexConfig()
// create a new rolodex
rolodex := index.NewRolodex(indexConfig)
// set the rolodex root node to the root node of the spec.
rolodex.SetRootNode(&rootNode)
// index the rolodex
indexedErr := rolodex.IndexTheRolodex()
if indexedErr != nil {
panic(indexedErr)
}
// resolve the petstore
rolodex.Resolve()
// extract the resolver from the root index.
node := rolodex.GetRootNode()
b, e := yaml.Marshal(node)
if e != nil {
panic(e)
}
var newNode yaml.Node
_ = yaml.Unmarshal(b, &newNode)
err := os.WriteFile("openapi/expanded.yml", b, 0644)
if err != nil {
fmt.Printf("Failed to write file: %v", err)
return
}
}

17
generator/go.mod Normal file
View File

@@ -0,0 +1,17 @@
module generator
go 1.21.1
require github.com/pb33f/libopenapi v0.15.13
require (
github.com/bahlo/generic-list-go v0.2.0 // indirect
github.com/buger/jsonparser v1.1.1 // indirect
github.com/dprotaso/go-yit v0.0.0-20220510233725-9ba8df137936 // indirect
github.com/mailru/easyjson v0.7.7 // indirect
github.com/vmware-labs/yaml-jsonpath v0.3.2 // indirect
github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect
golang.org/x/exp v0.0.0-20240213143201-ec583247a57a // indirect
golang.org/x/sync v0.6.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

144
generator/go.sum Normal file
View File

@@ -0,0 +1,144 @@
github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk=
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
github.com/buger/jsonparser v1.1.1 h1:2PnMjfWD7wBILjqQbt530v576A/cAbQvEW9gGIpYMUs=
github.com/buger/jsonparser v1.1.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dprotaso/go-yit v0.0.0-20191028211022-135eb7262960/go.mod h1:9HQzr9D/0PGwMEbC3d5AB7oi67+h4TsQqItC1GVYG58=
github.com/dprotaso/go-yit v0.0.0-20220510233725-9ba8df137936 h1:PRxIJD8XjimM5aTknUK9w6DHLDox2r2M3DI4i2pnd3w=
github.com/dprotaso/go-yit v0.0.0-20220510233725-9ba8df137936/go.mod h1:ttYvX5qlB+mlV1okblJqcSMtR4c52UKxDiX9GRBS8+Q=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=
github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A=
github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE=
github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU=
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.10.2/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk=
github.com/onsi/ginkgo v1.16.4 h1:29JGrr5oVBm5ulCWet69zQkzWipVXIol6ygQUe/EzNc=
github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0=
github.com/onsi/ginkgo/v2 v2.1.3/go.mod h1:vw5CSIxN1JObi/U8gcbwft7ZxR2dgaR70JSE3/PpL4c=
github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo=
github.com/onsi/gomega v1.17.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY=
github.com/onsi/gomega v1.19.0 h1:4ieX6qQjPP/BfC3mpsAtIGGlxTWPeA3Inl/7DtXw1tw=
github.com/onsi/gomega v1.19.0/go.mod h1:LY+I3pBVzYsTBU1AnDwOSxaYi9WoWiqgwooUqq9yPro=
github.com/pb33f/libopenapi v0.15.13 h1:x9G0ZViDR6usizfDZfk/y8mwkvx/fpYLf6zupYcuRuE=
github.com/pb33f/libopenapi v0.15.13/go.mod h1:PEXNwvtT4KNdjrwudp5OYnD1ryqK6uJ68aMNyWvoMuc=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0=
github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/vmware-labs/yaml-jsonpath v0.3.2 h1:/5QKeCBGdsInyDCyVNLbXyilb61MXGi9NP674f9Hobk=
github.com/vmware-labs/yaml-jsonpath v0.3.2/go.mod h1:U6whw1z03QyqgWdgXxvVnQ90zN1BWz5V+51Ewf8k+rQ=
github.com/wk8/go-ordered-map/v2 v2.1.8 h1:5h/BUHu93oj4gIdvHHHGsScSTMijfx5PeYkE/fJgbpc=
github.com/wk8/go-ordered-map/v2 v2.1.8/go.mod h1:5nJHM5DyteebpVlHnWMV0rPz6Zp7+xBAnxjb1X5vnTw=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/exp v0.0.0-20240213143201-ec583247a57a h1:HinSgX1tJRX3KsL//Gxynpw5CTOAIPhgL4W8PNiIpVE=
golang.org/x/exp v0.0.0-20240213143201-ec583247a57a/go.mod h1:CxmFvTBINI24O/j8iY7H1xHzx2i4OsyguNBmN/uPtqc=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk=
golang.org/x/net v0.0.0-20220225172249-27dd8689420f h1:oA4XRj0qtSt8Yo1Zms0CUlsT3KG69V2UGQWPBxujDmc=
golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.6.0 h1:5BMeUDZ7vkXGfEr1x9B4bRcTH4lpkTkpdh0T/J+qjbQ=
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e h1:fLOSk5Q00efkSvAm+4xcoXD+RRmLmmulPn5I3Y9F2EM=
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20191026110619-0b21df46bc1d/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@@ -29,30 +29,67 @@ export const title = '<%- tag %>'
<% }); -%>
</Properties>
<% }; -%>
<% if(operation.requestBody?.content && operation.requestBody?.content['application/json']){ %>
<% if(operation.requestBody && operation.requestBody["content"]["application/json"].schema.properties){ %>
#### Request-Body Parameters
<Properties>
<% components.get(operation.requestBody?.content['application/json'].schema.$ref.split('/').pop())?.parameters.forEach(function(parameter){ %>
<Property name="<%- parameter.name %>" type="<%- parameter.type %>" required=\{<%- parameter.required %>\}
<% if(parameter.enum){ %>
enumList="<%- parameter.enum %>"
<% }; -%>
<% if(parameter.minimum){ %>
min=\{<%- parameter.minimum %>\}
<% }; -%>
<% if(parameter.maximum){ %>
max=\{<%- parameter.maximum %>\}
<% }; -%>
<% if(parameter.minLength){ %>
minLen=\{<%- parameter.minLength %>\}
<% }; -%>
<% if(parameter.maxLength){ %>
maxLen=\{<%- parameter.maxLength %>\}
<% }; -%> >
<%- parameter.description %>
</Property>
<% }); -%>
</Properties>
<%
function renderProperties(properties, required = [], depth = 0) {
%><Properties><%
Object.entries(properties).forEach(([key, value]) => {
let type = value.type;
var isRequired = required.includes(key) ? '{true}' : '{false}';
if (type === 'array' && value.items) {
if (value.items.type === 'object' && value.items.properties) {
type = 'object[]';
} else {
type = value.items.type + '[]';
}
}
%><Property name="<%- key %>" type="<%- type %>" required=<%- isRequired %><%
if(value.enum) {
%> enumList={<%- JSON.stringify(value.enum) %>}<%
}
if(value.minimum !== undefined) {
%> min={<%- value.minimum %>}<%
}
if(value.maximum !== undefined) {
%> max={<%- value.maximum %>}<%
}
if(value.minLength !== undefined) {
%> minLen={<%- value.minLength %>}<%
}
if(value.maxLength !== undefined) {
%> maxLen={<%- value.maxLength %>}<%
}
%>>%>
<% if ((type === 'object' && value.properties) || (type === 'object[]' && value.items.properties)) { %>
<details class="custom-details" open>
<summary><%- value.description || 'More Information' %></summary>
<Properties>
<% if (type === 'object[]') { %>
<% renderProperties(value.items.properties, value.items.required || [], depth + 1); %>
<% } else { %>
<% renderProperties(value.properties, value.required || [], depth + 1); %>
<% } %>
</Properties>
</details>
<% } else { %>
<% if(value.description) { %><%- value.description %><% } %>
<% } %>
</Property>
<% });
%></Properties><%
}
var schema = operation.requestBody["content"]["application/json"].schema;
if(schema && schema.properties) {
renderProperties(schema.properties, schema.required || []);
}
%>
<% }; -%>
</Col>
@@ -65,13 +102,13 @@ curl -X <%- operation.operation.toUpperCase() %> <%- operation.fullPath %> \\<%
-H 'Accept: application/json' \\<% }; -%>
<% if(operation.requestBody?.content && operation.requestBody?.content['application/json']){ %>
-H 'Content-Type: application/json' \\<% }; %>
-H 'Authorization: Token <TOKEN>' <% if(operation.requestBody?.content && operation.requestBody?.content['application/json']){ %>\\\n--data-raw '<%- JSON.stringify(components.get(operation.requestBody?.content['application/json'].schema.$ref?.split('/').pop())?.example, null, 2) -%>'<% }; %>
-H 'Authorization: Token <TOKEN>' <% if(operation.requestBody?.content && operation.requestBody?.content['application/json']){ %>\\\n--data-raw '<%- JSON.stringify(operation.request.example, null, 2) -%>'<% }; %>
\`\`\`
\`\`\`js
const axios = require('axios');
<% if(operation.requestBody?.content && operation.requestBody?.content['application/json']){ -%>
let data = JSON.stringify(<%- JSON.stringify(components.get(operation.requestBody?.content['application/json'].schema.$ref?.split('/').pop())?.example, null, 2) %>);<% }; -%>
let data = JSON.stringify(<%- JSON.stringify(operation.request.example, null, 2) %>);<% }; -%>
let config = {
method: '<%- operation.operation.toLowerCase() %>',
@@ -103,7 +140,7 @@ import json
url = "<%- operation.fullPath %>"
<% if(operation.requestBody?.content && operation.requestBody?.content['application/json']){ -%>
payload = json.dumps(<%- JSON.stringify(components.get(operation.requestBody?.content['application/json'].schema.$ref?.split('/').pop())?.example, null, 2) %>)<% }; -%>
payload = json.dumps(<%- JSON.stringify(operation.request.example, null, 2) %>)<% }; -%>
<% if(true){%>headers: { <% }; -%>
<% if(operation.requestBody?.content && operation.requestBody?.content['application/json']){ %>
@@ -133,7 +170,7 @@ func main() {
url := "<%- operation.fullPath %>"
method := "<%- operation.operation.toUpperCase() %>"
<% if(operation.requestBody?.content && operation.requestBody?.content['application/json']){ %>
payload := strings.NewReader(\`<%- JSON.stringify(components.get(operation.requestBody?.content['application/json'].schema.$ref?.split('/').pop())?.example, null, 2) %>\`)<% }; -%>
payload := strings.NewReader(\`<%- JSON.stringify(operation.request.example, null, 2) %>\`)<% }; -%>
client := &http.Client {
}
@@ -183,7 +220,7 @@ request["Content-Type"] = "application/json"<% }; -%>
request["Accept"] = "application/json"<% }; %>
request["Authorization"] = "Token <TOKEN>"
<% if(operation.requestBody?.content && operation.requestBody?.content['application/json']){ %>
request.body = JSON.dump(<%- JSON.stringify(components.get(operation.requestBody?.content['application/json'].schema.$ref?.split('/').pop())?.example, null, 2) %>)<% }; -%>
request.body = JSON.dump(<%- JSON.stringify(operation.request.example, null, 2) %>)<% }; -%>
response = https.request(request)
puts response.read_body
@@ -194,7 +231,7 @@ OkHttpClient client = new OkHttpClient().newBuilder()
.build();
<% if(operation.requestBody?.content && operation.requestBody?.content['application/json']){ -%>
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, '<%- JSON.stringify(components.get(operation.requestBody?.content['application/json'].schema.$ref?.split('/').pop())?.example, null, 2) %>');<% }; %>
RequestBody body = RequestBody.create(mediaType, '<%- JSON.stringify(operation.request.example, null, 2) %>');<% }; %>
Request request = new Request.Builder()
.url("<%- operation.fullPath %>")
<% if(true){ %>.method("<%- operation.operation.toUpperCase() %>"<% if(operation.requestBody?.content && operation.requestBody?.content['application/json']){ %>, body<% }; %>)<% }; -%>
@@ -222,7 +259,7 @@ curl_setopt_array($curl, array(
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
<% if(true){ %>CURLOPT_CUSTOMREQUEST => '<%- operation.operation.toUpperCase() %>',<% }; -%>
<% if(operation.requestBody?.content && operation.requestBody?.content['application/json']){ %>
CURLOPT_POSTFIELDS => '<%- JSON.stringify(components.get(operation.requestBody?.content['application/json'].schema.$ref?.split('/').pop())?.example, null, 2) %>',<% }; %>
CURLOPT_POSTFIELDS => '<%- JSON.stringify(operation.request.example, null, 2) %>',<% }; %>
<% if(true){ %>CURLOPT_HTTPHEADER => array(<% }; -%>
<% if(operation.requestBody?.content && operation.requestBody?.content['application/json']){ %>
'Content-Type: application/json',<% }; -%>
@@ -239,29 +276,18 @@ echo $response;
\`\`\`
</CodeGroup>
<% operation.responseList.forEach(function(response){ %>
<% if(response?.content && response?.content['application/json']){ %>
<% if(response?.content['application/json'].schema.type === 'array'){ %>
<CodeGroup title="Response">
<% if(operation.response){ %>
<CodeGroup title="Response">
\`\`\`json {{ title: 'Example' }}
<%- JSON.stringify(new Array(components.get(response?.content['application/json'].schema.items.$ref?.split('/').pop())?.example), null, 2) %>
<%- JSON.stringify(operation.response.example, null, 2) %>
\`\`\`
\`\`\`json {{ title: 'Schema' }}
<%- JSON.stringify(new Array(components.get(response?.content['application/json'].schema.items.$ref?.split('/').pop())?.schema), null, 2) %>
<%- JSON.stringify(operation.response.schema, null, 2) %>
\`\`\`
</CodeGroup>
<% } else { %>
<CodeGroup title="Response">
\`\`\`json {{ title: 'Example' }}
<%- JSON.stringify(components.get(response?.content['application/json'].schema.$ref?.split('/').pop())?.example, null, 2) %>
\`\`\`
\`\`\`json {{ title: 'Schema' }}
<%- JSON.stringify(components.get(response?.content['application/json'].schema.$ref?.split('/').pop())?.schema, null, 2) %>
\`\`\`
</CodeGroup>
<% }; -%>
<% }; -%>
<% }); -%>
</CodeGroup>
<% }; %>
</Col>
</Row>