Navigation

Access Function Context

Overview

Stitch functions are aware of the context in which they were called and can behave dynamically based on that context. A function’s context includes application components, such as external services and other functions, as well as execution information, such as the profile of the user that was logged in when the function was called.

You can access all aspects of a function’s context in the function’s source code with the context global variable.

Application Components

Call a Function

You can call any function in your application from a function with the context.functions global variable.

// difference: subtracts b from a using the sum function
exports = function(a, b) {
    return context.functions.execute("sum", a, -1 * b);
};

Connect to an External Service

You can connect to a configured external service from a function by instantiating a service client with the context.services global variable. Any service actions for which you’ve configured rules are available as methods on the service client.

exports = function() {
  // Instantiate a service client for the HTTP Service named "myHttpService"
  const http = context.services.get("myHttpService");
  // Call the HTTP service's `get` action (if the service rules allow it)
  return http.get({ url: "https://www.mongodb.com" });
};

Access Global Values

You can access global values in a function with the context.values global variable.

exports = function() {
  // Get a global value (or `undefined` if no value has the specified name)
  const theme = context.values.get("theme");
  console.log(theme.colors)     // Output: { red: "#ee1111", blue: "#1111ee" }
  console.log(theme.colors.red) // Output: "#ee1111"
};

Execution Information

Get User Information

You can access the user object of the logged in user that called a function with the context.user global variable.

exports = function() {
  const currentUser = context.user
  console.log(currentUser.id)
}

Get Request Information

You can access information about the external HTTP call that initiated a function’s execution with the context.request global variable.

exports = function() {
  const request = context.request;
  if (request.httpReferrer == "https://www.example.com/") {
    applyPercentageDiscount(10);
  }
}