October 26, 2019

When adding a service in the Business Manager (Administration > Operations > Services) one of the types needs to be selected (like SOAP, FTP, etc.). They correspond with a specific service class when implementing the service call (dw.svc.SOAPService, dw.svc.FTPService, etc.). But how to pass parameters to a service with the type HTTPForm?

Let’s have a look on a simple example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
'use strict';

var LocalServiceRegistry = require('dw/svc/LocalServiceRegistry');
var HTTPRequestPart = require('dw/net/HTTPRequestPart');

function contact(contactForm) {
  const contactService = LocalServiceRegistry.createService('my.form.service', {
    createRequest: function (formService, formData) {
      return [
        new HTTPRequestPart('firstname', formData.firstname),
        new HTTPRequestPart('lastname', formData.lastname),
        new HTTPRequestPart('message', formData.message),
      ];
    },
    parseResponse: function (formService, client) {
      if (client.statusCode === 200) {
        return client.text;
      }
      throw new Error('service call not successful');
    },
  });

  var contactResponse = contactService.call(contactForm);

  if (contactResponse.ok) {
    return {
      success: true
    };
  }
  return {
    error: true
  };
}

module.exports = {
  contact: contact
};

The important part is to return the parameters as an array with dw.net.HTTPRequestPart objects. The POST call with the content-type "application/x-www-form-urlencoded" is handled internally by the dw.svc.HTTPFormService itself. The response still needs to be taken care of with the parseResponse(…​) implementation.

Contact