2

I try to figure out how to add custom code to my request similar way to pre-request script in Postman like:


const items = JSON.parse(pm.collectionVariables.get('items'))

const randomItem = _.sample(items)

pm.variables.set('randomItemId', randomItem.id)
pm.variables.set('randomItem', JSON.stringify(randomItem));

I know that for 03 2023 importing external libraries is in beta, but let's assume it works ok.

I understand that I need to create filter:

First question: where is option to create one? I wish it will be separated form my project code.

Second question: can I have filter code directly in my request (visible to quickly check what happening in request)? Or I need to create filters for every request where I need new custom code

I tried follow docs but there is no clear information where add files for filters: https://github.com/rangav/thunder-client-support/blob/master/docs/filters.md

pbaranski
  • 22,778
  • 19
  • 100
  • 117

1 Answers1

3

I partially figured it out because it looks like scripts are injected on Collection level.

Prerequisites - navigate to Thunder Client:

  1. Create Environment (Env tab -> menu -> New Environment) let's call it baseEnv
  2. In baseEnv set empty v variable and Save
  3. Create Collection (Collection tab -> menu -> New Collection) let's call it myCol
  4. In myCol go to menu -> Settings -> Environment and attach Environment baseEnv

Create script:

  1. Decide where you will keep the scripts (i.e. separate repository)
  2. Create file i.e. script.js
  3. Add function to script:
    async function testFunc() {
        console.log("Test log message");
        return "TEST";
    }
    
    module.exports = [testFunc];
    

To add custom script to Collection:

  1. Go to Collections and find your Collection
  2. Open Collection menu (...)
  3. Open Setting tab
  4. Choose file with script
  5. Save

Use script:

  1. Crete request in Collection (menu -> New Request)
  2. Url: https://httpbin.org/anything
  3. In Headers add header A-test with value: {{v | testFunc}} enter image description here
  4. Send request!

Result: enter image description here

If script is not loaded and function was not executed try:

  • load script again and save
  • type expression {{v | testFunc}} and save

Extend scripts:

  1. Place there files with 2 scripts:
  2. Example file with script https://github.com/rangav/thunder-client-support/blob/master/docs/custom-filters.js
  3. Example file with types https://github.com/rangav/thunder-client-support/blob/master/docs/tc-types.d.ts
pbaranski
  • 22,778
  • 19
  • 100
  • 117