ashkanyo
ashkanyo

Reputation: 132

Dynamic pre-request script Postman

I have this pre-request script and using runner to send bulk requests each second

     const moment = require('moment');
     postman.setEnvironmentVariable("requestid", moment().format("0223YYYYMMDDHHmmss000000"));

I need the “requestid” to be unique every time.

first request: "022320221115102036000001"

second request: "022320221115102037000002"

third request: "022320221115102038000003" . . .

and so on until let’s say 1000 requests.

Basically, I need to make the last 6 digits dynamic.

Upvotes: 0

Views: 1253

Answers (1)

bitoiu
bitoiu

Reputation: 7474

Your answer can be found on this postman request I've created for you. There's many ways to achieve this, given the little information provided, I've defaulted to:

  • Set a baseline prefix (before the last 6 numbers)
  • Give a start number for the last 6 numbers
  • If there IS NOT a previous variable stored initialized with the values above
  • If there IS a previous variable stored just increment it by one.
  • The variable date is your final result, current is just the increment

You can see here sequential requests:

enter image description here

And here is the code, but I would test this directly on the request I've provided above:

// The initial 6 number to start with
// A number starting with 9xxxxxx will be easier for String/Number converstions
const BASELINE = '900000'
const PREFIX = '022320221115102036'

// The previous used value if any
let current = pm.collectionVariables.get('current')

// If there's a previous number increment that, otherwise use the baseline
if (isNaN(current)) {
    current = BASELINE 
} else {
    current = Number(current) + 1
}

const date = PREFIX + current

// Final number you want to use
pm.collectionVariables.set('current', current)
pm.collectionVariables.set('date', PREFIX + date)
console.log(current)
console.log(date)

Upvotes: 1

Related Questions