Skip to content

Feature: template blocks in JavaScript, Python, etc. #557

@juanMarinero

Description

@juanMarinero

Issues

  • I have checked existing issues and there are no existing ones with the same request.

Feature description

https://www.jetbrains.com/help/idea/exploring-http-syntax.html#response-handling states:

You can handle the response using JavaScript. Type the > character after the request and specify the path and name of the JavaScript file or put the response handler script code wrapped in {% ... %}.

This does not apply to this plugin (I think). Only Lua is practical in template blocks.
I.e. there is no direct JavaScript equivalent to request.variables.set. Nor for Python, etc.

Below I coded how to workaround with io.popen, but I insist, this is a workaround.

With Lua it's easy:

# @lang=lua
< {%
  -- Install base64 library
  --   sudo luarocks install base64

  local base64 = require("base64")
  local encoded = base64.encode("user:passwd")
  -- Set variables directly in the context
  request.variables.set("authHeader_Local_02", encoded)
%}
// Request (200)
GET https://httpbin.org/basic-auth/user/passwd
Authorization: Basic {{authHeader_Local_02}}
###

Pseudo-JavaScript: base64 user-pass for test JS in template blocks

# @lang=lua
< {%
  -- Use Lua to execute a Node.js command and capture its output
  local handle = io.popen('node -e "console.log(\\\"dXNlcjpwYXNzd2Q=\\\")"')
  local encoded = handle:read("*a")
  handle:close()
  
  -- Trim whitespace and newlines
  encoded = encoded:gsub('%s+$', '')
  
  -- Only set variable if we got valid output (not an error)
  if encoded and encoded ~= "" and not encoded:match("Error") then
    request.variables.set("authHeader_Local_JS_01", encoded)
  else
    print("Error getting encoded value: " .. (encoded or "nil"))
  end
%}
// Request (200)
GET https://httpbin.org/basic-auth/user/passwd
Authorization: Basic {{authHeader_Local_JS_01}}
###

Pseudo-JavaScript second example

# @lang=lua
< {%
  -- Use Lua to execute a Node.js command and capture its output
  local handle = io.popen('node -e "console.log(Buffer.from(\\\"user:passwd\\\").toString(\\\"base64\\\"))"')
  local encoded = handle:read("*a")
  handle:close()
  
  -- Trim whitespace and newlines
  encoded = encoded:gsub('%s+$', '')
  
  -- Only set variable if we got valid output (not an error)
  if encoded and encoded ~= "" and not encoded:match("Error") then
    request.variables.set("authHeader_Local_JS_02", encoded)
  else
    print("Error getting encoded value: " .. (encoded or "nil"))
  end
%}
// Request (200)
GET https://httpbin.org/basic-auth/user/passwd
Authorization: Basic {{authHeader_Local_JS_02}}
###

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions