diff --git a/sdk/README.md b/sdk/README.md new file mode 100644 index 0000000..08b1d34 --- /dev/null +++ b/sdk/README.md @@ -0,0 +1,918 @@ + +
+ +addPet + +addPet +--- + **Example** + + ```js + const { data, error } = await name.addPet({ + /** Pet modal, description-Pet object that needs to be added to the store,required-true */ +}) +``` +**Responses** + + +> Error 4XX +```json +{ + "405": { + "description": "Invalid input" + } +} +``` + +###### [Pet](###Pet-modal) +
+ +
+ +updatePet + +updatePet +--- + **Example** + + ```js + const { data, error } = await name.updatePet({ + /** Pet modal, description-Pet object that needs to be added to the store,required-true */ +}) +``` +**Responses** + + +> Error 4XX +```json +{ + "400": { + "description": "Invalid ID supplied" + }, + "404": { + "description": "Pet not found" + }, + "405": { + "description": "Validation exception" + } +} +``` + +###### [Pet](###Pet-modal) +
+ +
+ +findPetsByStatus + +findPetsByStatus +--- + **Example** + + ```js + const { data, error } = await name.findPetsByStatus({ + _params: { + status:array, /** description-Status values that need to be considered for filter,required-true,items-{"type"-"string","enum"-["available","pending","sold"],"default"-"available"},collectionFormat-multi */ + } +}) +``` +**Responses** + + +> Success 2XX +```json +{ + "200": { + "description": "successful operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Pet" + } + } + } +} +``` + +> Error 4XX +```json +{ + "400": { + "description": "Invalid status value" + } +} +``` + +###### [Pet](###Pet-modal) +
+ +
+ +findPetsByTags + +findPetsByTags +--- + **Example** + + ```js + const { data, error } = await name.findPetsByTags({ + _params: { + tags:array, /** description-Tags to filter by,required-true,items-{"type"-"string"},collectionFormat-multi */ + } +}) +``` +**Responses** + + +> Success 2XX +```json +{ + "200": { + "description": "successful operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Pet" + } + } + } +} +``` + +> Error 4XX +```json +{ + "400": { + "description": "Invalid tag value" + } +} +``` + +###### [Pet](###Pet-modal) +
+ +
+ +getPetById + +getPetById +--- + **Example** + + ```js + const { data, error } = await name.getPetById({ + _pathParams: { + petId:integer, /** description-ID of pet to return,required-true,format-int64 */ + } +}) +``` +**Responses** + + +> Success 2XX +```json +{ + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/Pet" + } + } +} +``` + +> Error 4XX +```json +{ + "400": { + "description": "Invalid ID supplied" + }, + "404": { + "description": "Pet not found" + } +} +``` + +###### [Pet](###Pet-modal) +
+ +
+ +updatePetWithForm + +updatePetWithForm +--- + **Example** + + ```js + const { data, error } = await name.updatePetWithForm({ + name:string, /** description-Updated name of the pet,required-false */ + status:string, /** description-Updated status of the pet,required-false */ + _pathParams: { + petId:integer, /** description-ID of pet that needs to be updated,required-true,format-int64 */ + } +}) +``` +**Responses** + + +> Error 4XX +```json +{ + "405": { + "description": "Invalid input" + } +} +``` + +
+ +
+ +deletePet + +deletePet +--- + **Example** + + ```js + const { data, error } = await name.deletePet({ + _pathParams: { + petId:integer, /** description-Pet id to delete,required-true,format-int64 */ + } +}) +``` +**Responses** + + +> Error 4XX +```json +{ + "400": { + "description": "Invalid ID supplied" + }, + "404": { + "description": "Pet not found" + } +} +``` + +
+ +
+ +uploadFile + +uploadFile +--- + **Example** + + ```js + const { data, error } = await name.uploadFile({ + additionalMetadata:string, /** description-Additional data to pass to server,required-false */ + file:file, /** description-file to upload,required-false */ + _pathParams: { + petId:integer, /** description-ID of pet to update,required-true,format-int64 */ + } +}) +``` +**Responses** + + +> Success 2XX +```json +{ + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/ApiResponse" + } + } +} +``` + +###### [ApiResponse](###ApiResponse-modal) +
+ +
+ +getInventory + +getInventory +--- + **Example** + + ```js + const { data, error } = await name.getInventory({ + +}) +``` +**Responses** + + +> Success 2XX +```json +{ + "200": { + "description": "successful operation", + "schema": { + "type": "object", + "additionalProperties": { + "type": "integer", + "format": "int32" + } + } + } +} +``` + +###### [undefined](###undefined-modal) +
+ +
+ +placeOrder + +placeOrder +--- + **Example** + + ```js + const { data, error } = await name.placeOrder({ + /** Order modal, description-order placed for purchasing the pet,required-true */ +}) +``` +**Responses** + + +> Success 2XX +```json +{ + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/Order" + } + } +} +``` + +> Error 4XX +```json +{ + "400": { + "description": "Invalid Order" + } +} +``` + +###### [Order](###Order-modal) [Order](###Order-modal) +
+ +
+ +getOrderById + +getOrderById +--- + **Example** + + ```js + const { data, error } = await name.getOrderById({ + _pathParams: { + orderId:integer, /** description-ID of pet that needs to be fetched,required-true,maximum-10,minimum-1,format-int64 */ + } +}) +``` +**Responses** + + +> Success 2XX +```json +{ + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/Order" + } + } +} +``` + +> Error 4XX +```json +{ + "400": { + "description": "Invalid ID supplied" + }, + "404": { + "description": "Order not found" + } +} +``` + +###### [Order](###Order-modal) +
+ +
+ +deleteOrder + +deleteOrder +--- + **Example** + + ```js + const { data, error } = await name.deleteOrder({ + _pathParams: { + orderId:integer, /** description-ID of the order that needs to be deleted,required-true,minimum-1,format-int64 */ + } +}) +``` +**Responses** + + +> Error 4XX +```json +{ + "400": { + "description": "Invalid ID supplied" + }, + "404": { + "description": "Order not found" + } +} +``` + +
+ +
+ +createUser + +createUser +--- + **Example** + + ```js + const { data, error } = await name.createUser({ + /** User modal, description-Created user object,required-true */ +}) +``` +**Responses** + + +> Default +```json +{ + "default": { + "description": "successful operation" + } +} +``` + +###### [User](###User-modal) +
+ +
+ +createUsersWithArrayInput + +createUsersWithArrayInput +--- + **Example** + + ```js + const { data, error } = await name.createUsersWithArrayInput({ + /** User modal,type - array, description-List of user object,required-true */ +}) +``` +**Responses** + + +> Default +```json +{ + "default": { + "description": "successful operation" + } +} +``` + +###### [User](###User-modal) +
+ +
+ +createUsersWithListInput + +createUsersWithListInput +--- + **Example** + + ```js + const { data, error } = await name.createUsersWithListInput({ + /** User modal,type - array, description-List of user object,required-true */ +}) +``` +**Responses** + + +> Default +```json +{ + "default": { + "description": "successful operation" + } +} +``` + +###### [User](###User-modal) +
+ +
+ +loginUser + +loginUser +--- + **Example** + + ```js + const { data, error } = await name.loginUser({ + _params: { + username:string, /** description-The user name for login,required-true */ + password:string, /** description-The password for login in clear text,required-true */ + } +}) +``` +**Responses** + + +> Success 2XX +```json +{ + "200": { + "description": "successful operation", + "schema": { + "type": "string" + }, + "headers": { + "X-Rate-Limit": { + "type": "integer", + "format": "int32", + "description": "calls per hour allowed by the user" + }, + "X-Expires-After": { + "type": "string", + "format": "date-time", + "description": "date in UTC when token expires" + } + } + } +} +``` + +> Error 4XX +```json +{ + "400": { + "description": "Invalid username/password supplied" + } +} +``` + +###### [undefined](###undefined-modal) +
+ +
+ +logoutUser + +logoutUser +--- + **Example** + + ```js + const { data, error } = await name.logoutUser({ + +}) +``` +**Responses** + + +> Default +```json +{ + "default": { + "description": "successful operation" + } +} +``` + +
+ +
+ +getUserByName + +getUserByName +--- + **Example** + + ```js + const { data, error } = await name.getUserByName({ + _pathParams: { + username:string, /** description-The name that needs to be fetched. Use user1 for testing. ,required-true */ + } +}) +``` +**Responses** + + +> Success 2XX +```json +{ + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/User" + } + } +} +``` + +> Error 4XX +```json +{ + "400": { + "description": "Invalid username supplied" + }, + "404": { + "description": "User not found" + } +} +``` + +###### [User](###User-modal) +
+ +
+ +updateUser + +updateUser +--- + **Example** + + ```js + const { data, error } = await name.updateUser({ + /** User modal, description-Updated user object,required-true */ _pathParams: { + username:string, /** description-name that need to be updated,required-true */ + } +}) +``` +**Responses** + + +> Error 4XX +```json +{ + "400": { + "description": "Invalid user supplied" + }, + "404": { + "description": "User not found" + } +} +``` + +###### [User](###User-modal) +
+ +
+ +deleteUser + +deleteUser +--- + **Example** + + ```js + const { data, error } = await name.deleteUser({ + _pathParams: { + username:string, /** description-The name that needs to be deleted,required-true */ + } +}) +``` +**Responses** + + +> Error 4XX +```json +{ + "400": { + "description": "Invalid username supplied" + }, + "404": { + "description": "User not found" + } +} +``` + +
+ +# Modal Definations + + ### Order-modal + ```json +{ + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "petId": { + "type": "integer", + "format": "int64" + }, + "quantity": { + "type": "integer", + "format": "int32" + }, + "shipDate": { + "type": "string", + "format": "date-time" + }, + "status": { + "type": "string", + "description": "Order Status", + "enum": [ + "placed", + "approved", + "delivered" + ] + }, + "complete": { + "type": "boolean", + "default": false + } + }, + "xml": { + "name": "Order" + } +} +``` + + ### Category-modal + ```json +{ + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + }, + "xml": { + "name": "Category" + } +} +``` + + ### User-modal + ```json +{ + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "username": { + "type": "string" + }, + "firstName": { + "type": "string" + }, + "lastName": { + "type": "string" + }, + "email": { + "type": "string" + }, + "password": { + "type": "string" + }, + "phone": { + "type": "string" + }, + "userStatus": { + "type": "integer", + "format": "int32", + "description": "User Status" + } + }, + "xml": { + "name": "User" + } +} +``` + + ### Tag-modal + ```json +{ + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + }, + "xml": { + "name": "Tag" + } +} +``` + + ### Pet-modal + ```json +{ + "type": "object", + "required": [ + "name", + "photoUrls" + ], + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "category": { + "$ref": "#/definitions/Category" + }, + "name": { + "type": "string", + "example": "doggie" + }, + "photoUrls": { + "type": "array", + "xml": { + "name": "photoUrl", + "wrapped": true + }, + "items": { + "type": "string" + } + }, + "tags": { + "type": "array", + "xml": { + "name": "tag", + "wrapped": true + }, + "items": { + "$ref": "#/definitions/Tag" + } + }, + "status": { + "type": "string", + "description": "pet status in the store", + "enum": [ + "available", + "pending", + "sold" + ] + } + }, + "xml": { + "name": "Pet" + } +} +``` + + ### ApiResponse-modal + ```json +{ + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "type": { + "type": "string" + }, + "message": { + "type": "string" + } + } +} +``` diff --git a/sdk/yash.js b/sdk/yash.js new file mode 100644 index 0000000..2f07ff7 --- /dev/null +++ b/sdk/yash.js @@ -0,0 +1,314 @@ + +import axios from "axios"; +import { transformOperations } from './transformOperations' +export default class Yash { + constructor( headersObj ={}) { + this.version ='1.0.0' + this.requiredHeaders = 'name,lastname'; + this.optionalHeaders = 'token'; + this.name = "Yash"; + if(this.requiredHeaders){ + this.requiredHeaders.split(',').forEach(header => { + if (Object.keys(headersObj).indexOf(header) < 0) { + throw Error("All required header to initiate not passed"); + } + }); + } + this.configs = { + baseURL: "https://yash.ocm", + headers: { + ...headersObj, + } + } + const instance = axios.create({ + ...this.configs + }); + // get authorization on every request + instance.interceptors.request.use( + configs => { + if(this.optionalHeaders){ + this.optionalHeaders.split(',').forEach(header => { + this.configs.headers[header] = this.getHeader(header); + }); + } + configs.headers = this.configs.headers + configs.baseURL = this.configs.baseURL + return configs + }, + error => Promise.reject(error) + ); + this.axiosInstance = instance; + } + + fetchApi({ + isFormData, + method, + _data, + _url, + _params = {}, + transformResponse, + _pathParams = [], + headerConfigs = {} + }) { + return new Promise(async resolve => { + const obj = { + error: null, + data: null + }; + let data = _data; + if (isFormData) { + const formdata = new FormData(); + Object.entries(_data).forEach(arr => { + formdata.append(arr[0], arr[1]); + }); + data = formdata; + } + let url = _url; + if (Object.keys(_pathParams).length) { + Object.entries(_pathParams).forEach( + arr => (url = url.replace("{" + arr[0] + "}", arr[1])) + ); + } + try { + const resObj = await this.axiosInstance({ + url, + method, + data, + ...(transformResponse ? { transformResponse } : {}), + ...(Object.keys(_params).length ? { params: _params } : {}), + ...(isFormData + ? { + headers: { + "Content-Type": "multipart/form-data" + } + } + : {}) + }); + obj.data = resObj.data; + resolve(obj); + } catch (error) { + if (error.response) { + obj.error = error.response.data; + } else if (error.request) { + obj.error = error.request; + } else { + obj.error = error.message; + } + resolve(obj); + } + }); + } + + // --utils method for sdk class + setHeader(key, value) { + // Set optional header + this.configs.header[key] = value; + window.localStorage.setItem(key, value); + } + + // eslint-disable-next-line + getHeader(key) { + //Get header method + //Helps to check if the required header is present or not + return window.localStorage.getItem(key); + } + + // --utils method for sdk class + clearHeader(key) { + // Clear optional header + this.configs.header[key] = ''; + window.localStorage.removeItem(key); + } + + setBaseUrl(url) { + //Set BaseUrl + //Helps when we require to change the base url, without modifying the sdk code + + this.configs = { + ...this.configs, + baseURL: url + }; + } + // ------All api method---- + + + addPet({ _params,_pathParams,..._data } = {}) { + return this.fetchApi({ + method: "POST", + _url: '/pet', + _data, + _params, + }); + } + + updatePet({ _params,_pathParams,..._data } = {}) { + return this.fetchApi({ + method: "PUT", + _url: '/pet', + _data, + _params, + }); + } + + findPetsByStatus({ _params,_pathParams, } = {}) { + return this.fetchApi({ + method: "GET", + _url: '/pet/findByStatus', + _params, + }); + } + + findPetsByTags({ _params,_pathParams, } = {}) { + return this.fetchApi({ + method: "GET", + _url: '/pet/findByTags', + _params, + }); + } + + getPetById({ _params,_pathParams, } = {}) { + return this.fetchApi({ + method: "GET", + _url: '/pet/{petId}', + _params, + _pathParams, + }); + } + + updatePetWithForm({ _params,_pathParams,..._data } = {}) { + return this.fetchApi({ + method: "POST", + _url: '/pet/{petId}', + _data, + _params, + _pathParams, + }); + } + + deletePet({ _params,_pathParams, } = {}) { + return this.fetchApi({ + method: "DELETE", + _url: '/pet/{petId}', + _params, + _pathParams, + }); + } + + uploadFile({ _params,_pathParams,..._data } = {}) { + return this.fetchApi({ + method: "POST", + isFormData: true, + _url: '/pet/{petId}/uploadImage', + _data, + _params, + _pathParams, + }); + } + + getInventory({ _params,_pathParams, } = {}) { + return this.fetchApi({ + method: "GET", + _url: '/store/inventory', + _params, + }); + } + + placeOrder({ _params,_pathParams,..._data } = {}) { + return this.fetchApi({ + method: "POST", + _url: '/store/order', + _data, + _params, + }); + } + + getOrderById({ _params,_pathParams, } = {}) { + return this.fetchApi({ + method: "GET", + _url: '/store/order/{orderId}', + _params, + _pathParams, + }); + } + + deleteOrder({ _params,_pathParams, } = {}) { + return this.fetchApi({ + method: "DELETE", + _url: '/store/order/{orderId}', + _params, + _pathParams, + }); + } + + createUser({ _params,_pathParams,..._data } = {}) { + return this.fetchApi({ + method: "POST", + _url: '/user', + _data, + _params, + }); + } + + createUsersWithArrayInput({ _params,_pathParams,..._data } = {}) { + return this.fetchApi({ + method: "POST", + _url: '/user/createWithArray', + _data, + _params, + }); + } + + createUsersWithListInput({ _params,_pathParams,..._data } = {}) { + return this.fetchApi({ + method: "POST", + _url: '/user/createWithList', + _data, + _params, + }); + } + + loginUser({ _params,_pathParams, } = {}) { + return this.fetchApi({ + method: "GET", + _url: '/user/login', + _params, + }); + } + + logoutUser({ _params,_pathParams, } = {}) { + return this.fetchApi({ + method: "GET", + _url: '/user/logout', + _params, + }); + } + + getUserByName({ _params,_pathParams, } = {}) { + return this.fetchApi({ + method: "GET", + _url: '/user/{username}', + _params, + _pathParams, + }); + } + + updateUser({ _params,_pathParams,..._data } = {}) { + return this.fetchApi({ + method: "PUT", + _url: '/user/{username}', + _data, + _params, + _pathParams, + }); + } + + deleteUser({ _params,_pathParams, } = {}) { + return this.fetchApi({ + method: "DELETE", + _url: '/user/{username}', + _params, + _pathParams, + }); + } + +} diff --git a/src/codeStrings.js b/src/codeStrings.js index 4c1c9c5..995311b 100644 --- a/src/codeStrings.js +++ b/src/codeStrings.js @@ -1,3 +1,4 @@ +import chalk from "chalk"; import { notEmptyObj } from "./utils"; const stringOne = ({ sdkName, @@ -180,3 +181,26 @@ const endString = ` } `; export { stringOne, functionSignature, endString }; + +//MARKDOWN +export const markdownStartString = ({ name, operationName }) => ` +
+ +${operationName} + +${operationName} +--- + **Example** + + \`\`\`js + const { data, error } = await name.${operationName}({ +`; +export const markdownCodeBlockEnd = () => ` +}) +\`\`\``; +export const appendModalLink = modal => ` [${modal}](###${modal}-modal) `; +export const operationMarkdownEnd = () => ` +
+`; +export const responseMarkdown = ({ resCode, json }) => + `\n> ${resCode}\n\`\`\`json\n${JSON.stringify(json, null, 2)}\n\`\`\`\n`; diff --git a/src/codgen.js b/src/codgen.js index 8d155ae..df5e1b1 100644 --- a/src/codgen.js +++ b/src/codgen.js @@ -1,11 +1,22 @@ import chalk from "chalk"; import fs from "fs"; -import { stringOne, functionSignature, endString } from "./codeStrings"; +import { + stringOne, + functionSignature, + endString, + markdownStartString, + appendModalLink, + markdownCodeBlockEnd, + operationMarkdownEnd, + responseMarkdown +} from "./codeStrings"; import { extractPathParams, toCamelCase, toTitleCase, - notEmptyObj + notEmptyObj, + getDefinitionKey, + removeKeys } from "./utils"; import cp from "cp"; @@ -16,6 +27,16 @@ const isGoJson = json => { const isSwaggerJson = json => { return json && json.swagger; }; +const stringifyObj = obj => + Object.keys(obj) + .map(key => { + return `${key}:${ + typeof obj[key] !== "object" ? obj[key] : JSON.stringify(obj[key]) + }`; + }) + .join() + .replace(/:/g, "-"); + export function generateSDK({ jsonFile, jsFile, @@ -43,6 +64,7 @@ export function generateSDK({ let isSwaggerGenerated = isSwaggerJson(_jsonFile); let isGoGenerated = isGoJson(_jsonFile); const storeJsCodeInThisArr = []; + let storeMarkdown = []; storeJsCodeInThisArr.push( stringOne({ @@ -84,6 +106,132 @@ export function generateSDK({ const operationName = methodData.operationId; const consumes = methodData.consumes || []; const isFormData = consumes.includes("multipart/form-data"); + const thisOperationBodyParamsModals = []; + const thisOperationResponesModals = []; + + const bodyParamsDocGenerators = params => { + // lets group body/formData params,path params and query params together + // + const body = params.filter(param => + ["body", "formData"].includes(param.in) ? param : false + ); + const pathParams = params.filter(param => param.in === "path"); + const qparams = params.filter(param => param.in === "query"); + // + storeMarkdown.push(markdownStartString({ operationName, name })); + + // can't destruct "in" params bcoz a reserved keyword; + body.forEach(({ name, schema, type, ...other }) => { + // if name is body indicates it has a params for which a modal exist in definations + // so we just comment meta info here and link to that modal below example code + + if (name === "body") { + const definition = + _jsonFile.definitions[getDefinitionKey(schema)]; + storeMarkdown.push( + ` /** ${getDefinitionKey(schema)} modal,${ + schema.type ? "type - " + schema.type + "," : "" + } ${stringifyObj(removeKeys(other, "in"))} */` + ); + thisOperationBodyParamsModals.push(getDefinitionKey(schema)); + } else { + // else just name: type of param, stringify other info and comment // if there is a object in other info just JSON.stringify + storeMarkdown.push( + ` ${name}:${type}, /** ${stringifyObj({ + ...removeKeys(other, "in") + })} */\n` + ); + } + }); + if (pathParams.length) { + storeMarkdown.push(` _pathParams: {\n`); + pathParams.forEach(({ name, type, ...other }) => { + storeMarkdown.push( + ` ${name}:${type}, /** ${stringifyObj({ + ...removeKeys(other, "in") + })} */ \n` + ); + }); + storeMarkdown.push(` }`); + } + if (qparams.length) { + storeMarkdown.push(` _params: {\n`); + qparams.forEach(({ name, type, ...other }) => { + storeMarkdown.push( + ` ${name}:${type}, /** ${stringifyObj({ + ...removeKeys(other, "in") + })} */ \n` + ); + }); + storeMarkdown.push(` }`); + } + storeMarkdown.push(markdownCodeBlockEnd()); + }; + const responsesDocsGenerators = responses => { + const twoXX = {}; + const fourXX = {}; + const fiveXX = {}; + const defaultResponse = {}; + Object.keys(responses).forEach(key => { + if (responses[key] && responses[key].schema) { + thisOperationResponesModals.push( + getDefinitionKey(responses[key].schema) + ); + } + if (key.includes("20")) { + twoXX[key] = responses[key]; + } + if (key.includes("40")) { + fourXX[key] = responses[key]; + } + if (key.includes("50")) { + fiveXX[key] = responses[key]; + } + if (key.includes("default")) { + defaultResponse[key] = responses[key]; + } + }); + storeMarkdown.push( + `\n**Responses**\n + ` + ); + if (Object.keys(defaultResponse).length) { + storeMarkdown.push( + responseMarkdown({ resCode: "Default", json: defaultResponse }) + ); + } + if (Object.keys(twoXX).length) { + storeMarkdown.push( + responseMarkdown({ resCode: "Success 2XX", json: twoXX }) + ); + } + if (Object.keys(fourXX).length) { + storeMarkdown.push( + responseMarkdown({ resCode: "Error 4XX", json: fourXX }) + ); + } + if (Object.keys(fiveXX).length) { + storeMarkdown.push( + responseMarkdown({ resCode: "Error 5XX", json: fivXX }) + ); + } + }; + + bodyParamsDocGenerators(methodData.parameters); + responsesDocsGenerators(methodData.responses); + const thisOperationsModals = [ + ...thisOperationBodyParamsModals, + ...thisOperationResponesModals + ]; + if (thisOperationsModals.length) { + storeMarkdown.push(`\n###### `); + thisOperationsModals.forEach(a => + storeMarkdown.push(appendModalLink(a)) + ); + } + + storeMarkdown.push(operationMarkdownEnd()); + const operationFunction = functionSignature({ hasPathParams: extractPathParams(url).length, operationName, @@ -133,6 +281,23 @@ export function generateSDK({ process.exit(1); } } + + if (isSwaggerGenerated) { + const generateModalsReadeMe = json => { + const definitions = json.definitions; + storeMarkdown.push(`\n# Modal Definations\n`); + Object.keys(definitions).forEach(key => { + storeMarkdown.push( + `\n ### ${key}-modal\n \`\`\`json\n${JSON.stringify( + definitions[key], + null, + 2 + )}\n\`\`\`\n` + ); + }); + }; + generateModalsReadeMe(_jsonFile); + } storeJsCodeInThisArr.push(endString); const dir = "sdk"; if (!fs.existsSync(dir)) { @@ -143,6 +308,9 @@ export function generateSDK({ if (err) throw err; }); } + fs.writeFile("sdk/README.md", storeMarkdown.join(""), err => { + if (err) throw err; + }); fs.writeFile("sdk/" + name + ".js", storeJsCodeInThisArr.join(""), err => { if (err) throw err; diff --git a/src/utils.js b/src/utils.js index ffa0d19..7ae96fd 100644 --- a/src/utils.js +++ b/src/utils.js @@ -1,4 +1,5 @@ import chalk from "chalk"; +import { isArray } from "util"; export function toCamelCase(s = "") { return s @@ -53,3 +54,17 @@ export const printManPage = () => { `; console.log(manPage); }; +export const getDefinitionKey = a => + (a["$ref"] && a["$ref"] && a["$ref"].split("#/definitions/")[1]) || + (a && + a.items && + a.items["$ref"] && + a.items["$ref"].split("#/definitions/")[1]); + +export const removeKeys = (obj, ...a) => { + let abc = {}; + Object.keys(obj).forEach(key => + (a || []).includes(key) ? undefined : (abc[key] = obj[key]) + ); + return abc; +};