graphql-client icon indicating copy to clipboard operation
graphql-client copied to clipboard

Make a sqlx-like operation! macro

Open SorenHolstHansen opened this issue 2 years ago • 0 comments

I am not sure of the scope of this, but I am proposing a operation! (or maybe another name) macro that would allow something like this

fn main() -> Result<()> {
    let query = operation! {
        query User(id: Int!) {
            user { 
                id
                username
            }
        }
    };

    let user = query(1).await?; // user = UserQueryResponse { id, username }

    // or to better match the `perform_my_query` example, and maybe a better idea even
    // let user = query(UserQueryVariables { id: 1 }).await?;

    // do something with user.id, user.username, ...

    Ok(())
}

The operation! would support queries, migrations and subscriptions, and should be compile time checked for syntax errors, and against the schema.

It seems like you have most of the required pieces to do this, like the resulting struct, and variables. However there are some considerations

  • To allow this, it would probably be necessary to have a default place to have the schema file, like the crate root (or at least be able to set the location through the environment), so the macro knows where to find the schema.
  • To allow custom derives on the struct, make a corresponding operation_as!(SomeStruct, graphql) like in sqlx, to use your own struct
  • To allow to query files as well make a corresponding operation_from_file!(path) (and also operation_from_file_as!(SomeStruct, path).
  • The http client would have to be set by the crate, but that could be managed by features, so as to allow to query in wasm contexts as well. But the resulting query function (as in the example above) would be a lot like in the perform_my_query example in the readme

This would remove the requirement for codegen and make the feedback loop way faster.

SorenHolstHansen avatar Aug 03 '22 12:08 SorenHolstHansen