Navigation

Utility Packages

Overview

For developer convenience, MongoDB Stitch functions have access to utility packages provided through various global variables.

The following global utility packages are available in all functions:

Variable Description
console Includes standard console methods that output to the function editor’s debug console as well as your application logs.
JSON

Includes methods that convert between string and object representations of standard JSON objects. This is a standard built-in object across most Javascript environments.

You can find full documentation for the JSON package on MDN.

EJSON Includes methods that convert between string and object representations of MongoDB Extended JSON objects.
BSON Includes methods that construct and manipulate BSON objects.
utils.crypto Includes methods for working with cryptographic algorithms, such as HMAC, sha256, and md5. These methods are useful when your functions communicate with external HTTP services.

Utility Packages

console

console.log(arg...)

Logs information to the function editor debug console and your Stitch application’s logs. Accepts multiple arguments which are all included in the log output.

console.warn(arg...)

Logs a warning to the function editor debug console and your Stitch application’s logs. Accepts multiple arguments which are all included in the log output.

console.error(arg...)

Logs an error to the function editor debug console and your Stitch application’s logs. Accepts multiple arguments which are all included in the log output.

JSON

Includes methods that convert between string and object representations of standard JSON objects. This is a standard built-in object across most Javascript environments.

You can find full documentation for the JSON package on MDN.

JSON.parse(<json-string>)

Parses the provided string and attempts to convert it to a JavaScript object.

Parameter Type Description
<json-string> string A serialized string representation of a standard JSON object. Valid inputs include serialized object strings created by JSON.stringify() and EJSON.stringify().
Returns:A standard JSON object based on the provided JSON string.
JSON.stringify(<json-object>)

Serializes the provided JSON object to a string.

Parameter Type Description
<json-object> object A standard JSON object.
Returns:A string representation of the provided JavaScript object. The resulting Javascript object may contain BSON types.

EJSON

Includes methods that convert between string and object representations of MongoDB Extended JSON objects. EJSON is a superset of the JSON package.

EJSON.parse(<ejson-string>)

Parses the provided string and attempts to convert it to an EJSON object.

Parameter Type Description
<ejson-string> string A string representing serialized extended JSON.
Returns:A Javascript object representation of the provided EJSON string. The object may contain BSON types.
EJSON.stringify(<ejson-object>)

Serializes the provided EJSON object to a string.

Parameter Type Description
<ejson-object> document An EJSON object. The object may contain BSON types.
Returns:A string representation of the EJSON object.

BSON

BSON provides functions for constructing and manipulating BSON types.

Note

To avoid ambiguity with the $regex EJSON type, queries with the $regex operator must use a BSON.BSONRegExp.

Creating Explicit BSON types

The BSON global can be used to construct explicit BSON types. The following are the available BSON types in MongoDB Stitch:

Type Description Example
BSON.Binary A string of bytes. BSON.Binary.fromHex("a5f8c1", 0);
BSON.Code Embedded Javascript code. BSON.Code("var x = 123;");
BSON.DBPointer (Deprecated) A reference to another document. BSON.DBPointer("db.coll", BSON.ObjectId("5a14179d01236a9fc1086df6"));
BSON.DBRef A reference to another document. BSON.DBRef("db.coll", BSON.ObjectId("5a14179d01236a9fc1086df6"));
BSON.Decimal128 A 128 bit decimal. BSON.Decimal128.fromString("1.23");
BSON.Double A 64 bit double. BSON.Double(1.23);
BSON.Int32 A 32 bit signed integer. BSON.Int32(123);
BSON.Long A 64 bit signed integer. BSON.Long(0x00000000, 0x40000000);
BSON.MaxKey A value that compares higher than all other BSON values. BSON.MaxKey;
BSON.MinKey A value that compares lower than all other BSON values. BSON.MinKey;
BSON.ObjectId A 12 byte object ID. BSON.ObjectId("5a14179d01236a9fc1086df6");
BSON.BSONRegExp A regular expression. BSON.BSONRegExp("^test*", "i");
BSON.Symbol (Deprecated) A symbol. BSON.Symbol("symbol");
BSON.Timestamp Contains a 32 bit timestamp and 32 bit counter. For working with dates use Date. BSON.Timestamp(1511266261367, 0);

More information about BSON types can be found on BSON Types.

BSON.Binary

BSON.Binary has the following methods.

BSON.Binary.fromHex(hexString, subType)

Constructs a BSON.Binary from data represented as a hexadecimal string.

Parameter Type Description
hexString string A string of hexadecimal characters (0-9 and A-F). This must be byte aligned or an exception is thrown.
subType integer An integer in the range of 0-255. The value 0 represents generic binary. Other sub-types are documented on the BSON spec.
Returns:A BSON.Binary.
BSON.Binary.toHex()

Returns the BSON.Binary data represented as a hexadecimal string.

Returns:A string.
BSON.Binary.fromBase64(base64String, subType)

Constructs a BSON.Binary from data represented as a base64 string.

Parameter Type Description
base64String string A string of base64 encoded characters.
subType integer An integer in the range 0-255. The value 0 represents generic binary. Other sub-types are documented on the BSON spec.
Returns:A BSON.Binary.
BSON.Binary.toBase64()

Returns the BSON.Binary data represented as a base64 string.

Returns:A string.
BSON.Binary.text()

Returns a string representation of the data as UTF-8 encoded characters.

Returns:A string.
BSON.Decimal128
BSON.Decimal128.fromString(decimalString)

Constructs a BSON.Decimal128 from a string representation of a decimal number.

Parameter Type Description
decimalString string A string representing a decimal number. E.g. “123.45”.
Returns:A BSON.Decimal128.
BSON.Long

A BSON.Long is a 64 bit signed integer.

BSON.Long(low32, high32)

Constructs a BSON.Long from two 32 bit integers representing the low 32 bits and the high 32 bits.

Parameter Type Description
low32 integer Optional. Represents the low 32 bits of the BSON.Long.
high32 integer Optional. Represents the high 32 bits of the BSON.Long.
Returns:A BSON.Long. If no arguments are supplied the value returned is 0.

Examples

BSON can be used to return explicit BSON types.

exports = function() {
   return {
      a: BSON.Long(10),
      b: BSON.ObjectId("5a14179d01236a9fc1086df6"),
      c: BSON.Code("var x = 1"),
      d: new Date()
   };
};

utils.crypto

The crypto utility provides methods for working with cryptographic algorithms.

utils.crypto.hmac(input, secret, hash_function, output_format)

Generates an HMAC signature from the provided input and secret. This is useful when communicating with third-party HTTP services that require signed requests.

Parameter Type Description
input string The input for which you would like to generate a signature.
secret string The secret key to use when generating the signature.
hash_function string The name of the hashing function to use when generating the signature. The following functions are supported: "sha1", "sha256", "sha512".
output_format string The format of the generated signature. Can be either "hex" for a hex string, or "base64" for a Base64 string.
Returns:The signature of the input, in the format specified by output_format.
utils.crypto.hash(hash_function, input)

Generates a hash value for the provided input using the specified hash function.

Parameter Type Description
hash_function string The name of the hashing function. The following functions are supported: "sha1", "sha256", "md5".
input string or BSON.Binary Required. The input for which you would like to generate a hash value.
Returns:A hash value for the provided input generated by the specified hashing function.

Example

The API for Coinbase allows developers to make HTTP requests on behalf of their account by using an API key and by signing the requests with a secret. This page on their documentation gives an overview of the mechanics.

The following example shows a function using utils.crypto.hmac to sign a request to the Coinbase API. The function requests a list of transactions from the primary wallet of the user associated with the API key and secret.

Note

This function assumes the existence of an HTTP service named coinbase with a rule that allows GET requests to api.coinbase.com. It also assumes the existence of values named coinbase_api_key and coinbase_secret that are populated appropriately.

The API key configured in Coinbase must also allow the wallet:transactions:read scope for the request to complete successfully with a 200 OK status.

exports = function() {
  const cur_unix_time = Math.floor(Date.now() / 1000);
  const api_url = "https://api.coinbase.com";
  const request_path = "/v2/accounts/primary/transactions";

  const message = cur_unix_time.toString() + "GET" + request_path;
  const signature = utils.crypto.hmac(message, context.values.get("coinbase_secret"), "sha256", "hex");

  const coinbase = context.services.get("coinbase")
  const response = await coinbase.get({
    url: api_url + request_path,
    headers: {
      "CB-ACCESS-SIGN": [signature],
      "CB-ACCESS-TIMESTAMP": [cur_unix_time.toString()],
      "CB-ACCESS-KEY": [context.values.get("coinbase_api_key")]
    }
  });

  return EJSON.parse(response.body.text());
};
←   Context Modules Triggers  →