npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

sloosh

v1.1.0

Published

A minimal node SOAP client with graceful metainformation handling

Downloads

3

Readme

About this fork

This repository is a fork of this repo. We decided to fork that because we needed changes in this module which break the backward compatibility of the module. The only thing that was chanegd is the way module handles the metainformation of response:

See this section for more details.

Original

  client.someMethod(args, function (err, result) {
    // `result` is deserialized response
    // client.lastRequest, client.lastResponse - raw XML request and response
  });

Now it looks like this

  client.someMethod(args, function (err, result) {
    // `result` is deserialized response
    // `result.$meta` is a property that stores the metainformation about the request and response.
  });

Therefore client object won't be mutated after requests staying idempotent object.

Features:

  • Very simple API
  • Handles both RPC and Document schema types
  • Supports multiRef SOAP messages (thanks to @kaven276)
  • Support for both synchronous and asynchronous method handlers
  • WS-Security (currently only UsernameToken and PasswordText encoding is supported)

Install

Install with npm:

  npm install soap

Module

soap.createClient(url[, options], callback) - create a new SOAP client from a WSDL url. Also supports a local filesystem path.

  var soap = require('soap');
  var url = 'http://example.com/wsdl?wsdl';
  var args = {name: 'value'};
  soap.createClient(url, function(err, client) {
      client.MyFunction(args, function(err, result) {
          console.log(result);
      });
  });

Within the options object you may provide an endpoint property in case you want to override the SOAP service's host specified in the .wsdl file.

soap.listen(server, path, services, wsdl) - create 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
                  };
              }
          }
      }
  }

  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);

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:

  • request - Emitted for every received messages. The signature of the callback is function(request, methodName).
  • headers - Emitted when the SOAP Headers are not empty. The signature of the callback is function(headers, methodName).

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

SOAP Fault

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

  throw {
    Fault: {
      Code: {
        Value: "soap:Sender",
        Subcode: { value: "rpc:BadArguments" }
      },
      Reason: { Text: "Processing Error" }
    }
  };

SOAP Headers

A service method can look at the SOAP headers by providing a 3rd 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).

server security example using PasswordDigest

If server.authenticate is not defined no authentation 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

This is called prior to soap service method If the method is defined and returns false the incoming connection is terminated.

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

Client

An instance of Client is passed to the soap.createClient callback. It is used to execute methods on the soap service.

Client.describe() - description of services, ports and methods as a JavaScript object

  client.describe() // returns
    {
      MyService: {
        MyPort: {
          MyFunction: {
            input: {
              name: 'string'
            }
          }
        }
      }
    }

Client.setSecurity(security) - use the specified security protocol

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

  • addOptions - a method that accepts an options arg that is eventually passed directly to request
  • toXML - a method that reurns a string of XML.

By default there are 3 protocols:

####BasicAuthSecurity

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

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

  • rejectUnauthorized: false
  • strictSSL: false
  • secureOptions: constants.SSL_OP_NO_TLSv1_2//this is likely needed for node >= 10.0
  client.setSecurity(new soap.ClientSSLSecurity(
    '/path/to/key'
    , '/path/to/cert'
    , {/*default request options*/}
  ));

####WSSecurity

  client.setSecurity(new soap.WSSecurity('username', 'password'))

####BearerSecurity

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

Client.method(args, callback) - call method on the SOAP service.

  client.MyFunction({name: 'value'}, function(err, result) {
      // result is a javascript object
      // result.$meta is a hidden property to access for metainformation
  });

  See [this section](https://github.com/franza/sloosh#response) for more details.

See Response section for details.

Client.service.port.method(args, callback[, options]) - 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 here.
  • 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})

Client.addSoapHeader(soapHeader[, name, namespace, xmlns]) - add soapHeader to soap:Header node

Options

  • soapHeader Object({rootName: {name: "value"}}) or strict xml-string
Optional parameters when first arg is object :
  • name Unknown parameter (it could just a empty string)
  • namespace prefix of xml namespace
  • xmlns URI

Client Events

Client instances emit the following events:

  • request - Emitted before a request is sent. The event handler receives the entire Soap request (Envelope) including headers.
  • message - Emitted before a request is sent. The event handler receives the Soap body contents. Useful if you don't want to log /store Soap headers.
  • soapError - Emitted when an erroneous response is received. Useful if you want to globally log errors.
  • response - Emitted after a response is received. The event handler receives the entire response body. This is emitted for all responses (both success and errors).

WSSecurity

WSSecurity implements WS-Security. UsernameToken and PasswordText/PasswordDigest is supported. An instance of WSSecurity is passed to Client.setSecurity.

  new WSSecurity(username, password, passwordType)
    //'PasswordDigest' or 'PasswordText' default is PasswordText

Handling XML Attributes, Value and XML (wsdlOptions).

Sometimes it is necessary to override the default behaviour of sloosh in order to deal with the special requirements of your code base or a third library you use. Therefore you can use the wsdlOptions Object, which is passed in the #createClient() method and could have any (or all) of the following contents:

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

If nothing (or an empty Object {}) is passed to the #createClient() method, the sloosh defaults (attributesKey: 'attributes', valueKey: '$value' and xmlKey: '$xml') are used.

###Overriding the value key By default, sloosh 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, sloosh 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 so:

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 so.

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

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

Handling "ignored" namespaces

If an Element in a schema definition depends on an Element which is present in the same namespace, normally the tns: namespace prefix is used to identify this Element. This is not much of a problem as long as you have just one schema defined (inline or in a separate file). If there are more schema files, the tns: in the generated soap file resolved mostly to the parent wsdl file, which was obviously wrong.

sloosh now handles namespace prefixes which shouldn't be resolved (because it's not necessary) as so called ignoredNamespaces which default to an Array of 3 Strings (['tns', 'targetNamespace', 'typedNamespace']).

If this is not sufficient for your purpose you can easily add more namespace prefixes to this Array, or override it in its entirety by passing an ignoredNamespaces object within the options you pass in soap.createClient() method.

A simple ignoredNamespaces object, which only adds certain namespaces could look like this:

var options = {
  ignoredNamespaces: {
    namespaces: ['namespaceToIgnore', 'someOtherNamespace']
  }
}

This would extend the ignoredNamespaces of the WSDL processor to ['tns', 'targetNamespace', 'typedNamespace', 'namespaceToIgnore', 'someOtherNamespace'].

If you want to override the default ignored namespaces you would simply pass the following ignoredNamespaces object within the options:

var options = {
    ignoredNamespaces: {
      namespaces: ['namespaceToIgnore', 'someOtherNamespace'],
      override: true
    }
  }

This would override the default ignoredNamespaces of the WSDL processor to ['namespaceToIgnore', 'someOtherNamespace']. (This shouldn't be necessary, anyways).

Response

Response is an object which is deserialized from the XML response. It contains property $meta which contains metainformation about sent request and received response. $meta lives in object's prototype, so it is not enumerable and will not be included in the result of JSON.stringify.

Errors returned from the methods of client also contain metainformation in meta field.

Structure of meta:

{
  request: {
    xml: String,        // an XML representation of request
    headers: Object,    // HTTP headers of request
    message: String     // the body of SOAP request
  },
  response: {
    xml: String,        // an XML representation of response
    headers: Object,    // HTTP headers of response
    statusCode: Number  // status code of HTTP response
  },
  soapHeader: String    // the response soap header as a javascript object
}

Some of the properties above may be nullable, refer to the sources for details.

Contributors

Many thanks to original contributors of node-soap.