Skip to content

Commit

Permalink
feat: tie together namespace config with fetch and websocket options
Browse files Browse the repository at this point in the history
  • Loading branch information
lukeocodes committed May 19, 2024
1 parent f42ece3 commit 957dbb1
Show file tree
Hide file tree
Showing 11 changed files with 179 additions and 236 deletions.
4 changes: 2 additions & 2 deletions examples/node-prerecorded/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const transcribeUrl = async () => {
);

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

const transcribeFile = async () => {
Expand All @@ -29,7 +29,7 @@ const transcribeFile = async () => {
});

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

transcribeUrl();
Expand Down
45 changes: 8 additions & 37 deletions examples/node-speak/index.js
Original file line number Diff line number Diff line change
@@ -1,51 +1,22 @@
const { createClient } = require("../../dist/main/index");
const fs = require("fs");
const { pipeline } = require("stream");
const { promisify } = require("util");
const streamPipeline = promisify(pipeline);

const deepgram = createClient(process.env.DEEPGRAM_API_KEY);

const text = "Hello, how can I help you today?";

const getAudio = async () => {
const response = await deepgram.speak.request({ text }, { model: "aura-asteria-en" });
const stream = await response.getStream();
const headers = await response.getHeaders();
if (stream) {
const buffer = await getAudioBuffer(stream);
const { result } = await deepgram.speak.request({ text }, { model: "aura-asteria-en" });

fs.writeFile("audio.wav", buffer, (err) => {
if (err) {
console.error("Error writing audio to file:", err);
} else {
console.log("Audio file written to audio.wav");
}
});
} else {
console.error("Error generating audio:", stream);
if (!result.ok) {
throw new Error(`HTTP error! Status: ${result}`);
}

if (headers) {
console.log("Headers:", headers);
}
};

// helper function to convert stream to audio buffer
const getAudioBuffer = async (response) => {
const reader = response.getReader();
const chunks = [];

while (true) {
const { done, value } = await reader.read();
if (done) break;

chunks.push(value);
}

const dataArray = chunks.reduce(
(acc, chunk) => Uint8Array.from([...acc, ...chunk]),
new Uint8Array(0)
);

return Buffer.from(dataArray.buffer);
const fileStream = fs.createWriteStream("audio.wav");
await streamPipeline(result.body, fileStream);
};

getAudio();
27 changes: 19 additions & 8 deletions src/DeepgramClient.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import { DeepgramVersionError } from "./lib/errors";
import { AbstractClient } from "./packages/AbstractClient";
import { ListenClient } from "./packages/ListenClient";
import { ManageClient } from "./packages/ManageClient";
import { OnPremClient } from "./packages/OnPremClient";
import { ReadClient } from "./packages/ReadClient";
import { SpeakClient } from "./packages/SpeakClient";
import {
AbstractClient,
ListenClient,
ManageClient,
ReadClient,
SelfHostedClient as OnPremClient,
SelfHostedClient,
SpeakClient,
} from "./packages";

/**
* The DeepgramClient class provides access to various Deepgram API clients, including ListenClient, ManageClient, OnPremClient, ReadClient, and SpeakClient.
* The DeepgramClient class provides access to various Deepgram API clients, including ListenClient, ManageClient, SelfHostedClient, ReadClient, and SpeakClient.
*
* @see https://github.com/deepgram/deepgram-js-sdk
*/
Expand All @@ -20,8 +23,16 @@ export default class DeepgramClient extends AbstractClient {
return new ManageClient(this.options);
}

/**
* backwards compatibility for renaming onprem to selfhosted
* @deprecated
*/
get onprem(): OnPremClient {
return new OnPremClient(this.options);
return this.selfhosted;
}

get selfhosted(): SelfHostedClient {
return new SelfHostedClient(this.options);
}

get read(): ReadClient {
Expand Down
26 changes: 2 additions & 24 deletions src/lib/types/Fetch.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,5 @@
export type Fetch = typeof fetch;

export interface FetchOptions {
method?: RequestMethodType;
headers?: Record<string, string>;
cache?: "default" | "no-cache" | "reload" | "force-cache" | "only-if-cached"; // default, no-cache, reload, force-cache, only-if-cached
credentials?: "include" | "same-origin" | "omit"; // include, same-origin, omit
redirect?: "manual" | "follow" | "error"; // manual, follow, error
referrerPolicy?: // no-referrer, no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
| "no-referrer"
| "no-referrer-when-downgrade"
| "origin"
| "origin-when-cross-origin"
| "same-origin"
| "strict-origin"
| "strict-origin-when-cross-origin"
| "unsafe-url";
}
export type FetchOptions = RequestInit & { method?: RequestMethodType; duplex?: string };

export type RequestMethodType = "GET" | "POST" | "PUT" | "DELETE" | "PATCH"; // GET, POST, PUT, DELETE, etc.

export interface FetchParameters {
/**
* Pass in an AbortController's signal to cancel the request.
*/
signal?: AbortSignal;
}
export type RequestMethodType = "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
125 changes: 49 additions & 76 deletions src/packages/AbstractRestClient.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { DeepgramApiError, DeepgramError, DeepgramUnknownError } from "../lib/errors";
import { Readable } from "stream";
import { fetchWithAuth, resolveResponse } from "../lib/fetch";
import type { Fetch, FetchParameters, RequestMethodType } from "../lib/types/Fetch";
import type { Fetch, FetchOptions, RequestMethodType } from "../lib/types/Fetch";
import { AbstractClient } from "./AbstractClient";
import { DeepgramClientOptions } from "../lib/types";
import { isBrowser } from "../lib/helpers";
import merge from "deepmerge";

export abstract class AbstractRestClient extends AbstractClient {
protected fetch: Fetch;
Expand Down Expand Up @@ -49,113 +50,85 @@ export abstract class AbstractRestClient extends AbstractClient {
}
}

protected _getRequestParams(
protected _getRequestOptions(
method: RequestMethodType,
headers?: Record<string, string>,
parameters?: FetchParameters,
body?: string | Buffer | Readable
) {
const params: { [k: string]: any } = {
...this.options?.fetch,
method,
headers: { ...this.options?.fetch?.headers, ...headers } || {},
};

if (method === "GET") {
return params;
}
bodyOrOptions?: string | Buffer | Readable | FetchOptions,
options?: FetchOptions
): FetchOptions {
let reqOptions: FetchOptions = { method };

params.body = body;
params.duplex = "half";
if (method === "GET" || method === "DELETE") {
reqOptions = { ...reqOptions, ...(bodyOrOptions as FetchOptions) };
} else {
reqOptions = {
duplex: "half",
body: bodyOrOptions as BodyInit,
...reqOptions,
...options,
};
}

return { ...params, ...parameters };
return merge(this.namespaceOptions.fetch.options, reqOptions);
}

protected async _handleRequest(
fetcher: Fetch,
method: "GET" | "DELETE",
url: URL,
options?: FetchOptions
): Promise<Response>;
protected async _handleRequest(
method: "POST" | "PUT" | "PATCH",
url: URL,
body: string | Buffer | Readable,
options?: FetchOptions
): Promise<Response>;
protected async _handleRequest(
method: RequestMethodType,
url: string | URL,
headers?: Record<string, string>,
parameters?: FetchParameters,
body?: string | Buffer | Readable
): Promise<any> {
url: URL,
bodyOrOptions?: string | Buffer | Readable | FetchOptions,
options?: FetchOptions
): Promise<Response> {
return new Promise((resolve, reject) => {
fetcher(url, this._getRequestParams(method, headers, parameters, body))
.then((result) => {
if (!result.ok) throw result;

return result.json();
})
.then((data) => resolve(data))
.catch((error) => this._handleError(error, reject));
});
}
const fetcher = this.fetch;

protected async _handleRawRequest(
fetcher: Fetch,
method: RequestMethodType,
url: string | URL,
headers?: Record<string, string>,
parameters?: FetchParameters,
body?: string | Buffer | Readable
): Promise<any> {
return new Promise((resolve, reject) => {
fetcher(url, this._getRequestParams(method, headers, parameters, body))
fetcher(url, this._getRequestOptions(method, bodyOrOptions, options))
.then((result) => {
if (!result.ok) throw result;

return result;
resolve(result);
})
.then((data) => resolve(data))
.catch((error) => this._handleError(error, reject));
});
}

protected async get(
fetcher: Fetch,
url: string | URL,
headers?: Record<string, string>,
parameters?: FetchParameters
): Promise<any> {
return this._handleRequest(fetcher, "GET", url, headers, parameters);
protected async get(url: URL, options?: FetchOptions): Promise<any> {
return this._handleRequest("GET", url, options);
}

protected async post(
fetcher: Fetch,
url: string | URL,
url: URL,
body: string | Buffer | Readable,
headers?: Record<string, string>,
parameters?: FetchParameters
options?: FetchOptions
): Promise<any> {
return this._handleRequest(fetcher, "POST", url, headers, parameters, body);
return this._handleRequest("POST", url, body, options);
}

protected async put(
fetcher: Fetch,
url: string | URL,
url: URL,
body: string | Buffer | Readable,
headers?: Record<string, string>,
parameters?: FetchParameters
options?: FetchOptions
): Promise<any> {
return this._handleRequest(fetcher, "PUT", url, headers, parameters, body);
return this._handleRequest("PUT", url, body, options);
}

protected async patch(
fetcher: Fetch,
url: string | URL,
url: URL,
body: string | Buffer | Readable,
headers?: Record<string, string>,
parameters?: FetchParameters
options?: FetchOptions
): Promise<any> {
return this._handleRequest(fetcher, "PATCH", url, headers, parameters, body);
return this._handleRequest("PATCH", url, body, options);
}

protected async delete(
fetcher: Fetch,
url: string | URL,
headers?: Record<string, string>,
parameters?: FetchParameters
): Promise<any> {
return this._handleRequest(fetcher, "DELETE", url, headers, parameters);
protected async delete(url: URL, options?: FetchOptions): Promise<any> {
return this._handleRequest("DELETE", url, options);
}
}
Loading

0 comments on commit 957dbb1

Please sign in to comment.