Home

Awesome

strong-soap

CI Build Status Coverage Status

This module provides a Node.js SOAP client for invoking web services and a mock-up SOAP server capability to create and test your web service. This module is based on node-soap module.

<!-- Run `npm run toc` to update below section --> <!-- START doctoc generated TOC please keep comment here to allow auto update --> <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --> <!-- END doctoc generated TOC please keep comment here to allow auto update -->

Overview

Features:

Install

Node.js version 10, 12, and 14 are officially supported. We dropped version 8 support in 3.0.0.

Install with npm:

npm install strong-soap

Client

Start with the WSDL for the web service you want to invoke. For example, the stock quote service http://www.webservicex.net/stockquote.asmx and the WSDL is http://www.webservicex.net/stockquote.asmx?WSDL

Create a new SOAP client from WSDL URL using soap.createClient(url[, options], callback). Also supports a local file system path. An instance of Client is passed to the soap.createClient callback. It is used to execute methods on the soap service.

"use strict";

var soap = require('strong-soap').soap;
// wsdl of the web service this client is going to invoke. For local wsdl you can use, url = './wsdls/stockquote.wsdl'
var url = 'http://www.webservicex.net/stockquote.asmx?WSDL';

var requestArgs = {
  symbol: 'IBM'
};

var options = {};
soap.createClient(url, options, function(err, client) {
  var method = client['StockQuote']['StockQuoteSoap']['GetQuote'];
  method(requestArgs, function(err, result, envelope, soapHeader) {
    //response envelope
    console.log('Response Envelope: \n' + envelope);
    //'result' is the response body
    console.log('Result: \n' + JSON.stringify(result));
  });
});

As well as creating a client via a url, an existing WSDL object can be passed in via options.WSDL_CACHE.

var soap = require('strong-soap').soap;
var WSDL = soap.WSDL;

var url = 'http://www.webservicex.net/stockquote.asmx?WSDL';

// Pass in WSDL options if any

var options = {};
WSDL.open(url,options,
  function(err, wsdl) {
    // You should be able to get to any information of this WSDL from this object. Traverse
    // the WSDL tree to get  bindings, operations, services, portTypes, messages,
    // parts, and XSD elements/Attributes.

    // Set the wsdl object in the cache. The key (e.g. 'stockquotewsdl')
    // can be anything, but needs to match the parameter passed into soap.createClient()
    var clientOptions = {
      WSDL_CACHE : {
        stockquotewsdl: wsdl
      }
    };
    soap.createClient('stockquotewsdl', clientOptions, function(err, client) {
      var method = client['StockQuote']['StockQuoteSoap']['GetQuote'];
      method(requestArgs, function(err, result, envelope, soapHeader) {

      //response envelope
      console.log('Response Envelope: \n' + envelope);
      //'result' is the response body
      console.log('Result: \n' + JSON.stringify(result));
    });
  });
});

The Request envelope created by above service invocation:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Header/>
  <soap:Body>
    <ns1:GetQuote xmlns:ns1="http://www.webserviceX.NET/">
      <ns1:symbol>IBM</ns1:symbol>
    </ns1:GetQuote>
  </soap:Body>
</soap:Envelope>

This WSDL operation is defined as document/literal-wrapped style. Hence the request in soap <Body> is wrapped in operation name. Refer to test cases server-client-document-test and server-client-rpc-test to understand document and rpc styles and their Request, Response and Fault samples.

The options argument allows you to customize the client with the following properties:

Note: for versions of node >0.10.X, you may need to specify {connection: 'keep-alive'} in SOAP headers to avoid truncation of longer chunked responses.

Extra headers (optional)

User can define extra HTTP headers to be sent on the request.

var clientOptions = {};
soap.createClient(url, clientOptions, function(err, client) {
  var customRequestHeader = {customheader1: 'test1'};
  // Custom request header
  client.GetQuote(requestArgs, function(err, result, envelope) {
    // Result in SOAP envelope body which is the wrapper element.
    // In this case, result object corresponds to GetCityForecastByZIPResponse.
    console.log(JSON.stringify(result));
  }, null, customRequestHeader);
});

Client.describe()

Describes services, ports and methods as a JavaScript object.

// Describes the entire WSDL in a JSON tree object form.
var description = client.describe();
// Inspect GetQuote operation. You can inspect Service: {Port: {operation: {
console.log(JSON.stringify(description.StockQuote.StockQuoteSoap.GetQuote));

Client.setSecurity(security)

Use the specified security protocol.

Refer to test case ssl-test for an example of using this API.

Client.method(args, callback)

Call method on the SOAP service.

  client.MyFunction({name: 'value'}, function(err, result, envelope, soapHeader) {
      // Result is a javascript object
      // Envelope is the response envelope from the Web Service
      // soapHeader is the response soap header as a JavaScript object
  })

A method can also be called as a promise.

  client.MyFunction({name: 'value'}).then(function({result, envelope, soapHeader}){
    // ...
  }, function(err) {
    // ...
  });

  // in async/await flavor
  try {
    const {result, envelope, soapHeader} = await client.MyFunction({name: 'value'});
  } catch(err) {
    // handle error
  }

Client.service.port.method(args, callback[, options[, extraHeaders]])

Call a method using a specific service and port.

  client.MyService.MyPort.MyFunction({name: 'value'}, function(err, result) {
      // Result is a JavaScript object
  })

Options (optional)

Accepts any option that the request module accepts, see request module.

For example, you could set a timeout of 5 seconds on the request like this:

  client.MyService.MyPort.MyFunction({name: 'value'}, function(err, result) {
      // result is a javascript object
  }, {timeout: 5000})

You can measure the elapsed time on the request by passing the time option:

  client.MyService.MyPort.MyFunction({name: 'value'}, function(err, result) {
      // client.lastElapsedTime - the elapsed time of the last request in milliseconds
  }, {time: true})

Alternative method call using callback-last pattern

To align method call signature with Node's standard callback-last pattern and eventually allow promisification of method calls, the following method signatures are also supported:

client.MyService.MyPort.MyFunction({name: 'value'}, options, function (err, result) {
  // result is a javascript object
})

client.MyService.MyPort.MyFunction({name: 'value'}, options, extraHeaders, function (err, result) {
  // result is a javascript object
})

Client.lastRequest

The property that contains last full soap request for client logging.

Client.setEndpoint(url)

Overwrites the SOAP service endpoint address.

Client events

Client instances emit the following events:

For an example of using this API, see ssl-test.

Here is an example of 'soapError' event

soap.createClient(__dirname + '/wsdl/default_namespace.wsdl', function (err, client) {
  var didEmitEvent = false;
  client.on('soapError', function(err) {
    didEmitEvent = true;
    assert.ok(err.root.Envelope.Body.Fault);
  });
  client.MyOperation({}, function(err, result) {
    assert.ok(didEmitEvent);
    done();
  });
}, baseUrl);

Security

strong-soap has several default security protocols. You can easily add your own as well. The interface is quite simple. Each protocol defines two methods:

BasicAuthSecurity

  client.setSecurity(new soap.BasicAuthSecurity('username', 'password'));

BearerSecurity

  client.setSecurity(new soap.BearerSecurity('token'));

ClientSSLSecurity

Note: If you run into issues using this protocol, consider passing these options as default request options to the constructor:

  client.setSecurity(new soap.ClientSSLSecurity(
    '/path/to/key'
    , '/path/to/cert'
    , {/*default request options*/}
  ));

WSSecurity

WSSecurity implements WS-Security. UsernameToken and PasswordText/PasswordDigest is supported.

  var wsSecurity = new WSSecurity(username, password, options)
    //the 'options' object is optional and contains properties:
    //passwordType: 'PasswordDigest' or 'PasswordText' default is PasswordText
    //hasTimeStamp: true or false, default is true
    //hasTokenCreated: true or false, default is true
  client.setSecurity(wsSecurity);

WSSecurityCert

WS-Security X509 Certificate support.

  var privateKey = fs.readFileSync(privateKeyPath);
  var publicKey = fs.readFileSync(publicKeyPath);
  var password = ''; // optional password
  var wsSecurity = new soap.WSSecurityCert(privateKey, publicKey, password, 'utf8');
  client.setSecurity(wsSecurity);

Note: Optional dependency 'ursa' is required to be installed successfully when WSSecurityCert is used.

ClientSSLSecurityPFX

  const pfxSecurity = new soap.ClientSSLSecurityPFX(pathToPfxOrFileBuffer, passphrase)
  client.setSecurity(pfxSecurity)

XML attributes

Handling XML attributes, value, and XML (wsdlOptions)

To override the default behavior of strong-soap, use the wsdlOptions object, passed in the createClient() method. The wsdlOptions has the following properties:

var wsdlOptions = {
  attributesKey: 'theAttrs',
  valueKey: 'theVal',
  xmlKey: 'theXml'
}

If you call createClient() with no options (or an empty Object {}), strong-soap defaults to the following:

Overriding the value key

By default, strong-soap uses $value as key for any parsed XML value which may interfere with your other code as it could be some reserved word, or the $ in general cannot be used for a key to start with.

You can define your own valueKey by passing it in the wsdl_options to the createClient call like so:

var wsdlOptions = {
  valueKey: 'theVal'
};

soap.createClient(__dirname + '/wsdl/default_namespace.wsdl', wsdlOptions, function (err, client) {
  // your code
});

Overriding the xml key

As valueKey, strong-soap uses $xml as key. The xml key is used to pass XML Object without adding namespace or parsing the string.

Example :

dom = {
     $xml: '<parentnode type="type"><childnode></childnode></parentnode>'
};
<tns:dom>
    <parentnode type="type">
          <childnode></childnode>
    </parentnode>
</tns:dom>

You can define your own xmlKey by passing it in the wsdl_options to the createClient call like this:

var wsdlOptions = {
  xmlKey: 'theXml'
};

soap.createClient(__dirname + '/wsdl/default_namespace.wsdl', wsdlOptions, function (err, client) {
  // your code
});

Overriding the attributes key

You can achieve attributes like:

<parentnode>
  <childnode name="childsname">
  </childnode>
</parentnode>

By attaching an attributes object to a node.

{
  parentnode: {
    childnode: {
      $attributes: {
        name: 'childsname'
      }
    }
  }
}

However, "attributes" may be a reserved key for some systems that actually want a node:

<attributes>
</attributes>

In this case you can configure the attributes key in the wsdlOptions like this:

var wsdlOptions = {
  attributesKey: '$attributes'
};

Adding xsiType

soap.createClient(__dirname + '/wsdl/default_namespace.wsdl', wsdlOptions, function (err, client) {
  client.*method*({
    parentnode: {
      childnode: {
        $attributes: {
          $xsiType: "{xmlnsTy}Ty"
        }
      }
    }
  });
});

Removing the xsiType. The resulting Request shouldn't have the attribute xsiType

soap.createClient(__dirname + '/wsdl/default_namespace.wsdl', wsdlOptions, function (err, client) {
  client.*method*({
    parentnode: {
      childnode: {
        $attributes: {

        }
      }
    }
  });
});

To see it in practice, consider the sample in: test/request-response-samples/addPets__force_namespaces

XMLHandler

XMLHandler enables you to to convert a JSON object to XML and XML to a JSON object. It can also parse an XML string or stream into the XMLBuilder tree.

API to convert JSON object to XML and XML to JSON object:

var soap = require('..').soap;
var XMLHandler = soap.XMLHandler;
var xmlHandler = new XMLHandler();
var util = require('util');
var url = 'http://www.webservicex.net/stockquote.asmx?WSDL';

var requestArgs = {
  symbol: 'IBM'
};

var options = {};
var clientOptions = {};
soap.createClient(url, clientOptions, function(err, client) {
  var customRequestHeader = {customheader1: 'test1'};
  client.GetQuote(requestArgs, function(err, result, envelope, soapHeader) {
    // Convert 'result' JSON object to XML
    var node = xmlHandler.jsonToXml(null, null,
      XMLHandler.createSOAPEnvelopeDescriptor('soap'), result);
    var xml = node.end({pretty: true});
    console.log(xml);

    // Convert XML to JSON object
    var root = xmlHandler.xmlToJson(null, xml, null);
    console.log('%s', util.inspect(root, {depth: null}));

  }, options, customRequestHeader);
});

Parse XML string or stream into the XMLBuilder tree:

var root = XMLHandler.parseXml(null, xmlString);

WSDL

wsdl.open(wsdlURL, options, callback(err, wsdl))

Loads WSDL into a tree form. Traverse through WSDL tree to get to bindings, services, ports, operations, and so on.

Parameters:

var soap = require('..').soap;
var WSDL = soap.WSDL;
var path = require('path');

// Pass in WSDL options if any

var options = {};
WSDL.open('./wsdls/stockquote.wsdl',options,
  function(err, wsdl) {
    // You should be able to get to any information of this WSDL from this object. Traverse
    // the WSDL tree to get  bindings, operations, services, portTypes, messages,
    // parts, and XSD elements/Attributes.

    var getQuoteOp = wsdl.definitions.bindings.StockQuoteSoap.operations.GetQuote;
    // print operation name
    console.log(getQuoteOp.$name);
    var service = wsdl.definitions.services['StockQuote'];
    //print service name
    console.log(service.$name);
});

wsdl.openSync(wsdlURL, options)

Loads WSDL into a tree form directly from memory. It traverses through WSDL tree to get to bindings, services, ports, operations, and so on as long as you have your dependent WSDLs and schemas are loaded and available in the options.WSDL_CACHE. If any I/O is required to retrieve any dependencies this call will throw an error.

Parameters:

An example of loading WSDLs into your options.WSDL_CACHE and calling wsdl.loadSync() can be found in the test test/wsdl-load-from-memory-test

Server

soap.listen(server, path, services, wsdl)

Creates a new SOAP server that listens on path and provides services.

wsdl is an xml string that defines the service.

  var myService = {
      MyService: {
          MyPort: {
              MyFunction: function(args) {
                  return {
                      name: args.name
                  };
              },

              // This is how to define an asynchronous function.
              MyAsyncFunction: function(args, callback) {
                  // do some work
                  callback({
                      name: args.name
                  });
              },

              // This is how to receive incoming headers
              HeadersAwareFunction: function(args, cb, headers) {
                  return {
                      name: headers.Token
                  };
              },

              // You can also inspect the original `req`
              reallyDetailedFunction: function(args, cb, headers, req) {
                  console.log('SOAP `reallyDetailedFunction` request from ' + req.connection.remoteAddress);
                  return {
                      name: headers.Token
                  };
              }
          }
      }
  };

  var xml = require('fs').readFileSync('myservice.wsdl', 'utf8'),
      server = http.createServer(function(request,response) {
          response.end("404: Not Found: " + request.url);
      });

  server.listen(8000);
  soap.listen(server, '/wsdl', myService, xml);

An example of using the SOAP server is in test/server-client-document-test

Options

You can pass in server and WSDL Options using an options hash.

var xml = require('fs').readFileSync('myservice.wsdl', 'utf8');

soap.listen(server, {
    // Server options.
    path: '/wsdl',
    services: myService,
    xml: xml,

    // WSDL options.
    attributesKey: 'theAttrs',
    valueKey: 'theVal',
    xmlKey: 'theXml'
});

Server logging

If the log method is defined it will be called with 'received' and 'replied' along with data.

  server = soap.listen(...)
  server.log = function(type, data) {
    // type is 'received' or 'replied'
  };

Server events

Server instances emit the following events:

The sequence order of the calls is request, headers and then the dedicated service method.

    test.soapServer.on('request', function requestManager(request, methodName) {
      assert.equal(methodName, 'GetLastTradePrice');
      done();
    });

An example of using the SOAP server is in test/server-test

SOAP Fault

A service method can reply with a SOAP Fault to a client by throwing an object with a Fault property.

Example SOAP 1.1 Fault:

    test.service = {
      DocLiteralWrappedService: {
        DocLiteralWrappedPort: {
          myMethod: function (args, cb, soapHeader) {
            throw {
              Fault: {
                  faultcode: "sampleFaultCode",
                  faultstring: "sampleFaultString",
                  detail:
                    { myMethodFault:
                      {errorMessage: 'MyMethod Business Exception message', value: 10}
                    }
                }
            }
          }
        }
      }
    }

SOAP 1.2 Fault:

    test.service = {
      DocLiteralWrappedService: {
        DocLiteralWrappedPort: {
          myMethod: function (args, cb, soapHeader) {
            throw {
              Fault: {
                Code: {
                  Value: "soap:Sender",
                  Subcode: { Value: "rpc:BadArguments" }
                },
                Reason: { Text: "Processing Error" },
                Detail:
                {myMethodFault2:
                   {errorMessage2: 'MyMethod Business Exception message', value2: 10}
                }
              }
            }
          }
        }
      }
    }

Examples of SOAP 1.1/SOAP 1.2 Fault response can be found in test test/server-client-document-test

Server security example using PasswordDigest

If server.authenticate is not defined then no authentication will take place.

  server = soap.listen(...)
  server.authenticate = function(security) {
    var created, nonce, password, user, token;
    token = security.UsernameToken, user = token.Username,
            password = token.Password, nonce = token.Nonce, created = token.Created;
    return user === 'user' && password === soap.passwordDigest(nonce, created, 'password');
  };

Server connection authorization

The server.authorizeConnection method is called prior to the soap service method. If the method is defined and returns false then the incoming connection is terminated.

  server = soap.listen(...)
  server.authorizeConnection = function(req) {
    return true; // or false
  };

SOAP headers

Received SOAP headers

A service method can look at the SOAP headers by providing a third arguments.

  {
      HeadersAwareFunction: function(args, cb, headers) {
          return {
              name: headers.Token
          };
      }
  }

It is also possible to subscribe to the 'headers' event. The event is triggered before the service method is called, and only when the SOAP Headers are not empty.

  server = soap.listen(...)
  server.on('headers', function(headers, methodName) {
    // It is possible to change the value of the headers
    // before they are handed to the service method.
    // It is also possible to throw a SOAP Fault
  });

First parameter is the Headers object; second parameter is the name of the SOAP method that will called (in case you need to handle the headers differently based on the method).

Outgoing SOAP headers

Both client and server can define SOAP headers that will be added to what they send. They provide the following methods to manage the headers.

addSoapHeader(value, qname)

Adds soapHeader to soap:Header node.

Parameters:

addSoapHeader(value, qname, options);

Returns the index where the header is inserted.

changeSoapHeader(index, value, qname)

Changes an existing soapHeader.

Parameters:

getSoapHeaders()

Returns all defined headers.

clearSoapHeaders()

Removes all defined headers.

Examples of using SOAP header API are in: test/server-test and test/server-test

soap-stub

Unit testing services that use SOAP clients can be very cumbersome. To get around this you can use soap-stub in conjunction with sinon to stub soap with your clients.

Example

var sinon = require('sinon');
var soapStub = require('strong-soap/soap-stub');

var urlMyApplicationWillUseWithCreateClient = './example/stockquote.wsdl';
var clientStub = {
  SomeOperation: sinon.stub()
};

clientStub.SomeOperation.respondWithError = soapStub.createRespondingStub({error: 'error'});
clientStub.SomeOperation.respondWithSuccess = soapStub.createRespondingStub({success: 'success'});
// or if you are using promises
clientStub.SomeOperation.respondWithError = soapStub.createRespondingStubAsync({error: 'error'});
clientStub.SomeOperation.respondWithSuccess = soapStub.createRespondingStubAsync({success: 'success'});


soapStub.registerClient('my client alias', urlMyApplicationWillUseWithCreateClient, clientStub);


var fs = require('fs'),
  assert = require('assert'),
  request = require('@cypress/request'),
  http = require('http'),
  lastReqAddress;

describe('myService', function() {
  var clientStub;
  var myService;

  beforeEach(function() {
    clientStub = soapStub.getStub('my client alias');
    soapStub.reset();
    myService = clientStub;
  });

  describe('failures', function() {
    beforeEach(function() {
      clientStub.SomeOperation.respondWithError();
    });

    it('should handle error responses', function() {
      myService.SomeOperation(function(err, response) {
        // handle the error response.
      });
    });
  });
});

Contributors