diff --git a/js/polliLib/src/image.js b/js/polliLib/src/image.js index 0491020..3568b89 100644 --- a/js/polliLib/src/image.js +++ b/js/polliLib/src/image.js @@ -31,8 +31,16 @@ export async function image(prompt, { const data = await r.json(); if (json) return data; if (data?.url) { - const ir = await fetch(data.url); + const ir = await client.get(data.url); if (ir.ok) return await ir.blob(); + if (retries > 0) { + await sleep(retryDelayMs); + return await image(prompt, { + model, seed, width, height, image, nologo, private: priv, + enhance, safe, referrer, json, retries: retries - 1, retryDelayMs, + }, client); + } + throw new Error(`image error ${ir.status}`); } if (retries > 0) { await sleep(retryDelayMs); diff --git a/tests/pollilib-async-image.mjs b/tests/pollilib-async-image.mjs index 6d6767a..d943564 100644 --- a/tests/pollilib-async-image.mjs +++ b/tests/pollilib-async-image.mjs @@ -23,7 +23,8 @@ const client = { } }; -global.fetch = async () => ({ ok: true, blob: async () => new Blob(['x'], { type: 'image/png' }) }); +global.fetch = () => { throw new Error('fetch should not be called'); }; const blob = await image('test', {}, client); assert(blob instanceof Blob); +assert.equal(calls, 2); diff --git a/tests/pollilib-image-error.mjs b/tests/pollilib-image-error.mjs new file mode 100644 index 0000000..d40c3b3 --- /dev/null +++ b/tests/pollilib-image-error.mjs @@ -0,0 +1,32 @@ +import assert from 'assert/strict'; +import fs from 'fs/promises'; +import { image } from '../js/polliLib/src/image.js'; + +let calls = 0; +const pending = JSON.parse(await fs.readFile(new URL('./fixtures/pending-image.json', import.meta.url), 'utf8')); +const client = { + imageBase: 'https://example.com', + async get(url, opts = {}) { + calls++; + if (calls === 1) { + return { + ok: true, + headers: { get: () => 'application/json' }, + async json() { return pending; }, + }; + } + return { ok: false, status: 500, headers: { get: () => 'text/plain' } }; + } +}; + +global.fetch = () => { throw new Error('fetch should not be called'); }; + +let caught = null; +try { + await image('test', { retries: 0 }, client); +} catch (err) { + caught = err; +} +assert(caught); +assert.equal(caught.message, 'image error 500'); +assert.equal(calls, 2);