Draftable Compare API - Node.js Client Library
==============================================
A thin JavaScript client for the Draftable API which wraps all available endpoints and handles authentication and signing.
See the full API documentation for an introduction to the API, usage notes, and other reference material.
- Initializing the client
- Retrieving comparisons
- Deleting comparisons
- Creating comparisons
- Displaying comparisons
- Exporting comparisons
- Utility functions
- Browser support
- Self-signed certificates
Requirements
------------
- Operating system: Any maintained Linux, macOS, or Windows release
- Node.js runtime: Any maintained version
- Create a free API account
- Retrieve your credentials
- Install the library
- Instantiate a client
- Start creating comparisons
left: {
source: 'https://api.draftable.com/static/test-documents/code-of-conduct/left.rtf',
fileType: 'rtf',
},
right: {
source: 'https://api.draftable.com/static/test-documents/code-of-conduct/right.pdf',
fileType: 'pdf',
},
}).then(function(comparison) {
console.log("Comparison created: %s", comparison);
// Generate a signed viewer URL to access the private comparison. The expiry
// time defaults to 30 minutes if the valid_until parameter is not provided.
const viewerURL = comparisons.signedViewerURL(comparison.identifier);
console.log("Viewer URL (expires in 30 mins): %s", viewerURL);
});
```
API reference
-------------
- All API requests return Promises:
Comparison
objects
- Successful calls that return no data resolve to null
(e.g. a DELETE
request)
- Calls which fail for any reason will reject the Promise
with an Error
object
Initializing the client
The package exports a function to create aClient
for your API account.
Client
provides a comparisons
property which yields a ComparisonsClient
to manage the comparisons for your API account.
Creating a Client
differs slightly based on the API endpoint being used:
```js
// Draftable API (default endpoint)
var comparisons = require('@draftable/compare-api').client(
'<yourAccountId>', // Replace with your API credentials from:
'<yourAuthToken>' // https://api.draftable.com/account/credentials
).comparisons;
// Draftable API regional endpoint or Self-hosted
var comparisons = require('@draftable/compare-api').client(
'<yourAccountId>', // Replace with your API credentials from the regional
'<yourAuthToken>', // Draftable API endpoint or your Self-hosted container
'https://draftable.example.com/api/v1' // Replace with the endpoint URL
).comparisons;
```
For API Self-hosted you may need to suppress TLS certificate validation if the server is using a self-signed certificate (the default).
Retrieving comparisons
getAll()
Promise
which resolves to a list of all your comparisons, ordered from newest to oldest. This is potentially an expensive operation.
get(identifier: string)
Promise
which resolves to the specified Comparison
or rejects if the specified comparison identifier does not exist.
Comparison
objects have the following properties:
identifier: string
left: object
/right: object
fileType: string
The file extension
- sourceURL: string
(optional)
The URL for the file if the original request was specified by URL
- displayName: string
(optional)
The display name for the file if given in the original request
publiclyAccessible: boolean
creationTime: Date
expiryTime: Date
(optional)
ready: boolean
Comparison
is ready (i.e. it has been processed) it has the following additional properties:
failed: boolean
errorMessage: string
(only present iffailed
)
Example usage
```js var identifier = ''; comparisons.get(identifier).then(function(comparison) {const visibility = comparison.publiclyAccessible ? 'private' : 'public';
const status = comparison.ready ? 'ready' : 'not ready';
console.log("Comparison '%s' (%s) is %s.", comparison.identifier, visibility, status);
if (comparison.ready && comparison.failed) {
console.log("The comparison failed with error: %s", comparison.errorMessage);
}
});
```
Deleting comparisons
destroy(identifier: string)
Promise
which resolves on successfully deleting the specified comparison or rejects if no such comparison exists.
Example usage
```js comparisons.getAll().then(function(oldestcomparisons) {console.log("Deleting oldest 10 comparisons ...");
const deleteStartIndex = Math.max(0, oldest_comparisons.length - 10);
for (let i = deleteStartIndex; i < oldest_comparisons.length; ++i) {
const identifier = oldest_comparisons[i].identifier;
comparisons.destroy(identifier).then(function() {
console.log("Comparison '%s' deleted.", identifier);
});
}
});
```
Creating comparisons
create(options)
Promise
which resolves to a new Comparison
object.
options
consists of the following parameters:
left: object
/right: object
identifier: string
(optional)
publiclyAccessible: boolean
(optional)
false
or unspecified authentication is required to view the comparison
- If true
the comparison can be accessed by anyone with knowledge of the URL
expires: Date | string
(optional)
Date
object or a string
which can be parsed by Date.parse
- If specified, the provided expiry time must be UTC and in the future
- If unspecified, the comparison will never expire (but may be explicitly deleted)
options.left
and options.right
consist of the following parameters:
source: buffer | string
buffer
, contains the file data (e.g. {source: fs.readFileSync('path/to/file')}
)
- If provided as a string
, the URL from which the server will download the file (e.g. {source: 'https://example.com/path/to/file'}
)
fileType: string
pdf
- Word: docx
, docm
, doc
, rtf
- PowerPoint: pptx
, pptm
, ppt
- Text: txt
displayName: string
(optional)
Example usage
```js var identifier = comparisons.generateIdentifier(); comparisons.create({identifier: identifier,
left: {
source: 'https://domain.com/left.pdf',
fileType: 'pdf',
displayName: 'Document.pdf',
},
right: {
source: fs.readFileSync('path/to/right/file.docx'),
fileType: 'docx',
displayName: 'Document (revised).docx',
},
// Expire this comparison in 2 hours (default is no expiry)
expires: new Date(Date.now() + 1000 * 60 * 120),
}).then(function(comparison) {
console.log("Created comparison: %s", comparison);
});
```
Displaying comparisons
publicViewerURL(identifier: string, wait?: boolean)
signedViewerURL(identifier: string, valid_until?: Date | string, wait?: boolean)
identifier
wait
(optional)
false
or unspecified, the viewer will show an error if the identifier
does not exist
- If true
, the viewer will wait for a comparison with the provided identifier
to exist
Note this will result in a perpetual loading animation if the `identifier` is never created
The signedViewerURL
function also supports the following parameters:
valid_until
(optional)
Date
object or a string
which can be parsed by Date.parse
- If specified, the provided expiry time must be UTC and in the future
- If unspecified, the URL will be generated with the default 30 minute expiry
See the displaying comparisons section in the API documentation for additional details.
Example usage
```js var identifier = '' // Retrieve a signed viewer URL which is valid for 1 hour. The viewer will wait // for the comparison to exist in the event processing has not yet completed. var validuntil = new Date(Date.now() + 1000 60 60) var viewerURL = comparisons.signedViewerURL(identifier, validuntil, true); console.log("Viewer URL (expires in 1 hour): %s", viewerURL); ```Exporting comparisons
Export the comparison to PDF by sending the comparison identifier along with the requested export kind.- Four export kinds are supported.
Export
objects have the following properties:
identifier: string
comparison: string
url: string
kind: string
single_page
, combined
, left or right
ready: boolean
failed: boolean
Export example usage
Post request of the export ```js client.exports .requestExport({comparison: "<identifier>",
kind: "combined",
include_cover_page: false,
})
.then((result: ExportResult) => {
console.log(result);
}
```
Get requested export
```js
client.exports.get(requestResponse.identifier).then((result: ExportResult) => {
console.log(result);
});
```
Utility functions
generateIdentifier()
Browser support
This library is designed primarily for server-side usage. Usage in web browsers (client-side) is not currently supported. Calling the Draftable API via client-side JavaScript is generally discouraged as this implies sharing API credentials with end-users.Self-signed certificates
If connecting to an API Self-hosted endpoint which is using a self-signed certificate (the default) you will need to suppress certificate validation. This can be done by setting theNODE_TLS_REJECT_UNAUTHORIZED
environment variable to 0
.
See the below examples for different operating systems and shell environments. Note that all examples only set the variable for the running shell and it will not persist. To persist the setting consult the documentation for your shell environment. This should be done with caution as this setting suppresses certificate validation for all connections made by the Node.js runtime!
(ba)sh (Linux, macOS, WSL)
```sh
export NODETLSREJECTUNAUTHORIZED=0
```
PowerShell:
```posh
$env:NODETLSREJECTUNAUTHORIZED=0
```
Command Prompt (Windows):
```cmd
SET NODETLSREJECTUNAUTHORIZED=0
```
Setting this environment variable in production environments is strongly discouraged as it significantly lowers security. We only recommend setting this environment variable in development environments if configuring a CA signed certificate for API Self-hosted is not possible.
License
-------
All content is licensed under the terms of The MIT License.