Skip to content

feat: support token-based auth endpoint#377

Merged
naomi-lgbt merged 4 commits into
mainfrom
feat/auth
Apr 14, 2025
Merged

feat: support token-based auth endpoint#377
naomi-lgbt merged 4 commits into
mainfrom
feat/auth

Conversation

@naomi-lgbt

@naomi-lgbt naomi-lgbt commented Apr 10, 2025

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • New Features

    • Introduced an audio transcription demonstration that processes a preset audio file. This feature securely retrieves and uses an access token to handle transcription requests while providing detailed logging.
    • Enhanced authentication capabilities with robust token management and error handling, ensuring a smoother and more reliable transcription experience for users.
    • Added a new interface for structured token responses, improving clarity in token management.
  • Documentation

    • Updated documentation for new methods and interfaces to assist developers in understanding the functionalities.

@coderabbitai

coderabbitai Bot commented Apr 10, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

The changes introduce a new example file that demonstrates the process of authenticating via a Deepgram client and transcribing an audio URL. A new function is added to perform these steps, utilizing an API key from the environment. The Deepgram client now exposes an auth getter that provides an instance of the newly added AuthRestClient class, which supplies an asynchronous token-granting method. Additionally, a new interface for the token response (GrantTokenResponse) and corresponding export statements have been added to support type consistency.

Changes

File(s) Change Summary
examples/.../node-auth/index.js Added a new file with the transcribeUrl function that creates a Deepgram client, retrieves a token through authentication, and transcribes a predefined audio URL.
src/DeepgramClient.ts Added a getter method auth in the DeepgramClient class that returns an instance of AuthRestClient.
src/lib/types/GrantTokenResponse.ts
src/lib/types/index.ts
Introduced a new GrantTokenResponse interface defining access_token and expires_in, and updated the index export to include this new interface.
src/packages/AuthRestClient.ts
src/packages/index.ts
Added a new AuthRestClient class with a grantToken method for handling authentication requests, and updated the package index to export its functionalities.

Sequence Diagram(s)

sequenceDiagram
    participant User as User
    participant Script as transcribeUrl Function
    participant Client as DeepgramClient
    participant Auth as AuthRestClient
    participant Listen as Listen Module

    User->>Script: Invoke transcribeUrl
    Script->>Client: Create client with API key
    Client->>Auth: Call grantToken for token retrieval
    Auth-->>Client: Return access token
    Script->>Client: Set token property with access token
    Script->>Listen: Call transcribeUrl (audio URL, options)
    Listen-->>Script: Return transcription result
    Script->>User: Log token and transcription result
Loading

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 71ba273 and 08e12dd.

📒 Files selected for processing (2)
  • src/DeepgramClient.ts (2 hunks)
  • src/packages/AuthRestClient.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/DeepgramClient.ts
  • src/packages/AuthRestClient.ts

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (3)
src/packages/AuthRestClient.ts (2)

14-16: Consider adding request body support for future flexibility.

The POST request is currently sending an empty string as the request body. While this might be sufficient for the current API requirements, consider adding support for an optional request body parameter to future-proof the method if the API evolves to require additional parameters.

  public async grantToken(
-    endpoint = ":version/auth/grant"
+    endpoint = ":version/auth/grant",
+    body: Record<string, unknown> = {}
  ): Promise<DeepgramResponse<GrantTokenResponse>> {
    try {
      const requestUrl = this.getRequestUrl(endpoint);
-      const result: GrantTokenResponse = await this.post(requestUrl, "").then((result) =>
+      const result: GrantTokenResponse = await this.post(requestUrl, JSON.stringify(body)).then((result) =>
        result.json()
      );

10-10: Add type annotation for the endpoint parameter.

Adding a type annotation for the endpoint parameter would make the interface more explicit and improve code maintainability.

  public async grantToken(
-    endpoint = ":version/auth/grant"
+    endpoint: string = ":version/auth/grant"
  ): Promise<DeepgramResponse<GrantTokenResponse>> {
examples/node-auth/index.js (1)

1-1: Use ES modules syntax for consistency with the TypeScript codebase.

The static analysis tools flag this CommonJS require statement. Consider using ES modules syntax for consistency with the TypeScript codebase.

- const { createClient } = require("../../dist/main/index");
+ import { createClient } from "../../dist/main/index.js";
🧰 Tools
🪛 ESLint

[error] 1-1: A require() style import is forbidden.

(@typescript-eslint/no-require-imports)


[error] 1-1: 'require' is not defined.

(no-undef)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 87c554b and 069c9e9.

📒 Files selected for processing (6)
  • examples/node-auth/index.js (1 hunks)
  • src/DeepgramClient.ts (2 hunks)
  • src/lib/types/GrantTokenResponse.ts (1 hunks)
  • src/lib/types/index.ts (1 hunks)
  • src/packages/AuthRestClient.ts (1 hunks)
  • src/packages/index.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
src/DeepgramClient.ts (1)
src/packages/AuthRestClient.ts (1)
  • AuthRestClient (6-27)
examples/node-auth/index.js (1)
src/index.ts (1)
  • createClient (46-46)
🪛 ESLint
examples/node-auth/index.js

[error] 1-1: A require() style import is forbidden.

(@typescript-eslint/no-require-imports)


[error] 1-1: 'require' is not defined.

(no-undef)


[error] 4-4: 'process' is not defined.

(no-undef)


[error] 9-9: 'console' is not defined.

(no-undef)


[error] 11-11: 'console' is not defined.

(no-undef)


[error] 23-23: 'console' is not defined.

(no-undef)


[error] 24-24: 'console' is not defined.

(no-undef)

🔇 Additional comments (7)
src/packages/index.ts (1)

5-5: LGTM: Export for new AuthRestClient

The new export follows the established pattern and is properly alphabetized among the other exports.

src/lib/types/index.ts (1)

29-29: LGTM: Export for new GrantTokenResponse type

The new export follows the established pattern and is properly alphabetized among the other type exports.

src/lib/types/GrantTokenResponse.ts (1)

1-4: LGTM: Well-structured token response interface

The interface correctly defines the expected properties for a token response following standard conventions.

src/DeepgramClient.ts (1)

5-5: LGTM: Import for new AuthRestClient

The import is correctly added to the existing import statement.

src/packages/AuthRestClient.ts (1)

9-26: LGTM: Well-implemented token authorization method.

The grantToken method provides a clean implementation with proper error handling for Deepgram-specific errors. The response typing is correctly structured using the DeepgramResponse generic type.

examples/node-auth/index.js (2)

5-9: LGTM: Proper token retrieval implementation.

Good error handling pattern for the token retrieval - destructuring the response to access the result and error separately, and throwing the error if present.

🧰 Tools
🪛 ESLint

[error] 9-9: 'console' is not defined.

(no-undef)


12-22: LGTM: Good token usage and transcription configuration.

This example properly demonstrates setting the token on the client and configuring the transcription options. The use of a keyterm array is particularly helpful as an example of the API's capabilities.

Comment thread src/DeepgramClient.ts Outdated
Comment on lines +95 to +97
get auth(): AuthRestClient {
return new AuthRestClient(this.options);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add JSDoc documentation for consistency

The new auth getter is missing JSDoc documentation that follows the pattern established by other client getters in this class.

+  /**
+   * Returns a new instance of the AuthRestClient, which provides access to the Deepgram API's authentication functionality.
+   *
+   * @returns {AuthRestClient} A new instance of the AuthRestClient.
+   */
   get auth(): AuthRestClient {
     return new AuthRestClient(this.options);
   }

Also, consider moving this getter to be grouped with the other non-deprecated client getters for better organization.

📝 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
get auth(): AuthRestClient {
return new AuthRestClient(this.options);
}
/**
* Returns a new instance of the AuthRestClient, which provides access to the Deepgram API's authentication functionality.
*
* @returns {AuthRestClient} A new instance of the AuthRestClient.
*/
get auth(): AuthRestClient {
return new AuthRestClient(this.options);
}

Comment on lines +3 to +25
const transcribeUrl = async () => {
const deepgram = createClient(process.env.DEEPGRAM_API_KEY);
const { result: token, error: tokenError } = await deepgram.auth.grantToken();
if (tokenError) {
throw tokenError;
}
console.log("Token", token);

console.log("Transcribing URL", "https://dpgr.am/spacewalk.wav");
deepgram.token = token.access_token;
const { result, error } = await deepgram.listen.prerecorded.transcribeUrl(
{
url: "https://dpgr.am/spacewalk.wav",
},
{
model: "nova-3",
keyterm: ["spacewalk"],
}
);

if (error) console.error(error);
if (!error) console.dir(result, { depth: 5 });
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add API key validation for better error handling.

The example assumes that the DEEPGRAM_API_KEY environment variable is properly set. Consider adding validation to provide a more helpful error message if it's missing.

const transcribeUrl = async () => {
+  if (!process.env.DEEPGRAM_API_KEY) {
+    console.error("DEEPGRAM_API_KEY environment variable is not set");
+    process.exit(1);
+  }
+
  const deepgram = createClient(process.env.DEEPGRAM_API_KEY);
  const { result: token, error: tokenError } = await deepgram.auth.grantToken();
  if (tokenError) {
    throw tokenError;
  }
  console.log("Token", token);
📝 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
const transcribeUrl = async () => {
const deepgram = createClient(process.env.DEEPGRAM_API_KEY);
const { result: token, error: tokenError } = await deepgram.auth.grantToken();
if (tokenError) {
throw tokenError;
}
console.log("Token", token);
console.log("Transcribing URL", "https://dpgr.am/spacewalk.wav");
deepgram.token = token.access_token;
const { result, error } = await deepgram.listen.prerecorded.transcribeUrl(
{
url: "https://dpgr.am/spacewalk.wav",
},
{
model: "nova-3",
keyterm: ["spacewalk"],
}
);
if (error) console.error(error);
if (!error) console.dir(result, { depth: 5 });
};
const transcribeUrl = async () => {
if (!process.env.DEEPGRAM_API_KEY) {
console.error("DEEPGRAM_API_KEY environment variable is not set");
process.exit(1);
}
const deepgram = createClient(process.env.DEEPGRAM_API_KEY);
const { result: token, error: tokenError } = await deepgram.auth.grantToken();
if (tokenError) {
throw tokenError;
}
console.log("Token", token);
console.log("Transcribing URL", "https://dpgr.am/spacewalk.wav");
deepgram.token = token.access_token;
const { result, error } = await deepgram.listen.prerecorded.transcribeUrl(
{
url: "https://dpgr.am/spacewalk.wav",
},
{
model: "nova-3",
keyterm: ["spacewalk"],
}
);
if (error) console.error(error);
if (!error) console.dir(result, { depth: 5 });
};
🧰 Tools
🪛 ESLint

[error] 4-4: 'process' is not defined.

(no-undef)


[error] 9-9: 'console' is not defined.

(no-undef)


[error] 11-11: 'console' is not defined.

(no-undef)


[error] 23-23: 'console' is not defined.

(no-undef)


[error] 24-24: 'console' is not defined.

(no-undef)

if (!error) console.dir(result, { depth: 5 });
};

transcribeUrl();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for the main function call.

The example directly calls transcribeUrl() without any error handling. Consider wrapping the call in a try-catch block to properly handle any errors that might be thrown.

- transcribeUrl();
+ transcribeUrl().catch(error => {
+   console.error("Error during transcription:", error);
+   process.exit(1);
+ });
📝 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
transcribeUrl();
transcribeUrl().catch(error => {
console.error("Error during transcription:", error);
process.exit(1);
});

Comment thread src/DeepgramClient.ts Outdated
jpvajda
jpvajda previously approved these changes Apr 11, 2025

@jpvajda jpvajda left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I just had one docs comment suggestion, else this passed my testing.

Comment thread src/DeepgramClient.ts Outdated
@naomi-lgbt naomi-lgbt merged commit f95597a into main Apr 14, 2025
@naomi-lgbt naomi-lgbt deleted the feat/auth branch April 14, 2025 16:07
@coderabbitai coderabbitai Bot mentioned this pull request Jul 16, 2025
8 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants