Skip to content

Commit

Permalink
feat: don't throw error if doc was already uploaded
Browse files Browse the repository at this point in the history
  • Loading branch information
vladholubiev committed Jul 19, 2019
1 parent 43dc20d commit e3e3e5e
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 0 deletions.
3 changes: 3 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
13 changes: 13 additions & 0 deletions src/upload.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
});
8 changes: 8 additions & 0 deletions src/upload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down

0 comments on commit e3e3e5e

Please sign in to comment.