Compute WritingCode Nodejs - scootrio/scootr-aws GitHub Wiki

Writing Code for the Node.js Runtime

The Scootr AWS Driver uses AWS Lambda to deploy compute resources to the cloud. As such, the code you write will need to conform to the API specified by the AWS Lambda services. Generally speaking, how you write your handler will depend on the event triggering your handler and on any resource references you may be using. However, most handlers written in Node.js will adhere to the following format:

'use strict';

async function handler(event, context) {
  // Business logic for handling the event goes here.
  //
  // You can optionally return a value that will be handled depending on
  // the type of event that triggered the lambda function.
  console.log('Hello, world!');
}

module.exports = handler;

NOTE: The use of console logging functions inside the handler will log the provided arguments to the lambda functions CloudWatch Log Group. These logs are currently not accessible by the Scootr runtime library. Support for this feature is in progress.

Handling HTTP Events

The most common type of event used to trigger a compute resource in Scootr is the HTTP event. In AWS, this event maps to an API Gateway endpoint.

The Request

The JavaScript object below is a simplified example of what the event parameter might look like. The examples assumes a POST request has been made to the /users/{id} endpoint (where the value of 123 is used as the id URL path parameter):

event = {
    httpMethod: 'POST',
    path: '/users/123',

    // Parameters from the URL. All values are strings.
    pathParameters: {
        id: '123'
    },

    // Empty in this case. All values would be strings.
    queryStringParameters: {},

    // The raw request body. If the Content-Type of the request is
    // 'application/json', this would be a JSON formatted string
    body: '',

    // Key-value pairs of HTTP headers and their values
    headers: { ... },
};

To learn more about these and other properties on the event parameter passed to the handler function, see the documentation for using AWS Lambda with API Gateway.

The Response

When responding to an API Gateway event, you will use generally the following response format:

'use strict';

async function handler(event, context) {
  //
  // Do something with the event. Then, return a result
  // that will get sent as the HTTP response to the request.
  //
  return {
    statusCode: 200,
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ message: 'Hello, world!' })
  };
}

module.exports = handler;

For more information about the response object, see the response format for API Gateway Lambda integrations.

A Note About DRY Code and The AWS Response Format

It can be helpful to create a function that will create an HTTP response object that adheres to AWS Lambda's API that you can reuse in your handler depending on the type of response you need to send. Here is an example of how such a helper could be implemented:

function createJsonResponse(statusCode, body = {}, headers = {}) {
  return {
    statusCode,
    headers: {
      'Content-Type': 'application/json',
      ...headers
    },
    body: JSON.stringify(body)
  };
}

You could then use the createJsonResponse function as follows in your handler:

async function handler(event) {
  try {
    const response = await someAsynchronousComputationThatCouldFail();
    return createJsonResponse(200, { message: 'Success', data: response });
  } catch (err) {
    return createJsonReponse(500, { message: 'Failure', details: err.message });
  }
}

What's Next?

Check out the AWS SDKs for Node.js by visiting the supported runtimes page.