3

How do I leverage SPE to query Solr via GraphQL?

1 Answer 1

4

You can use the below function to query a defined GraphQL endpoint.

function Invoke-GraphRequest {
    param(
        [string]$query,
        [Sitecore.Data.Items.Item]$siteRoot,
        [string]$apiPath
    )
    
    $apiKeyItemPath = "/sitecore/system/Settings/Services/API Keys/key-name"
    $apiKeyItem = Get-Item -Path "master:$apiKeyItemPath"
    
    if (!$apiKeyItem) {
        Show-Alert "Unable to locate JSS API Key item at the following path: $apiKeyItemPath"
        exit
    }
    
    $linkOptions = New-Object -Type Sitecore.Links.UrlBuilders.ItemUrlBuilderOptions
    $linkOptions.AlwaysIncludeServerUrl = $true
    
    $homeUrl = [Sitecore.Links.LinkManager]::GetItemUrl($siteRoot, $linkOptions)
    
    if ([string]::IsNullOrEmpty($homeUrl)) {
        Show-Alert "Unable to get base url from home item: $($siteRoot.ID.ToString())"
        exit
    }
    
    $hostName = ([System.Uri]$homeUrl).Host
    $baseUrl = "https://$($hostName)$apiPath"
    
    $encodedQuery = [System.Web.HttpUtility]::UrlEncode($query) 
    
    $url = "$($baseUrl)?sc_apikey=$($apiKeyItem.ID.ToString())&query=$encodedQuery"
    
    $response = Invoke-WebRequest -Uri $url -UseBasicParsing
    
    $responseData = $response.Content | ConvertFrom-Json
    
    return $responseData
}

Usage:

$query = @"
        {
          search(rootItem: "{ADA8C66A-641F-45D8-B2E5-D3E757252CA2}", 
            index: "calendar_master_index",
            facetOn: [
              "service_location_facet"
            ], 
            fieldsEqual: [
              {name: "_template", value: "c746de598de3409f860071e5810c4d9e"}, 
            ]) {
            facets {
              values {
                value
              }
            }
          }
        }
"@ # this can't be tabbed over, or it will throw an error when imported

$homeItem = Get-Item -Path "master:/sitecore/content/site-name/home"

Import-Function -Name Invoke-GraphRequest
    
$responseData = Invoke-GraphRequest -Query $query -siteRoot $homeItem -apiPath "/api/graph-ql-endpoint"
    
$serviceLocationOptions = @{}
    
$facetValues = $responseData.data.search.facets.values
    
foreach ($facetValue in $facetValues) {
    $serviceLocationOptions[$facetValue.value] = $facetValue.value
}
    
return $serviceLocationOptions

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.