Skip to content

Use Case: Implement a SOAP Web Service

do- edited this page Dec 11, 2022 · 14 revisions

This scenario is basically serializing an object, with some extra wrapping.

Input

You have:

  • a WSDL file myService.wsdl stored in a local filesystem with all dependencies;
  • a function named myMethod (/*...*/) that calculates:
    • normally, a single property object {MyMethodResponse: {...}}, where MyMethodResponse is a local name of the element representing the corresponding message type;
    • otherwise, an Error is thrown.

Problem

Send the HTTP response rp representing the obtained result as a SOAP message.

Basic Solution

const {XMLSchemata, SOAP11, SOAP12, SOAPFault} = require ('xml-toolkit')

const SOAP = SOAP11 // or SOAP12

const xs = new XMLSchemata (`myService.wsdl`)

let body, statusCode; try {  
  body = xs.stringify (myMethod (/*...*/))
  statusCode = 200
}
catch (x) {
  body = new SOAPFault (x)
  statusCode = 500
}

rp.writeHead (statusCode, {
  'Content-Type': SOAP.contentType,
})

const xml = SOAP.message (body)
rp.end (xml)

Q&A

How to set the SOAP Header?

Provide its literal XML as the 2nd argument to SOAP.message

const xml = SOAP.message (body, header)

To add an empty Header element, use the zero length string ('').

For missing or null 2nd argument, SOAP Header is omitted.

How to add custom attributes to the SOAP Body and Header elements?

Use XMLSchemata.any argument instead of plain XML body and/or header.

For example: to add Id: "1" to the Body element, write

const xml = rp.end (SOAP.message ([body, {Id: 1}], header))

How to set detail and other extra fields for a SOAP Fault?

Pass it to the SOAPFault constructor: see the corresponding article for more information.

Clone this wiki locally