Skip to content

Instantly share code, notes, and snippets.

@scottsbaldwin
Created June 6, 2017 14:51
Show Gist options
  • Save scottsbaldwin/230465d8d90c9e05b37535dbc723c7ac to your computer and use it in GitHub Desktop.
Save scottsbaldwin/230465d8d90c9e05b37535dbc723c7ac to your computer and use it in GitHub Desktop.
Pipedrive File Uploader
var _ = require('lodash'),
fs = require('fs'),
FormData = require('form-data');
const PIPEDRIVE_API_TOKEN='REDACTED';
function addFileToDeal(filePath, dealId) {
return new Promise((resolve, reject) => {
if (_.isNil(filePath) || filePath === '') {
reject(new Error('filePath must be set.'));
return;
}
if (!_.isNumber(dealId) || dealId < 1) {
reject(new Error(`dealId must be a positive number. You passed: ${dealId}`));
return;
}
// The Pipedrive Files Node.js SDK is broken with binary files
// so we go straight to the API using an HTTPs client.
let form = new FormData();
form.append('deal_id', dealId);
form.append('file', fs.createReadStream(filePath));
let opts = {
protocol: 'https:',
host: 'api.pipedrive.com',
path: `/v1/files?api_token=${PIPEDRIVE_API_TOKEN}`
};
form.submit(opts, (err, res) => {
if (err) {
reject(err);
return;
}
if (res.statusCode !== 201) {
reject(`The file upload should have returned a 201 status, but returned ${res.statusCode}.`);
return;
}
let body = [];
res.on('data', (chunk) => body.push(chunk));
res.on('end', () => {
let json = JSON.parse(body.join(''));
if (!json.data) {
reject('The file upload response JSON did not have a data property.');
return;
}
resolve(json.data);
});
});
});
}
module.exports = addFileToDeal;
@emafriedrich
Copy link

awesome! Thanks! Work perfectly

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment