{
  "version": 12,
  "name": "15_code_blocks",
  "description": "Example: code blocks (async JavaScript). Shows: reading the previous response, the built-in assertion helpers (Functions panel), setting $variables from code, requests embedded in code and called in a loop with request(id, { $var }), ad-hoc calls with http(), reading project files with readFile(), and writing reports with saveFile().\nNeeds the 'run code' permission.",
  "globals": [
    {
      "name": "$dummy",
      "value": "https://dummyjson.com"
    },
    {
      "name": "$httpbin",
      "value": "https://httpbin.org"
    },
    {
      "name": "$category",
      "value": "laptops"
    }
  ],
  "globalFunctions": "// Assertion helpers, built on check(label, pass, details).\n// Each records a pass / fail line in the log and the report.\n// A failed one fails its step when the step is done;\n// the code keeps running. Change them or add your own.\n// r defaults to the last response.\n\nfunction assertTrue(value, label = \"is true\") {\n  return check(label, Boolean(value), { actual: value, expected: true });\n}\n\nfunction assertEqual(actual, expected, label = \"equals \" + JSON.stringify(expected)) {\n  return check(label, isEqual(actual, expected), { actual, expected });\n}\n\nfunction assertNotEqual(actual, unexpected, label = \"does not equal \" + JSON.stringify(unexpected)) {\n  return check(label, !isEqual(actual, unexpected), { actual, expected: \"not \" + JSON.stringify(unexpected) });\n}\n\n// text contains a part, or a list contains an item\nfunction assertContains(haystack, needle, label = \"contains \" + JSON.stringify(needle)) {\n  const pass = Array.isArray(haystack) ? haystack.some((x) => isEqual(x, needle)) : String(haystack).includes(needle);\n  return check(label, pass, { actual: haystack, expected: needle });\n}\n\nfunction assertMatch(text, regex, label = \"matches \" + regex) {\n  return check(label, new RegExp(regex).test(String(text)), { actual: text, expected: String(regex) });\n}\n\nfunction assertLessThan(actual, limit, label = \"< \" + limit) {\n  return check(label, Number(actual) < Number(limit), { actual, expected: \"< \" + limit });\n}\n\nfunction assertGreaterThan(actual, limit, label = \"> \" + limit) {\n  return check(label, Number(actual) > Number(limit), { actual, expected: \"> \" + limit });\n}\n\n// expected: 200, \"2xx\", or a list such as [200, 201]\nfunction assertStatus(expected, r = response) {\n  const list = [].concat(expected).map(String);\n  const status = String(r && r.status);\n  const pass = list.some((e) => e === status || (/^[1-5]xx$/i.test(e) && e[0] === status[0]));\n  return check(\"status is \" + list.join(\" or \"), pass, { actual: r && r.status, expected });\n}\n\nfunction assertTimeBelow(ms, r = response) {\n  return check(\"time < \" + ms + \" ms\", Boolean(r) && r.timeMs < ms, { actual: r && r.timeMs, expected: \"< \" + ms });\n}\n\n// without expected, the header only has to exist\nfunction assertHeader(name, expected, r = response) {\n  const value = r ? r.headers[String(name).toLowerCase()] : undefined;\n  if (expected === undefined) return check(\"header \" + name + \" exists\", value !== undefined, { actual: value });\n  return check(\"header \" + name + \" equals \" + expected, String(value) === String(expected), { actual: value, expected });\n}\n\n// e.g. assertJsonPath(\"$.items[0].id\", 42); without expected, the value only has to exist\nfunction assertJsonPath(path, expected, r = response) {\n  const value = jsonPath(path, r);\n  if (expected === undefined) return check(path + \" exists\", value !== undefined, { actual: value });\n  return check(path + \" equals \" + JSON.stringify(expected), isEqual(value, expected), { actual: value, expected });\n}\n\n// schema: a JSON Schema object\nfunction assertSchema(schema, r = response) {\n  const result = validateSchema(r, schema);\n  return check(\"matches the JSON Schema\", result.valid, { error: result.errors || undefined });\n}\n",
  "libraries": [],
  "activeEnvironment": "",
  "auth": {
    "type": "none"
  },
  "settings": {},
  "data": {
    "file": ""
  },
  "cookies": [],
  "tags": [
    "example",
    "code",
    "scripting"
  ],
  "steps": [
    {
      "id": "list",
      "method": "GET",
      "name": "List products of a category",
      "params": [
        {
          "name": "select",
          "value": "title,price,rating"
        }
      ],
      "type": "request",
      "url": "$dummy/products/category/$category"
    },
    {
      "code": "const data = JSON.parse(response.body);\nassertStatus(200);\nassertGreaterThan(data.total, 0, \"the category has products\");\nassertTrue(data.products.every((p) => p.price > 0), \"every product has a price\");\n\n// Variables set in code are visible to every later step.\n$productIds = data.products.slice(0, 3).map((p) => p.id);\n$cheapest = data.products.reduce((a, b) => (a.price < b.price ? a : b));\nlog(`${data.total} ${$category}; cheapest: ${$cheapest.title} at $${$cheapest.price}`);",
      "id": "inspect",
      "name": "Inspect the response with assertion helpers",
      "type": "code"
    },
    {
      "code": "// The request box below is called once per id; the local value is passed in as $pid.\n$ratings = [];\nfor (const id of $productIds) {\n  const res = await request(\"rq_product01\", { $pid: id });\n  const p = JSON.parse(res.body);\n  assertEqual(p.id, id, `product ${id} returned`);\n  $ratings.push({ id: p.id, title: p.title, rating: p.rating });\n}\nlog(\"ratings:\", JSON.stringify($ratings));",
      "id": "loop-requests",
      "name": "Loop over ids with an embedded request",
      "requests": [
        {
          "checks": [
            {
              "op": "equals",
              "target": "status",
              "value": "200"
            }
          ],
          "id": "rq_product01",
          "method": "GET",
          "name": "Product by id",
          "params": [
            {
              "name": "select",
              "value": "title,rating"
            }
          ],
          "url": "$dummy/products/$pid"
        }
      ],
      "type": "code"
    },
    {
      "code": "// http() sends a request straight from code (same cookies, proxy and settings as the flow).\nconst csv = readFile(\"customers.csv\");\nconst r = await http({ method: \"POST\", url: `${$httpbin}/post`, headers: { \"Content-Type\": \"text/csv\" }, body: csv });\nconst echo = JSON.parse(r.body);\nassertEqual(r.status, 200, \"httpbin accepted the CSV\");\nassertEqual(echo.data, csv, \"the body arrived unchanged\");\n$customerCount = csv.trim().split(\"\\n\").length - 1;\nlog(`${$customerCount} customers uploaded`);",
      "id": "adhoc-http",
      "name": "Ad-hoc call with http() and a project file",
      "type": "code"
    },
    {
      "code": "const best = [...$ratings].sort((a, b) => b.rating - a.rating)[0];\nconst path = saveFile(\"reports/code-blocks-summary.json\", {\n  category: $category,\n  cheapest: { id: $cheapest.id, title: $cheapest.title, price: $cheapest.price },\n  bestRated: best,\n  customersUploaded: $customerCount,\n  finishedAt: new Date().toISOString(),\n});\nlog(\"report saved to\", path);",
      "id": "report",
      "name": "Save a JSON report to the run folder",
      "type": "code"
    }
  ]
}
