1

As the title said, I am trying to extract value for "ssoid" variable that is available in the API payload. Is it possible to do this using JS? Thank you very much!

enter image description here

Payload object:

{
    "query": "query Driver_All($customer: DriverInput!) {\n        driver(customer: $customer) {\n                authenticated\n                accounts\n                sharedAccounts\n         units {\n            count\n            previous\n            next\n            facets {\n              name\n              displayName\n              facetValues {\n                value\n                count\n              }\n            }\n            results {\n              productLineDesc\n              hasPendingTasks\n              hasAppointment\n              hasOpenDefects\n              currentStatusStage\n              status\n              activeStatusStep {\n                status\n                description\n                dateTimeFormatted\n                active\n                action\n                transactonDate\n                filterStatus\n              }\n              openDefectDate\n              countOfVehiclesWithPendingTasks\n              showMiles\n              showReeferHours\n              showStandbyHours\n              groups {\n                id\n                name\n              }\n              workflows {\n                section\n                steps {\n                  dateTimeFormatted\n                  description\n                  active\n                  status\n                  action\n                  alwaysLastStep\n                  transactonDate\n                }\n              }\n              unitStatus{\n                maintenanceStatusDate,\n                maintenanceStatusDescription\n                roadsideCaseStatusDate\n                roadsideCaseStatusDescription\n                odometerStatusDate\n                odometerStatusDescription\n               }\n               unitSummary {\n                location {\n                  locationSummary {\n                    locationCode\n                    locationId\n                    locationName\n                    street1\n                    street2\n                    city\n                    state\n                    zip\n                    latitude\n                    longitude\n                  }\n                  shop {\n                    phone\n                  }\n                }\n                unitId\n                unitNumber\n                customerUnitNumber\n                vehicleVin\n                odometer\n                odometerReadingDate\n                chassisMake\n                chassisModel\n                locationNumber\n                locationName\n                nextPM\n                pMLastDate\n                pMNextDate\n                vehicleMake\n                vehicleYear\n                vehicleModel\n              }\n              unitDetail {\n                accountNumber\n                fISAccountNumber\n                customerAssignedNumber\n                isShared\n                engineMake\n                engineModel\n                unitType\n                vehicleLicenseDate\n                vehicleLicenseTag\n                accountMgrNational\n                chassisAxleCount\n                chassisGearRatio\n                transMake\n                transModel\n                transNoSpeeds\n                suspensionMake\n                suspensionModel\n                suspensionType\n                vehicleGVWQty\n                engineEstLife\n                engineHP\n                engineNumCylinders\n                leaseExpirationDate\n                leaseTermMonths\n                tireSizeFront\n                tireSizeRear\n                tTTUnitType\n                billingDistrictCode\n                physicalDistrictCode\n                hasLiftgate\n                isRefrigerated\n                bodyLength\n                bodyHeight\n                bodyWidth\n                bodyType\n                referMake\n                referModel\n                rearAxleMake\n                rearAxleModel\n                rearAxleType\n              }\n              unitAppointment\n              {\n                appointmentId\n                appointmentDate\n                appointmentStatus\n                appointmentEndTime\n                appointmentLocation\n                appointmentStartTime\n                appointmentWorkItems\n                formattedTime\n                formattedAppointmentDate\n              }\n              vehicleOdometer {\n                lastBilledDate\n                billingToDate\n                billingFromDate\n                billingDueDate\n                billedOdometer\n                billedReeferHours\n                billedStdByHours\n                lastReadingDate\n                lastOdometerReading\n                lastReeferHoursReading\n                lastStandByHoursReading\n                odometerUnitOfMeasure\n                source\n              }\n            }\n          }\n        }\n}",
    "variables": {
        "customer": {
            "userName": "abc.com",
            "id": "4b470c91-5425-4b95-9bb9-393a8f4c6af7",
            "ssoid": "14642008",
            "token": "",
            "firstName": "FN",
            "lastName": "LN",
            "accessingOneVehicleNumber": "",
            "unitsPage": "?maximumRows=20&startPageIndex=1&sortBy=StatusOrder ASC, StatusOrder < 16 ? ActiveStatusStep.TransactionDateTime.Value.Date : DateTime.Now.Date ASC, UnitSummary.UnitNumber ASC",
            "phoneNumber": "+1 566-444-4444"
        }
    }
}```
user3191724
  • 139
  • 10

1 Answers1

2

Not sure how you want to integrate it with Google Tag Manager, but this script will intercept fetch requests and allow you to access the body/payload as JSON, then forward the request after getting what you need from the request payload. Tested in Chrome and Firefox. Thanks to the following resources for helping build this solution: capturing fetch requests and this github issue showing how to clone a request.

If you need help making this work with GTM, then please provide more details on what you are trying to accomplish and I will look into it.

window.fetch = new Proxy(window.fetch, {
  apply(fetch, that, args) {
    return (async() => {
      try {
        //change this condition to only match the request you want to intercept
        var req = args[0];
        if (req.method === "POST") {
          //clone the request because payload can only be consumed once.
          var payload = await req.clone().json();
          console.log({payload});
        }
      } catch (e) {
        console.log(e)
      };
      //Perform fetch
      const result = fetch.apply(that, args);
      return result;
    })()
  }
});

Edit: args[0] should refer to the Request object. method refers to the request method property, which should be "POST" since you are expecting a payload to be sent with the request.

If for some reason the first item in the args array is not a request object, you can change the reference to the index, but I'm not sure why it wouldn't be. You can log all the args to the console to troubleshoot that part.

I mentioned in the comment that you can change that condition to suit your needs. For example, if there is a specific URL path you want to target, then you can add that logic to the if statement. For other options, check out the link about request objects above, or simply log the whole thing to console to see all the request properties.

var path = "api/path/";
if (req.method === "POST" && req.url.indexOf(path) > -1) {
  //clone the request because payload can only be consumed once.
  var payload = await req.clone().json();
  console.log({payload});
}
Jscrip
  • 309
  • 1
  • 7
  • 1
    Thank you so much for this. I am planing to have "ssoid" value in the GTM variable on page view. As long I can target a specific request to intercept, this will work in GTM var. I am not sure how to handle this part : ` //change this condition to only match the request you want to intercept if (args[0].method === "POST") { ` – user3191724 Mar 24 '22 at 16:48
  • 2
    No problem, I learned something new in the process so wins all around. I added some more details to help with handling specific requests. The if statement is where you can filter which requests trigger further action. args[0] should just be the request object, but I updated the script and explanation for more clarity . Also included an example of targeting a specific substring of a url. You should be able to hook into the section where payload is logged to the console. – Jscrip Mar 24 '22 at 17:38
  • @Jcrip This is way out of my comfort zone :) I am not sure what to do from here. This is my attempt btw. https://snipboard.io/p3PF1Y.jpg Not sure if it helps but I added a payload object in the main post. Can't thank you enough for this! – user3191724 Mar 25 '22 at 20:40