Send back a response from your Joule

To send back a response you will need to include the joule-node-response module, instantiate a Response object and call its send() method. These are all of the methods you'll call to construct your response.

  • setContext(context) - You must pass the context passed into your exports.handler function into this method.
  • setContentType(string) - You can pass a content type to return a Content-Type HTTP header. The default is application/json.
  • setHttpStatusCode(int code) - You can pass in the numeric HTTP status code you'd like to send in your response. The default is 200 and supported status codes are 200, 201, 202, 400, 401, 403, 404, 409 and 500.
  • setHeader(string name, string value) - You can call this numerous times and pass in HTTP headers by name and value.
  • send(mixed data) - You must pass a string or object which will be used as your Joule's response body. If you pass a on object then make sure to set the response to be application/json.

The joule-node-response module should already be in the Joule's package.json. It's available via npm.

How to use

Success example

// require the response module
var Response = require('joule-node-response');

exports.handler = function(event, context) {
  var response = new Response();
  response.setContext(context);

  // At some point you will have result data you want to return in the response
  var result = {
      user: {
          user_id: 12345,
          username: "foo",
          email: "bar@joule.run"
      }
  };

  // send back a 200 response with your result
  response.send(result);
}

This is the response that the caller will receive along with a 200 HTTP status.

{
    user: {
        user_id: 12345,
        username: "foo",
        email: "bar@joule.run"
    }
}

Error example

// if you want to send back an error
// require the response module
var Response = require('joule-node-response');

exports.handler = function(event, context) {
  var response = new Response();
  response.setContext(context);

  // At some point you will have error data you want to return in the response
  var result = {
      error: {
          message: "User not found"
      }
  };

  // send back a 404 with the error result
  response.setHttpStatusCode(404);
  response.send(result);
}

The caller will get this response:

{
    error: {
        message: "User not found"
    }
}

Alternative content type example

// require the response module
var Response = require('joule-node-response');

exports.handler = function(event, context) {
  var response = new Response();
  response.setContext(context);

  // At some point you will have result data you want to return in the response
  var result = '<Response><Sms>Sms body content</Sms></Response>';

  // send back the raw XML
  response.setContentType('application/xml');
  response.send(result);
}

The caller will get this response:

<Response><Sms>Sms body content</Sms></Response>