Search code examples
rustgraphqlreqwestserde-json

Error deserializing response: error decoding response body: missing field `data` reqwest + graphql


My code don't appear erros on code but if i run this error appears

Error deserializing response: error decoding response body: missing field `data` at line 1 column 214

JSON looks like this, I imagine there must be type errors

{
    "data": {
        "card": {
            "title": "ffffff",
            "done": false,
            "id": "885876174",
            "updated_at": "2024-02-29T11:42:00-03:00",
                    "fields": [
                {
                    "array_value": null,
                    "name": "",
                    "native_value": "ffffff",
                    "value": "ffffff"
                },
]
            }
            ]
        }
    }
}
#[derive(Serialize, Deserialize, Debug)]
pub struct QueryData {
    card: CardQuery,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct QueryResult {
    data: QueryData,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct CardQuery {
    id: String,
    title: String,
    current_phase: Phase,
    fields: Vec<Field>,
    done: bool,
}

pub async fn notification(Json(payload): Json<Value>) -> Json<Value> {
    dotenv().ok();

    let data_value = payload
        .get("data")
        .expect("Missing 'data' field in request body");

    let data_body: NotificationData = serde_json::from_value(data_value.clone())
        .expect("Failed to parse 'data' field as NotificationData");

    let token_pipefy: String =
        std::env::var("TOKEN_PIPEFY").expect("TOKEN_PIPEFY environment variable not found");

    let authorization_header = HeaderValue::from_str(&format!("Bearer {}", token_pipefy)).unwrap();

    let endpoint = "https://api.pipefy.com/graphql";

    let query = r#"
           query CardQuery($id: ID!) {
               card(id: $id) {
                id
                title
                done
                current_phase{
                    name
                }
                updated_at
                    fields{
                        name
                        native_value
                        value
            }
                    
               }
           }
       "#;

    let variable = json!({"id": data_body.card.id});

    let body = serde_json::json!({
            "query": query,
            "variable": variable
    });

    let client = Client::new();

    let response: reqwest::Response = client
        .post(endpoint)
        .header("Authorization", authorization_header)
        .header("Content-Type", "application/json")
        .json(&body)
        .send()
        .await
        .expect("Error sending request");

    let json_response: Result<QueryResult, Error> = match response.json().await {
        Ok(card) => {
            println!("{:#?}", card);
            Ok(card)
        }
        Err(err) => {
            println!("Error deserializing response: {}", err);
            Err(err)
        }
    };

    match json_response {
        Ok(data_query) => {
            println!("{:?}", data_query);

            if data_body.action == "card.create" {
                return Json(json!({
                    "data": {
                        "action": data_body.action,

                        "card": {
                            "id": data_query,
                            "title": data_query.data.card.title,
                            "done": data_query.data.card.done,
                            "current_phase": data_query.data.card.current_phase,
                            "fields": {
                                "filial": data_query.data.card.fields[1],
                                "buyiD": data_query.data.card.fields[2]

                            }
                        }
                    },
                    "status": {
                        "statusCode": "200",
                        "message": "Inserido com sucesso",
                        "action": data_body.action
                    }
                }));
            } else {
                return Json(json!({
                    "message": {
                        "msg": "não foi possivel saber qual ação tomar.",
                        "action": data_body.action
                    }
                }));
            }
        }
        Err(err) => {
            print!("{:?}", err);
            return Json(json!({
                "message": {
                    "msg": "Não retornou nada",
                }
            }));
        }
    }
}

I've tried removing the typings, doing more type, doing less types and it's still giving the error. I really don't know where I'm going wrong, the error is probably in my face but I'm trying so hard that I'm not succeeding searching


Solution

  • resolved

    the error is on body... Correct is "variables" not "variable"

        let variable = json!({"id": data_body.card.id});
    
        let body = serde_json::json!({
                "query": query,
                "variable": variable
        });
    

    Correct:

        let variable = json!({"id": data_body.card.id});
    
        let body = serde_json::json!({
                "query": query,
                "variables": variable
        });