Skip to content

Commit

Permalink
Merge pull request #11 from flotiq/feature/24580-lambda-generation
Browse files Browse the repository at this point in the history
24580 - codegen with lambda
  • Loading branch information
trzcina authored May 29, 2024
2 parents 9309093 + 0cd2196 commit c56814e
Show file tree
Hide file tree
Showing 5 changed files with 277 additions and 203 deletions.
2 changes: 1 addition & 1 deletion clean_duplicate_import.sh
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#!/bin/bash

file_patterns="src/models/*WithoutInternal.ts src/models/*WithoutRequired.ts src/models/*WithoutInternalAllOf*.ts"
file_patterns="src/models/*WithoutInternal.ts src/models/*WithoutRequired.ts"
delete_line="import { DataSource, DataSourceFromJSON } from './DataSource';"

escaped_delete_line=$(printf '%s\n' "$delete_line" | sed 's:[][\/.^$*]:\\&:g')
Expand Down
83 changes: 44 additions & 39 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,32 @@ const fs = require('fs');
const path = require('path');
const dotenv = require('dotenv');
const yargs = require('yargs');
const admZip = require('adm-zip')

const compileToJsFlag = "compiled-js";

async function lambdaInvoke(url) {

try {
const response = await axios.get(url, { responseType: 'arraybuffer' })
const decoded = Buffer.from(response.data, 'base64')
return decoded;

} catch (error) {
if (error.response) {
const decoder = new TextDecoder('utf-8')
const errorData = JSON.parse(decoder.decode(error.response.data))

console.error('Error fetching data: ', errorData.message);
process.exit(1);
} else {
console.error('Error fetching data: unknown error');
process.exit(1);
}
}
}


const argv = yargs(process.argv)
.command("flotiq-codegen-ts generate [options]", "Generate api integration for your Flotiq project", {})
.usage("Use flotiq-codegen-ts generates typescript Fetch API integration for your Flotiq project.")
Expand All @@ -21,23 +44,6 @@ const argv = yargs(process.argv)
}).help().alias("help", "h").argv;


async function downloadSchema(url) {
const response = await axios.get(url);
// console.log(response.data);
return JSON.stringify(response.data);
}

async function modifySchema(schema) {
// Example: Replace a string in the schema
const schema1 = schema + "";
return schema1.replace(/Content: /g, '');
}

async function saveSchemaToFile(schema, filename) {
const filePath = path.join(__dirname, filename);
fs.writeFileSync(filePath, schema);
return filePath;
}

async function confirm(msg) {
const response = await inquirer.prompt([
Expand Down Expand Up @@ -77,7 +83,7 @@ async function main() {

if (fs.existsSync(filepath)) {
dotenv.config({ path: filepath})

if (process.env[envName]) {

query = await confirm(`${envName} found in env file. \n Do you want to use API key from ${file}?`)
Expand All @@ -103,39 +109,38 @@ async function main() {

}


const schemaUrl = `https://api.flotiq.com/api/v1/open-api-schema.json?user_only=1&hydrate=1&auth_token=${apiKey}`;
const compileToJs = argv[compileToJsFlag];

try {
console.log('Downloading OpenAPI schema...');
const schema = await downloadSchema(schemaUrl);
const modifiedSchema = await modifySchema(schema);
const schemaFile = await saveSchemaToFile(modifiedSchema, 'schema.json');
// Correctly resolving the path to cfg.json
const configPath = path.join(__dirname, 'cfg.json');
const outputPath = path.join(process.cwd(), 'flotiqApi');

// Generate command
// const command = `openapi-generator-cli generate -i ${schemaFile} -g typescript-fetch --additional-properties=apiKey=${apiKey} -o ./generated-api`;
const genCommand = `openapi-generator-cli --openapitools ${configPath} generate`;
const lambdaUrl = `https://0c8judkapg.execute-api.us-east-1.amazonaws.com/default/codegen-ts?token=${apiKey}`
var zip = new admZip(await lambdaInvoke(lambdaUrl))
const localPath = path.join(__dirname, 'flotiqApi');
const outputPath = path.join(process.cwd(), 'flotiqApi');
console.log('Generating client from schema...');

if(!compileToJs){
zip.extractAllTo(outputPath);
getCleanUpCommand(outputPath);
console.log('Client generated successfully!');
return;
}

zip.extractAllTo(localPath)

// compile api to js command
const buildJsCommand = `sh build_to_js.sh`;

console.log('Generating client from schema...');
execSync(genCommand, {stdio: 'ignore', cwd: __dirname});
console.log('Compiling to javascript...');
getCleanUpCommand();

if (compileToJs) {
console.log('Compiling to javascript...');
getCleanUpCommand();
execSync(buildJsCommand, {stdio: 'ignore', cwd: __dirname});
getMoveCommand(outputPath, true);
} else {
getMoveCommand(outputPath);
getCleanUpCommand(outputPath);
}
execSync(buildJsCommand, {stdio: 'ignore', cwd: __dirname});
getMoveCommand(outputPath, true);

console.log('Client generated successfully!');

} catch (error) {
console.error('An error occurred:', error);
process.exit(1);
Expand Down
63 changes: 63 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"license": "ISC",
"dependencies": {
"@openapitools/openapi-generator-cli": "^2.13.1",
"adm-zip": "^0.5.12",
"axios": "^1.6.8",
"dotenv": "^16.4.5",
"inquirer": "^8.2.0",
Expand Down
Loading

0 comments on commit c56814e

Please sign in to comment.