From 83494bf587bc52840cd324f5c08708988d703905 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Mon, 7 Aug 2023 22:11:07 -0700 Subject: [PATCH] defer auth check until request time Check for auth when an API request is made, instead of checking at runtime. --- index.js | 8 ++++---- index.test.ts | 16 ++++++++-------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/index.js b/index.js index 6a23effa..e91d2b20 100644 --- a/index.js +++ b/index.js @@ -37,10 +37,6 @@ class Replicate { * @param {Function} [options.fetch] - Fetch function to use. Defaults to `globalThis.fetch` */ constructor(options) { - if (!options.auth) { - throw new Error('Missing required parameter: auth'); - } - this.auth = options.auth; this.userAgent = options.userAgent || `replicate-javascript/${packageJSON.version}`; @@ -166,6 +162,10 @@ class Replicate { async request(route, options) { const { auth, baseUrl, userAgent } = this; + if (!auth) { + throw new Error('Not authenticated. Set `auth` option when initializing the Replicate client.'); + } + let url; if (route instanceof URL) { url = route; diff --git a/index.test.ts b/index.test.ts index 818f8744..fced0211 100644 --- a/index.test.ts +++ b/index.test.ts @@ -33,14 +33,6 @@ describe('Replicate client', () => { }); expect(clientWithCustomUserAgent.userAgent).toBe('my-app/1.2.3'); }); - - test('Throws error if no auth token is provided', () => { - const expected = 'Missing required parameter: auth' - - expect(() => { - new Replicate({ auth: "" }); - }).toThrow(expected); - }); }); describe('collections.list', () => { @@ -668,6 +660,14 @@ describe('Replicate client', () => { await expect(client.run(':abc123', options)).rejects.toThrow(); }); + test('Throws an error if client was initialized without auth', async () => { + // @ts-expect-error + client = new Replicate({}); + + const expected = 'Not authenticated'; + await expect(client.run('owner/model:5c7d5dc6', { input: { query: 'hello' } })).rejects.toThrow(expected); + }); + test('Throws an error if webhook URL is invalid', async () => { await expect(async () => { await client.run(