Created
June 6, 2017 14:51
-
-
Save scottsbaldwin/230465d8d90c9e05b37535dbc723c7ac to your computer and use it in GitHub Desktop.
Pipedrive File Uploader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
awesome! Thanks! Work perfectly