Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var sys = require('util');
- var http = require('http');
- var fs = require('fs');
- var url = require('url');
- var srv = http.createServer(function (request, response) {
- SOAP2REST(request.url,
- function(d) {
- var headers = {
- "Content-Type": d.response.headers["Content-Type"]
- };
- response.writeHead(d.response.statusCode, headers);
- response.end(d.data);
- },
- function(e) {
- }
- );
- }).listen(8080);
- function SOAP2REST(URL, success, error) {
- URL = url.parse(URL, true);
- // Load Service Definition
- try {
- var soapJSON = fs.readFileSync('./soap' + URL.pathname + '.json', 'UTF-8');
- } catch (e) {
- return die({msg: "Service description " + URL.pathname + ".json could not be found!",
- err: e}, 404);
- }
- // Load SOAP Request
- var soapXML = '';
- try {
- soapXML = fs.readFileSync('./soap' + URL.pathname + '.xml', 'UTF-8');
- } catch (e) {
- // No problem
- }
- // Parse SOAP Configuration
- try {
- var soapJSON = JSON.parse(soapJSON);
- var soapURL = url.parse(soapJSON.url, true);
- } catch (e) {
- return die({
- msg: "Service JSON could not be parsed!",
- name: e.name,
- message: e.message}, 500
- );
- }
- // Set Parameters
- for (p in URL.query)
- soapXML = soapXML.replace('##' + p.toUpperCase() + '##', URL.query[p]);
- // Prepare SOAP Request Headers
- soapJSON.headers = soapJSON.headers || {};
- soapJSON.headers["Content-Length"] = soapXML.length;
- soapJSON.headers["Connection"] = "close";
- // Do SOAP Call
- var httpOptions = {
- host: soapURL.hostname,
- post: soapURL.port || 80,
- method: soapJSON.method || 'POST',
- path: soapURL.pathname,
- headers: soapJSON.headers,
- };
- httpOptions.body = soapXML;
- doHTTP(httpOptions,
- function(d) {
- success(d);
- },
- function(e){
- error(e, 500);
- }
- );
- }
- function doHTTP(options, success, error) {
- var req = http.request(options, function(res) {
- var data = '';
- res.setEncoding(options.encoding || 'utf8');
- res.on('data', function (chunk) { data += chunk; });
- res.on('end', function () { success({ data: data, response: res }); });
- });
- if (typeof options.body != 'undefined') req.write(options.body);
- req.end();
- req.on('error', function(e) { error('HTTP ERROR: ' + e.message); });
- }
- function out(d) {
- if (typeof global.response != 'undefined') global.response.write(d); else console.log(d);
- }
- function dp(d, t) {
- console.log(t || "DEBUG:", d);
- }
- function dpe(d) {
- console.error("ERROR:", d);
- }
- function die(d,s) {
- if (typeof global.response != 'undefined') {
- global.response.statusCode = s || 500;
- global.response.setHeader('Content-Type', 'text/plain');
- global.response.write(d);
- response.end();
- }
- out(sys.inspect(d));
- if (s==500) process.exit(1);
- return false;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement