Writing Functions with JavaScript

In FaasPlus, each function operates within a code block that follows a specific structure. This structure ensures consistency, flexibility, and access to necessary tools and data. The following guidelines outline the required function template, available request properties, and how to make external calls.

Function Template

All functions in FaasPlus must follow this standard template:

const handleRequest = async () => {
  return 'OK';
};

This template ensures that every function is structured to handle asynchronous requests, allowing you to focus on your function’s logic while FaasPlus handles execution.

Using the req Object

If your function requires access to request data, such as JSON body or query parameters, you can use the req object as a parameter in the function:

const handleRequest = async (req) => {
  // Access JSON body data
  const data = req.body;

  // Access query string parameters
  const params = req.params;

  // Access workspace variables
  const variables = req.variables;

  return 'Data processed';
};

Using req allows your function to work with incoming request data:

  • req.body: Contains the JSON body of the request, enabling you to access and manipulate payload data. For instance if you need to get request body value of firstName you can write req.body.firstName it will get the post body firstName value
  • req.params: Holds query string parameters, useful for handling data passed via the URL. For instance if you wanna get fullName from querystring ?fullName=John you can use req.params.fullName
  • req.variables: Contains workspace-level variables, providing access to any predefined configurations or constants relevant to your function. If your workspace has baseUrl variables you can access it via req.variables.baseUrl

Making External Calls with fetch

If your function needs to interact with external services or APIs, you can use fetch by including it as a parameter in your function:

const handleRequest = async (fetch) => {
  // Example of making an external API call
  const response = await fetch('https://api.example.com/data');
  const data = await response.json();

  return data;
};

By using fetch, your function can retrieve data from external sources, post data to APIs, and handle responses. This integration provides flexibility for building functions that rely on external resources.

Summary

Following this function template ensures that your code is compatible with FaasPlus’s execution model. By adhering to the template, using the req object for request data, and leveraging fetch for external calls, you can build robust, responsive functions tailored to your application’s needs.