Skip to content

Commit

Permalink
Implemented openapi-to-postman as a Service instead of using execShel…
Browse files Browse the repository at this point in the history
…lCommand
  • Loading branch information
Tim committed May 24, 2021
1 parent 0780908 commit fe7a29f
Show file tree
Hide file tree
Showing 2 changed files with 97 additions and 12 deletions.
69 changes: 69 additions & 0 deletions src/application/OpenApiToPostmanService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import oaConverter from 'openapi-to-postmanv2'
import path from 'path'
import fs from 'fs-extra'

export class OpenApiToPostmanService {
/**
* Helper function for the CLI to convert OpenApi data input
* (ported from https://github.com/postmanlabs/openapi-to-postman)
* @param {String} openApiObj - OpenApi spec file used for conversion input
* @param options - OpenApi to Postman conversion options
* @returns {string}
*/
async convert(openApiObj: string, options: any): Promise<string> {
return await new Promise((resolve, reject) => {

let inputFile = path.resolve(options.inputFile)
openApiObj = fs.readFileSync(inputFile, 'utf8')

// apply options from config file if present
if (options.configFile) {
let configFile = path.resolve(options.configFile)
// console.log('Options Config file: ', configFile)
let configFileOptions = JSON.parse(fs.readFileSync(configFile, 'utf8'))
options = Object.assign({}, options, configFileOptions)
}

// override options provided via cli
// if (definedOptions && !_.isEmpty(definedOptions)) {
// options = definedOptions;
// }

if (options.testsuiteFile) {
let testsuiteFile = path.resolve(options.testsuiteFile)
// console.log('Testsuite file: ', testsuiteFile)
options.testSuite = true
options.testSuiteSettings = JSON.parse(fs.readFileSync(testsuiteFile, 'utf8'))
}

// Convert OpenApi to Postman collection
oaConverter.convert({
type: 'string',
data: openApiObj
}, options, (err, status) => {
if (err) {
reject(err)
}
if (!status.result) {
// console.log(status.reason)
reject(status.reason)
} else if (options.outputFile) {
let filePath = path.resolve(options.outputFile)
// console.log('Writing to Postman collection: ', options.prettyPrintFlag, filePath, status) // eslint-disable-line no-console
fs.writeFile(filePath, JSON.stringify(status.output[0].data, null, 4), (err) => {
if (err) {
console.log('Could not write to file', err)
reject(err)
}
console.log('\x1b[32m%s\x1b[0m', '\n ✅ Conversion successful, Postman collection written to file\n ')
})
// Return Postman collection
resolve(status.output[0].data)
} else {
// console.log(status.output[0].data)
resolve(status.output[0].data)
}
})
})
}
}
40 changes: 28 additions & 12 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,14 @@ import fs from 'fs-extra'
import emoji from 'node-emoji'
import path from 'path'
import { CollectionDefinition } from 'postman-collection'
import * as readline from 'readline'
import yargs from 'yargs'
import { DownloadService } from './application/DownloadService'
import { PostmanService } from './application/PostmanService'
import { OpenApiToPostmanService } from './application/OpenApiToPostmanService'
import {
cleanupTestSchemaDefs,
clearTmpDirectory,
disableOptionalParams,
execShellCommand,
getConfig,
injectEnvVariables,
injectPreRequest,
Expand Down Expand Up @@ -187,21 +186,38 @@ require('dotenv').config()
// --- openapi-to-postman - Transform OpenApi to Postman collection, with optional test suite generation
process.stdout.write(`\r 🕓 Starting OpenApi to Postman conversion ...`)
const tmpCollectionFile = `${process.cwd()}/tmp/working/tmpCollection.json`
const collectionGenerated = await execShellCommand(
`openapi2postmanv2 -s ${openApiSpec} -o ${tmpCollectionFile} -p ${
includeTests && `-g ${testSuiteConfigFile}`
} -c ${postmanConfigFile}`
)
readline.clearLine(process.stdout, 0) // clear previous stdout message

if (!collectionGenerated) {
throw new Error(`Collection generation failed.`)
const oaToPostman = new OpenApiToPostmanService()
const oaToPostmanConfig = {
inputFile: openApiSpec,
outputFile: tmpCollectionFile,
prettyPrintFlag: true,
configFile: postmanConfigFile,
testSuite: includeTests || false,
testsuiteFile: testSuiteConfigFile,
testFlag: tmpCollectionFile
}
const collectionGenerated = await oaToPostman.convert(openApiSpec, oaToPostmanConfig)
.catch(function(err) {
console.log('error: ', err)
throw new Error(`Collection generation failed.`)
})

// const collectionGenerated = await execShellCommand(
// `openapi2postmanv2 -s ${openApiSpec} -o ${tmpCollectionFile} -p ${
// includeTests && `-g ${testSuiteConfigFile}`
// } -c ${postmanConfigFile}`
// )

// if (!collectionGenerated) {
// throw new Error(`Collection generation failed.`)
// }

// --- Portman - load generated Postman collection
let collectionJson = {}
try {
collectionJson = require(`${tmpCollectionFile}`) as CollectionDefinition
collectionJson = collectionGenerated as CollectionDefinition
// collectionJson = require(`${tmpCollectionFile}`) as CollectionDefinition
} catch (err) {
console.error('\x1b[31m', 'Collection generation failed ')
process.exit(0)
Expand Down Expand Up @@ -278,7 +294,7 @@ require('dotenv').config()

// --- Portman - Upload Postman collection to Postman app
if (syncToPostman) {
process.stdout.write(`\r ⚡ Uploading to Postman ...`)
console.log(`⚡ Uploading to Postman ...`)
const collectionIdentification = options.p ? options.p : collection.info.name
const postman = new PostmanService()
if (postman.isGuid(collectionIdentification)) {
Expand Down

0 comments on commit fe7a29f

Please sign in to comment.