From e3e3e5ef550b84835dbf9dfa3dbcaed5379e78ca Mon Sep 17 00:00:00 2001 From: Vlad Holubiev Date: Fri, 19 Jul 2019 20:16:47 +0300 Subject: [PATCH] feat: don't throw error if doc was already uploaded --- readme.md | 3 +++ src/upload.test.ts | 13 +++++++++++++ src/upload.ts | 8 ++++++++ 3 files changed, 24 insertions(+) diff --git a/readme.md b/readme.md index 7f16558..81e83d6 100644 --- a/readme.md +++ b/readme.md @@ -26,6 +26,9 @@ const jwt = getJWTForDocumentPreview(documentId); - `PSPDFKIT_SERVER_JWT_KEY` - `PSPDFKIT_SERVER_JWT_PASSPHRASE` +**Note:** this library tries to be idempotent. +Unlike PSPDFKit server, it catches errors when document with provided ID was already uploaded. + See [Client Authentication](https://pspdfkit.com/guides/server/current/pspdfkit-server/client-authentication/) section of PSPDFKit documentation for details. diff --git a/src/upload.test.ts b/src/upload.test.ts index e1e5d25..b1b2763 100644 --- a/src/upload.test.ts +++ b/src/upload.test.ts @@ -32,3 +32,16 @@ it('should return uploaded document id', async () => { const documentId = await uploadPDF('some-doc-id', createReadStream('./test.pdf')); expect(documentId).toEqual('some-doc-id'); }); + +it('should return provided doc id when doc already exists', async () => { + ((fetch as unknown) as jest.Mock).mockResolvedValueOnce({ + status: 400, + async text() { + return 'A document with the given document_id already exists.'; + } + }); + + const documentId = await uploadPDF('some-another-doc-id', createReadStream('./test.pdf')); + + expect(documentId).toEqual('some-another-doc-id'); +}); diff --git a/src/upload.ts b/src/upload.ts index 33791fa..53fe2f7 100644 --- a/src/upload.ts +++ b/src/upload.ts @@ -21,6 +21,14 @@ export async function uploadPDF(documentId: string, fileStream: ReadStream): Pro } }); + if (response.status === 400) { + const errorMessage = await response.text(); + + if (errorMessage.includes(`A document with the given document_id already exists`)) { + return documentId; + } + } + const { data: {document_id} }: UploadDocumentResponse = await response.json();