Skip to content

New GraphQL mandate to send "operation name" fix#46

Open
MdAsimKhan wants to merge 1 commit intogazuntype:masterfrom
MdAsimKhan:master
Open

New GraphQL mandate to send "operation name" fix#46
MdAsimKhan wants to merge 1 commit intogazuntype:masterfrom
MdAsimKhan:master

Conversation

@MdAsimKhan
Copy link
Copy Markdown

The latest update of GraphQL mentions that we need to mandatorily send an operation name for the query for it to pass otherwise all api calls will fail or return null.

I have implemented this fix that works. Go to your HttpHandler.cs and replace your first PostAsync() method with this.

public static async Task<UnityWebRequest> PostAsync(string url, string details, string authToken = null, object variables = null, string operationName = null)
{
    // 1. Check if the query is anonymous and name it
    // This looks for 'query {', 'mutation {', or just '{'
    string processedQuery = details.Trim();

    // Try to find an existing name first (for your new Login API)
    Match nameMatch = Regex.Match(processedQuery, @"\b(?:query|mutation)\s+([a-zA-Z0-9_]+)");
    
    if (nameMatch.Success)
    {
        operationName = nameMatch.Groups[1].Value;
    }
    else
    {
        // No name found? It's anonymous. Let's inject "EduzoOp"
        operationName = "EduzoOp";
        
        if (processedQuery.StartsWith("query"))
            processedQuery = Regex.Replace(processedQuery, @"^query\s*\{", "query EduzoOp {");
        else if (processedQuery.StartsWith("mutation"))
            processedQuery = Regex.Replace(processedQuery, @"^mutation\s*\{", "mutation EduzoOp {");
        else if (processedQuery.StartsWith("{"))
            processedQuery = "query EduzoOp " + processedQuery;
    }

    // 2. Build the payload with the now-mandatory operationName
    var payload = new Dictionary<string, object>
    {
        { "query", processedQuery },
        { "operationName", operationName }
    };

    if (variables != null) 
        payload.Add("variables", variables);

    // 3. Serialize and continue with your original logic
    string jsonData = JsonConvert.SerializeObject(payload);
    byte[] postData = Encoding.UTF8.GetBytes(jsonData);
    
    // --- Rest of your original code starts here ---
    UnityWebRequest request = UnityWebRequest.PostWwwForm(url, UnityWebRequest.kHttpVerbPOST);
    request.uploadHandler = new UploadHandlerRaw(postData);
    request.SetRequestHeader("Content-Type", "application/json");
    
    if (!String.IsNullOrEmpty(authToken))
        request.SetRequestHeader("Authorization", "Bearer " + authToken);

    OnRequestBegin requestBegin = new OnRequestBegin();
    requestBegin.FireEvent();

    try
    {
        await request.SendWebRequest();
    }
    catch (Exception e)
    {
        Debug.Log("Testing exceptions");
        OnRequestEnded requestFailed = new OnRequestEnded(e);
        requestFailed.FireEvent();
    }
    
    Debug.Log(request.downloadHandler.text);

    OnRequestEnded requestSucceeded = new OnRequestEnded(request.downloadHandler.text);
    requestSucceeded.FireEvent();
    
    return request;
}

The latest update of GraphQL mentions that we need to mandatorily send an operation name for the query for it to pass otherwise all api calls will fail or return null.

I have implemented this fix that works. Go to your HttpHandler.cs and replace your first PostAsync() method with this.


```
public static async Task<UnityWebRequest> PostAsync(string url, string details, string authToken = null, object variables = null, string operationName = null)
{
    // 1. Check if the query is anonymous and name it
    // This looks for 'query {', 'mutation {', or just '{'
    string processedQuery = details.Trim();

    // Try to find an existing name first (for your new Login API)
    Match nameMatch = Regex.Match(processedQuery, @"\b(?:query|mutation)\s+([a-zA-Z0-9_]+)");
    
    if (nameMatch.Success)
    {
        operationName = nameMatch.Groups[1].Value;
    }
    else
    {
        // No name found? It's anonymous. Let's inject "EduzoOp"
        operationName = "EduzoOp";
        
        if (processedQuery.StartsWith("query"))
            processedQuery = Regex.Replace(processedQuery, @"^query\s*\{", "query EduzoOp {");
        else if (processedQuery.StartsWith("mutation"))
            processedQuery = Regex.Replace(processedQuery, @"^mutation\s*\{", "mutation EduzoOp {");
        else if (processedQuery.StartsWith("{"))
            processedQuery = "query EduzoOp " + processedQuery;
    }

    // 2. Build the payload with the now-mandatory operationName
    var payload = new Dictionary<string, object>
    {
        { "query", processedQuery },
        { "operationName", operationName }
    };

    if (variables != null) 
        payload.Add("variables", variables);

    // 3. Serialize and continue with your original logic
    string jsonData = JsonConvert.SerializeObject(payload);
    byte[] postData = Encoding.UTF8.GetBytes(jsonData);
    
    // --- Rest of your original code starts here ---
    UnityWebRequest request = UnityWebRequest.PostWwwForm(url, UnityWebRequest.kHttpVerbPOST);
    request.uploadHandler = new UploadHandlerRaw(postData);
    request.SetRequestHeader("Content-Type", "application/json");
    
    if (!String.IsNullOrEmpty(authToken))
        request.SetRequestHeader("Authorization", "Bearer " + authToken);

    OnRequestBegin requestBegin = new OnRequestBegin();
    requestBegin.FireEvent();

    try
    {
        await request.SendWebRequest();
    }
    catch (Exception e)
    {
        Debug.Log("Testing exceptions");
        OnRequestEnded requestFailed = new OnRequestEnded(e);
        requestFailed.FireEvent();
    }
    
    Debug.Log(request.downloadHandler.text);

    OnRequestEnded requestSucceeded = new OnRequestEnded(request.downloadHandler.text);
    requestSucceeded.FireEvent();
    
    return request;
}
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant