diff --git a/README.md b/README.md index ed1de39..5e5d06b 100644 --- a/README.md +++ b/README.md @@ -271,7 +271,7 @@ await store.setJSON('some-key', { ### `delete(key: string): Promise` -Deletes an object with the given key, if one exists. +If an entry exists with the given key, deletes it and returns `true`. If not, `false` is returned. ```javascript await store.delete('my-key') diff --git a/src/main.test.ts b/src/main.test.ts index aa52044..4e70eb8 100644 --- a/src/main.test.ts +++ b/src/main.test.ts @@ -1080,9 +1080,32 @@ describe('delete', () => { siteID, }) - await blobs.delete(key) - await blobs.delete(complexKey) + expect(await blobs.delete(key)).toBe(true) + expect(await blobs.delete(complexKey)).toBe(true) + expect(mockStore.fulfilled).toBeTruthy() + }) + + test('Returns `false` when the blob does not exist', async () => { + const mockStore = new MockFetch() + .delete({ + headers: { authorization: `Bearer ${apiToken}` }, + response: new Response(JSON.stringify({ url: signedURL })), + url: `https://api.netlify.com/api/v1/sites/${siteID}/blobs/${key}?context=production`, + }) + .delete({ + response: new Response(null, { status: 404 }), + url: signedURL, + }) + + globalThis.fetch = mockStore.fetch + + const blobs = getStore({ + name: 'production', + token: apiToken, + siteID, + }) + expect(await blobs.delete(key)).toBe(false) expect(mockStore.fulfilled).toBeTruthy() }) @@ -1112,7 +1135,7 @@ describe('delete', () => { test('Deletes from the blob store', async () => { const mockStore = new MockFetch().delete({ headers: { authorization: `Bearer ${edgeToken}` }, - response: new Response(null), + response: new Response(null, { status: 202 }), url: `${edgeURL}/${siteID}/production/${key}`, }) @@ -1125,8 +1148,27 @@ describe('delete', () => { siteID, }) - await blobs.delete(key) + expect(await blobs.delete(key)).toBe(true) + expect(mockStore.fulfilled).toBeTruthy() + }) + + test('Returns `false` when the blob does not exist', async () => { + const mockStore = new MockFetch().delete({ + headers: { authorization: `Bearer ${edgeToken}` }, + response: new Response(null, { status: 404 }), + url: `${edgeURL}/${siteID}/production/${key}`, + }) + + globalThis.fetch = mockStore.fetch + + const blobs = getStore({ + edgeURL, + name: 'production', + token: edgeToken, + siteID, + }) + expect(await blobs.delete(key)).toBe(false) expect(mockStore.fulfilled).toBeTruthy() }) diff --git a/src/store.ts b/src/store.ts index bf9506b..76213f4 100644 --- a/src/store.ts +++ b/src/store.ts @@ -78,11 +78,19 @@ export class Store { } } - async delete(key: string) { + async delete(key: string): Promise { const res = await this.client.makeRequest({ key, method: HTTPMethod.DELETE, storeName: this.name }) - if (res.status !== 200 && res.status !== 204 && res.status !== 404) { - throw new BlobsInternalError(res.status) + switch (res.status) { + case 200: + case 202: + return true + + case 404: + return false + + default: + throw new BlobsInternalError(res.status) } }