Skip to content

Commit

Permalink
Merge pull request #25 from flotiq/feature/24627-codegen-watch-param
Browse files Browse the repository at this point in the history
#24627 codegen watch param
  • Loading branch information
trzcina authored Jun 13, 2024
2 parents e850b81 + 588f0a3 commit 408ca4b
Show file tree
Hide file tree
Showing 8 changed files with 219 additions and 65 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
node_modules
flotiqApi
flotiqApiBuildJs
src/codegen-ts-watch-config.json
49 changes: 39 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ flotiq-codegen-ts

This package generates Typescript Fetch API integration for your Flotiq project.


## See it in action!

![Flotiq API accessible through TypeScript](./.images/flotiq-typescript-intellisense-2.gif)
Expand All @@ -23,20 +22,23 @@ npx flotiq-codegen-ts generate

## Usage

Run `flotiq-codegen-ts`, provide your API key and wait for your Typescript code to be generated in the `flotiqApi` folder.
Run `flotiq-codegen-ts`, provide your API key and wait for your Typescript code to be generated in the `flotiqApi`
folder.
Then start using it:

```javascript
import { FlotiqApi } from 'flotiqApi/src';
import {FlotiqApi} from 'flotiqApi/src';

const FLOTIQ_RO_API_KEY = 'YOUR_API_KEY';
const flotiq = new FlotiqApi(FLOTIQ_RO_API_KEY);

// Use your IDE IntelliSense to work with types & api endpoints!

const eventList = await flotiq.EventAPI.list({limit:100});
const eventList = await flotiq.EventAPI.list({limit: 100});
```

## Usage in JS project

If you wish to use `flotiqApi` in JS project you can use `flotiq-codegen-ts` with `--compiled-js` flag

```
Expand All @@ -47,26 +49,53 @@ Now set of compiled `d.ts` and `.js` will be automatically generated in your `fl
You can now import and use the API in your project:

```javascript
import { FlotiqApi } from 'flotiqApi/index';
import {FlotiqApi} from 'flotiqApi/index';

const FLOTIQ_RO_API_KEY = 'YOUR_API_KEY';
const flotiq = new FlotiqApi(FLOTIQ_RO_API_KEY);

// Use your IDE IntelliSense to work with types & api endpoints!

const eventList = await flotiq.EventAPI.list({limit:100});
const eventList = await flotiq.EventAPI.list({limit: 100});
```

## Watching for changes in your data in Flotiq

The `flotiq-codegen-ts` tool offers a feature to continuously monitor changes in the content on your Flotiq account. It
automatically regenerates the SDK whenever changes are detected, ensuring that developers always have the most
up-to-date data models in their IDE without manual intervention.

The `--watch` option for `flotiq-codegen-ts` ensures your SDK stays up-to-date by automatically monitoring and regenerating
based on content changes.

If you want to see changes made in Flotiq by your content editor in your IDE, use `flotiq-codegen-ts` with `--watch`
flag

```
npx flotiq-codegen-ts generate --watch
```

or, if you want your SDK to be directly compiled to JavaScript use `flotiq-codegen-ts` with flags `--watch`
and `--compiled-js`

```
npx flotiq-codegen-ts generate --watch --compiled-js
```

Now, `flotiq-codegen-ts` will check for changes in your Flotiq content every 10 seconds. If changes are detected, it will
automatically regenerate your SDK to reflect the updates.

## Developing

To start developing this project, follow these steps:

1. Clone the repository `git clone [email protected]:flotiq/flotiq-codegen-ts.git`
1. Clone the repository `git clone [email protected]:flotiq/flotiq-codegen-ts.git`
2. Install dependencies `yarn install`
3. Run the project `yarn start`

## Collaborating

If you wish to talk with us about this project, feel free to hop on our [![Discord Chat](https://img.shields.io/discord/682699728454025410.svg)](https://discord.gg/FwXcHnX).
If you wish to talk with us about this project, feel free to hop on
our [![Discord Chat](https://img.shields.io/discord/682699728454025410.svg)](https://discord.gg/FwXcHnX).

If you found a bug, please report it in [issues](https://github.com/flotiq/flotiq-codegen-ts).
196 changes: 142 additions & 54 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,27 @@ const dotenv = require('dotenv');
const yargs = require('yargs');
const admZip = require('adm-zip');
const os = require('os');
const buildToJs = require("./build_to_js");
const cleanDuplicateImport = require("./clean_duplicate_import");
const buildToJs = require("./src/build_to_js");
const cleanDuplicateImport = require("./src/clean_duplicate_import");
const loading = require('loading-cli');

const compileToJsFlag = "compiled-js";
const watchFlag = "watch";
const watchInterval = 10000;

const CLI_GREEN = "\x1b[32m%s\x1b[0m";
const CLI_BLUE = "\x1b[36m%s\x1b[0m";

const colorYellow = (str) => {
return `\x1b[33m${str}\x1b[0m`;
}

const getWorkingPath = () => fs.mkdtempSync(`${os.tmpdir()}${path.sep}`);

const loader = loading({
text: colorYellow("Watching for changes ..."), color: "yellow"
});

async function lambdaInvoke(url) {

try {
Expand All @@ -41,6 +52,13 @@ async function lambdaInvoke(url) {
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.")
.option(watchFlag, {
description: "Listen for changes in Flotiq Api Schema, and regenerate SDK after detected change",
alias: "",
type: "boolean",
default: false,
demandOption: false,
})
.option(compileToJsFlag, {
description: "Generates Fetch API integration compiled to JavaScript",
alias: "",
Expand All @@ -51,61 +69,13 @@ const argv = yargs(process.argv)


async function confirm(msg) {
const response = await inquirer.prompt([
{
name: 'confirmation',
type: 'confirm',
message: msg
}
]);
const response = await inquirer.prompt([{
name: 'confirmation', type: 'confirm', message: msg
}]);
return response.confirmation;
}

async function main() {

const envfiles = [
'.env',
'.env.local',
'.env.development',
'env.local',
'env.development'
];
const envName = "FLOTIQ_API_KEY";
let apiKey = ''
for (const file of envfiles) {
const filepath = path.join(process.cwd(), file)

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

if (process.env[envName]) {

query = await confirm(`${envName} found in '${file}' file. \n Do you want to use API key from ${file}?`)
if (query) {
//using API key from file
apiKey = process.env[envName];
break;
}
}
}
}

if (!apiKey) {
const answers = await inquirer.prompt([
{
type: 'input',
name: 'apiKey',
message: 'Please enter your Flotiq API key:',
validate: input => !!input || 'API key cannot be empty.'
}
]);

apiKey = answers.apiKey;

}

const compileToJs = argv[compileToJsFlag];

async function generateSDK(apiKey, compileToJs) {
try {
console.log('Generating client from schema...');

Expand Down Expand Up @@ -144,4 +114,122 @@ async function main() {
}
}

async function checkForChanges(apiKey) {
const updatedAtResult = await makeRequest(apiKey, 'updatedAt');
const createdAtResult = await makeRequest(apiKey, 'createdAt');

return {
updatedAt: updatedAtResult.data[0].updatedAt, createdAt: createdAtResult.data[0].createdAt,
}
}


async function makeRequest(apiKey, orderBy) {
const FILTERS_URL = "https://api.flotiq.com/api/v1/internal/contenttype"

try {
const response = await axios.get(FILTERS_URL, {
params: {
order_by: orderBy, limit: 1, order_direction: 'desc'
}, headers: {
['X-AUTH-TOKEN']: apiKey
}
});

return response.data;
} catch (error) {
loader.stop();
loader.clear();
console.error('An error occurred in listening for changes. Details: ', error.response.data);
process.exit(1);
}
}

async function watchChanges(apiKey, compileToJs) {
const configFile = path.join(__dirname, '/src/codegen-ts-watch-config.json');
const data = await checkForChanges(apiKey);
if (!fce.existsSync(configFile)) {
fce.createFileSync(configFile);
fce.writeJsonSync(configFile, data);
}

const configData = fce.readJsonSync(configFile);

if (JSON.stringify(data) === JSON.stringify(configData)) {
return;
}

loader.stop();
loader.succeed('Detected changes in content!')
console.log(CLI_GREEN, 'Detected changes in content!');

fce.writeJsonSync(configFile, data);
await generateSDK(apiKey, compileToJs);
loader.start();
}


async function main() {
const envfiles = ['.env', '.env.local', '.env.development', 'env.local', 'env.development'];
const envName = "FLOTIQ_API_KEY";
let apiKey = ''
for (const file of envfiles) {
const filepath = path.join(process.cwd(), file)

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

if (process.env[envName]) {

query = await confirm(`${envName} found in '${file}' file. \n Do you want to use API key from ${file}?`)
if (query) {
//using API key from file
apiKey = process.env[envName];
break;
}
}
}
}

if (!apiKey) {
const answers = await inquirer.prompt([{
type: 'input',
name: 'apiKey',
message: 'Please enter your Flotiq API key:',
validate: input => !!input || 'API key cannot be empty.'
}]);

apiKey = answers.apiKey;

}

const compileToJs = argv[compileToJsFlag];
const watch = argv[watchFlag];

if (!watch) {
await generateSDK(apiKey, compileToJs);
return;
}

loader.start();
await watchChanges(apiKey, compileToJs);
setInterval(
await watchChanges,
watchInterval,
apiKey,
compileToJs
);
}

/**
* SIGINT (ctrl + c) handler
* we have to stop the handler, otherwise it causes disappear of console cursor
*/
process.on('SIGINT', function () {
loader.stop();
loader.clear();
console.log(colorYellow("Application terminated !"));
process.exit(0);
});

main();
23 changes: 23 additions & 0 deletions package-lock.json

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

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "flotiq-codegen-ts",
"version": "1.2.0",
"version": "1.2.1",
"description": "CLI tool to generate API clients using Flotiq API and OpenAPI Generator",
"main": "index.js",
"bin": {
Expand All @@ -23,6 +23,7 @@
"dotenv": "^16.4.5",
"fs-extra": "^11.2.0",
"inquirer": "^8.2.0",
"loading-cli": "^1.1.2",
"typescript": "^4.0",
"yargs": "^15.3.1"
}
Expand Down
File renamed without changes.
File renamed without changes.
Loading

0 comments on commit 408ca4b

Please sign in to comment.