Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Auto-Initialize the API #23

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions lib/api/core/OpenAPI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ export type OpenAPIConfig = {
request: Interceptors<RequestInit>;
response: Interceptors<Response>;
};
INITIALIZED: boolean;
};

export const OpenAPI: OpenAPIConfig = {
Expand All @@ -53,4 +54,5 @@ export const OpenAPI: OpenAPIConfig = {
request: new Interceptors(),
response: new Interceptors(),
},
INITIALIZED: false,
};
6 changes: 6 additions & 0 deletions lib/api/core/request.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { init } from "../../config";
import { ApiError } from "./ApiError";
import type { ApiRequestOptions } from "./ApiRequestOptions";
import type { ApiResult } from "./ApiResult";
Expand Down Expand Up @@ -348,6 +349,11 @@ export const request = <T>(
config: OpenAPIConfig,
options: ApiRequestOptions<T>,
): CancelablePromise<T> => {
// Verify that config has been initialized
if (!config.INITIALIZED) {
init();
}

return new CancelablePromise(async (resolve, reject, onCancel) => {
try {
const url = getUrl(config, options);
Expand Down
3 changes: 3 additions & 0 deletions lib/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,9 @@ export const init = (
return await getToken();
},
});

// Mark OpenAPI as initialized
OpenAPI.INITIALIZED = true;
Comment on lines +65 to +67
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Consider improving initialization safety and documentation

The initialization tracking addition needs some improvements:

  1. The function should be synchronized to prevent race conditions during parallel initialization attempts
  2. The INITIALIZED flag should only be set after ensuring all initialization steps succeed
  3. The JSDoc should document the initialization state behavior

Here's a suggested implementation:

 /**
  * Initializes the integration with Kinde, using either provided configuration
  * or default values from `kindeConfig`.
  *
  * @param {Object} [config] - Optional configuration object for Kinde.
  * @param {string} [config.kindeDomain] - The domain of your Kinde account.
  * @param {string} [config.clientId] - Your Kinde M2M client ID.
  * @param {string} [config.clientSecret] - Your Kinde M2M client secret.
+ * @throws {Error} If initialization fails due to missing configuration or invalid state
+ * @returns {Promise<void>} - Resolves when initialization is complete
  */
-export const init = (
+export const init = async (
   config: Pick<
     configType,
     "kindeDomain" | "clientId" | "clientSecret"
   > = kindeConfig,
-) => {
+) => {
+  // Prevent parallel initialization
+  if (OpenAPI.INITIALIZED) {
+    return;
+  }

   if (!process.env.KINDE_DOMAIN && config.kindeDomain === "") {
     throw new Error("kindeDomain or env KINDE_DOMAIN is not set");
   }

   _merge(
     kindeConfig,
     {
       clientId: process.env.KINDE_MANAGEMENT_CLIENT_ID,
       clientSecret: process.env.KINDE_MANAGEMENT_CLIENT_SECRET,
       audience: process.env.KINDE_DOMAIN + "/api",
       kindeDomain: process.env.KINDE_DOMAIN,
     },
     config,
   );

   _merge(OpenAPI, {
     BASE: kindeConfig.kindeDomain,
     TOKEN: async () => {
       return await getToken();
     },
   });

+  try {
+    // Verify the configuration by attempting to get an initial token
+    await getToken();
+    OpenAPI.INITIALIZED = true;
+  } catch (error) {
+    throw new Error(`Failed to initialize: ${error.message}`);
+  }
 };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Mark OpenAPI as initialized
OpenAPI.INITIALIZED = true;
/**
* Initializes the integration with Kinde, using either provided configuration
* or default values from `kindeConfig`.
*
* @param {Object} [config] - Optional configuration object for Kinde.
* @param {string} [config.kindeDomain] - The domain of your Kinde account.
* @param {string} [config.clientId] - Your Kinde M2M client ID.
* @param {string} [config.clientSecret] - Your Kinde M2M client secret.
* @throws {Error} If initialization fails due to missing configuration or invalid state
* @returns {Promise<void>} - Resolves when initialization is complete
*/
export const init = async (
config: Pick<
configType,
"kindeDomain" | "clientId" | "clientSecret"
> = kindeConfig,
) => {
// Prevent parallel initialization
if (OpenAPI.INITIALIZED) {
return;
}
if (!process.env.KINDE_DOMAIN && config.kindeDomain === "") {
throw new Error("kindeDomain or env KINDE_DOMAIN is not set");
}
_merge(
kindeConfig,
{
clientId: process.env.KINDE_MANAGEMENT_CLIENT_ID,
clientSecret: process.env.KINDE_MANAGEMENT_CLIENT_SECRET,
audience: process.env.KINDE_DOMAIN + "/api",
kindeDomain: process.env.KINDE_DOMAIN,
},
config,
);
_merge(OpenAPI, {
BASE: kindeConfig.kindeDomain,
TOKEN: async () => {
return await getToken();
},
});
try {
// Verify the configuration by attempting to get an initial token
await getToken();
OpenAPI.INITIALIZED = true;
} catch (error) {
throw new Error(`Failed to initialize: ${error.message}`);
}
};

};

function _merge(target: object = {}, ...objects: object[]): object {
Expand Down
18 changes: 14 additions & 4 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,25 +28,35 @@ The following ENV variables are required to run the project:
## Usage

```js
import { Users, init } from "@kinde/management-api-js";
import { Users } from "@kinde/management-api-js";

init();
const { users } = await Users.getUsers();
```

### Params can be passed to the function as an object

```js
import { Users, init } from "@kinde/management-api-js";
import { Users } from "@kinde/management-api-js";

const params = {
id: "kp_xxx",
};

init();
const userData = await Users.getUserData(params);
```

### Manually Initializing the API

```js
import { init } from "@kinde/management-api-js";

init({
domain: "mybusiness.kinde.com",
clientId: "client_id",
clientSecret: "client_secret",
});
```

## API documentation

You can find management API documentation here: [Kinde Management API Documentation](https://kinde.com/api/docs/#kinde-management-api)
Expand Down