Last active
July 7, 2020 16:48
-
-
Save travist/06763744d790f935bc7b305e2d69acd8 to your computer and use it in GitHub Desktop.
Webhook Download PDF
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
'use strict'; | |
const config = { | |
projectUrl: 'http://localhost:3000', | |
apiKey: '23423423lkj234ljk234lkj234lkj23' | |
}; | |
const express = require('express'); | |
const bodyParser = require('body-parser'); | |
const methodOverride = require('method-override'); | |
const fetch = require('node-fetch'); | |
const fs = require('fs'); | |
// Creat eour application. | |
const app = express(); | |
// Add Middleware necessary for REST API's | |
app.use(bodyParser.urlencoded({extended: true})); | |
app.use(bodyParser.json()); | |
app.use(methodOverride('X-HTTP-Method-Override')); | |
function download(url, filename) { | |
return fetch(url).then((res) => { | |
return new Promise((resolve, reject) => { | |
const fileStream = fs.createWriteStream(filename); | |
res.body.pipe(fileStream); | |
res.body.on("error", (err) => { | |
reject(err); | |
}); | |
fileStream.on("finish", function() { | |
resolve(); | |
}); | |
}); | |
}); | |
} | |
app.post('/*', (req, res, next) => { | |
fetch(`http://${config.projectUrl}/project/${req.body.submission.project}/token`, { | |
headers: { | |
'x-allow': `GET:/project/${req.body.submission.project}/form/${req.body.submission.form}/submission/${req.body.submission._id}/download`, | |
'x-expire': 3600, | |
'x-token': config.apiKey | |
} | |
}) | |
.then(res => res.json()) | |
.then(json => { | |
download(`http://${config.projectUrl}/project/${req.body.submission.project}/form/${req.body.submission.form}/submission/${req.body.submission._id}/download?token=${json.key}`, `./${req.body.submission._id}.pdf`).then(() => { | |
console.log('Download complete'); | |
}); | |
}); | |
next(); | |
}) | |
module.exports = app; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment