Last active
December 19, 2015 07:09
-
-
Save rricard/5916719 to your computer and use it in GitHub Desktop.
A sample Papiel reader written in pure node.js
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
#!/bin/node | |
/** | |
* Launch with `node papiel-reader.js` | |
*/ | |
var http = require('http'), | |
https = require('https'), | |
fs = require('fs'), | |
url = require('url'); | |
// Send a manifest to Papiel | |
var isSSL = node.env.SSL || false, | |
port = node.env.PORT || ((isSSL) ? 8443 : 8000), | |
endpoint = "http" + ((isSSL) ? 's' : '') + '://' + (node.env.HOST || 'localhost') + ':' + port + '/', | |
manifest = { | |
name: "papiel-test", | |
dependencies: [], | |
optional_dependencies: [], | |
metadata: [], | |
optional_metadata: [], | |
returns: [ | |
"hello" | |
], | |
optional_returns: [], | |
endpoint: endpoint | |
}, | |
sendOpts = { | |
hostname: node.env.PAPIEL_HOST || 'api.papiel.fr', | |
port: node.env.PAPIEL_PORT || 443, | |
path: '/reader?client_id=' + node.env.CLIENT_ID + '&client_secret=' + node.env.CLIENT_SECRET, | |
method: 'POST', | |
headers: { | |
'Content-Type': 'application/x-www-form-urlencoded' | |
} | |
}; | |
var req = https.request(sendOpts); | |
req.end(JSON.stringify(manifest)); | |
// Create an asynchronous processor | |
function processor (data, cb) { | |
cb({ hello: "world" }); | |
} | |
// Server waiting for documents | |
function responder (req, res) { | |
var buffer = ""; | |
req.on('data', function (data) { | |
buffer += data; | |
}); | |
req.on('end', function () { | |
res.end(); | |
var data = JSON.parse(buffer), | |
parsedURL = url.parse(data['return_callback']), | |
resOpts = { | |
hostname: parsedURL.host, | |
port: parsedURL.port || 443, | |
path: parsedURL.path + '?client_id=' + node.env.CLIENT_ID + '&client_secret=' + node.env.CLIENT_SECRET, | |
method: 'POST', | |
headers: { | |
'Content-Type': 'application/x-www-form-urlencoded' | |
} | |
}; | |
processor(data, function (newData) { | |
var returnReq = https.request(resOpts); | |
returnReq.end(JSON.stringify(newData)); | |
}); | |
}); | |
} | |
if(isSSL) { | |
var options = { | |
key: fs.readFileSync(node.env.SSL_KEY), | |
cert: fs.readFileSync(node.env.SSL_CERT), | |
}; | |
https.createServer(options, responder).listen(port); | |
} else { | |
http.createServer(responder).listen(port); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment