Skip to content

Instantly share code, notes, and snippets.

@mark05e
Last active June 19, 2024 02:05
Show Gist options
  • Save mark05e/566e8ad7b9749d583dc90a3bc89d3183 to your computer and use it in GitHub Desktop.
Save mark05e/566e8ad7b9749d583dc90a3bc89d3183 to your computer and use it in GitHub Desktop.

Postman Scripts

Write OAuth to environment variables

// Write OAuth to environment variables
if (pm.response.code == 200) {
    const responseJson = pm.response.json();

    const access_token = responseJson.access_token;
    pm.environment.set("__access_token", access_token)

    const expires_in = responseJson.expires_in;
    const now = Date.now() / 1000;
    const expires_at = now + expires_in - 100;
    pm.environment.set("__expires_at",expires_at)
    
    console.log("writing token data to env variables complete!")
} else {
    console.warn('unsucessful auth. wiping existing keys if any.')
    pm.environment.set("__access_token", '')
    pm.environment.set("__expires_at", '')
}

Check if auth token is active

// Check if auth token is active
const currentTimestamp = Date.now() / 1000;
const expires_at = pm.environment.get("__expires_at")
const access_token = pm.environment.get("__access_token")
if (!expires_at || !access_token) {
    throw new Error('No token available. Please generate new one.')
}
if (currentTimestamp > expires_at) {
  throw new Error('Auth token has expired. Please generate new one.')
} else {
  console.log(`Auth token is valid for ${getRemainingMinutes(expires_at)} minutes.`);
}

function getRemainingMinutes(expires_at) {
  const currentTimestamp = Math.floor(Date.now() / 1000);
  const timeDiff = expires_at - currentTimestamp;
  const remainingMinutes = Math.max(0, Math.floor(timeDiff / 60));
  return remainingMinutes;
}

Update variables in request

// Update variables in request
pm.variables.set("AccountNumber","1234")

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment