diff --git a/src/index.ts b/src/index.ts index 76f464c..a65da26 100644 --- a/src/index.ts +++ b/src/index.ts @@ -17,7 +17,7 @@ export interface ClientOptions { /** * Defaults to process.env['HONCHO_AUTH_TOKEN']. */ - apiKey?: string | undefined; + apiKey?: string | null | undefined; /** * Specifies the environment to use for the API. @@ -87,14 +87,14 @@ export interface ClientOptions { /** API Client for interfacing with the Honcho API. */ export class Honcho extends Core.APIClient { - apiKey: string; + apiKey: string | null; private _options: ClientOptions; /** * API Client for interfacing with the Honcho API. * - * @param {string | undefined} [opts.apiKey=process.env['HONCHO_AUTH_TOKEN'] ?? undefined] + * @param {string | null | undefined} [opts.apiKey=process.env['HONCHO_AUTH_TOKEN'] ?? null] * @param {Environment} [opts.environment=local] - Specifies the environment URL to use for the API. * @param {string} [opts.baseURL=process.env['HONCHO_BASE_URL'] ?? http://localhost:8000] - Override the default base URL for the API. * @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. @@ -106,15 +106,9 @@ export class Honcho extends Core.APIClient { */ constructor({ baseURL = Core.readEnv('HONCHO_BASE_URL'), - apiKey = Core.readEnv('HONCHO_AUTH_TOKEN'), + apiKey = Core.readEnv('HONCHO_AUTH_TOKEN') ?? null, ...opts }: ClientOptions = {}) { - if (apiKey === undefined) { - throw new Errors.HonchoError( - "The HONCHO_AUTH_TOKEN environment variable is missing or empty; either provide it, or instantiate the Honcho client with an apiKey option, like new Honcho({ apiKey: 'My API Key' }).", - ); - } - const options: ClientOptions = { apiKey, ...opts, @@ -153,7 +147,23 @@ export class Honcho extends Core.APIClient { }; } + protected override validateHeaders(headers: Core.Headers, customHeaders: Core.Headers) { + if (this.apiKey && headers['authorization']) { + return; + } + if (customHeaders['authorization'] === null) { + return; + } + + throw new Error( + 'Could not resolve authentication method. Expected the apiKey to be set. Or for the "Authorization" headers to be explicitly omitted', + ); + } + protected override authHeaders(opts: Core.FinalRequestOptions): Core.Headers { + if (this.apiKey == null) { + return {}; + } return { Authorization: `Bearer ${this.apiKey}` }; }