Libraries
The JavaScript libraries bundled with Relay and how scripts load them.
Declaration
const _ = require("lodash");
const { v4: uuidv4 } = require("uuid");Overview
Relay bundles the libraries that Postman scripts use most, so scripts can use them without a network connection or a package manager. Load one with require, or use its global name where it has one. A library loads the first time a script uses it in a send.
const signature = CryptoJS.HmacSHA256(relay.request.body.raw, relay.environment.get("webhookSecret"))
.toString(CryptoJS.enc.Hex);
relay.request.headers.upsert({ key: "X-Signature", value: signature });
const tomorrow = moment().add(1, "day").format("YYYY-MM-DD");
relay.variables.set("startDate", tomorrow);Topics
Bundled libraries
| Library | Version | require name | Global | Use it for |
|---|---|---|---|---|
| Ajv | 6.12.6 | ajv | Validating values against JSON Schemas (draft-07). | |
| chai | 4.5.0 | chai | chai | Assertions; expect and assert are built on it. |
| cheerio | 1.0.0 | cheerio | cheerio | Querying HTML with jQuery-style selectors. |
| crypto-js | 4.2.0 | crypto-js | CryptoJS | Hashes, HMACs, AES and encodings. |
| lodash | 4.17.21 | lodash | _ | Utilities for objects, arrays and strings. |
| moment | 2.30.1 | moment | moment | Parsing, formatting and doing arithmetic with dates. |
| uuid | 9.0.1 | uuid | Generating UUIDs, such as with v4(). | |
| xml2js | 0.6.2 | xml2js | Parsing XML into objects and building XML from them. |
require("atob") and require("btoa") return the global atob and btoa functions.
Loading a library
require(module)
require(module: string): anyReturns the library called module. Asking for any other module throws an error that lists the available ones.
Examples
Validate a value with Ajv
const Ajv = require("ajv");
const ajv = new Ajv({ allErrors: true });
const valid = ajv.validate({ type: "array", items: { type: "string" } }, relay.response.json().tags);
assert.isTrue(valid, ajv.errorsText());To validate the whole response body, relay.response.to.have.jsonSchema(schema) is shorter.
Read an HTML page with cheerio
const $ = cheerio.load(relay.response.text());
relay.environment.set("csrfToken", $("meta[name=csrf-token]").attr("content"));Parse XML with xml2js
const xml2js = require("xml2js");
xml2js.parseString(relay.response.text(), (error, result) => {
if (error) throw error;
console.log(result);
});For a quick synchronous parse, use the global xml2Json(text).
Discussion
Scripts run without Node, so libraries that need Node's modules, process or Buffer aren't available, and you can't install others. moment includes only its English locale, and cheerio is its slim build, which parses HTML with htmlparser2.
See Also
- Global functions: Timers, encoding, random values and the legacy Postman globals available to every script.
- expect: A function that starts a chai or Jest-style assertion about a value.