apollo-rs icon indicating copy to clipboard operation
apollo-rs copied to clipboard

Usability: current patterns used in the router

Open Geal opened this issue 3 years ago • 0 comments

We are using the parser in the router for two use cases:

  • extracting subgraph URLs from the schema
  • building selection sets from the query to filter fields in the response

Currently we're using directly the Document interface, which does the job well, but requires some boilerplate, so we'd like to improve usability a bit,n maybe by adding utility methods. Here are some code snippets we're currently using:

Getting the name of an element as a string

We did it in multiple different ways, it would be nice to have a single method for that.

https://github.com/apollographql/router/blob/cd50d36d6f3b1a9d2902ccab2e08e89a85e3caf9/crates/apollo-router-core/src/schema.rs#L34-L39

let name = $definition
    .name()
    .expect("never optional according to spec; qed")
    .text()
    .to_string();

https://github.com/apollographql/router/blob/cd50d36d6f3b1a9d2902ccab2e08e89a85e3caf9/crates/apollo-router-core/src/schema.rs#L100-L105

if directive
    .name()
    .and_then(|n| n.ident_token())
    .as_ref()
    .map(|id| id.text())
    == Some("join__graph")

https://github.com/apollographql/router/blob/cd50d36d6f3b1a9d2902ccab2e08e89a85e3caf9/crates/apollo-router-core/src/schema.rs#L112-L116

let arg_name = argument
    .name()
    .and_then(|n| n.ident_token())
    .as_ref()
    .map(|id| id.text().to_owned());

https://github.com/apollographql/router/blob/cd50d36d6f3b1a9d2902ccab2e08e89a85e3caf9/crates/apollo-router-core/src/request.rs#L62-L68

let name = field
    .name()
    .expect("the node Name is not optional in the spec; qed")
    .text()
    .to_string();
let alias = field.alias().map(|x| x.name().unwrap().text().to_string());
let name = alias.unwrap_or(name);

https://github.com/apollographql/router/blob/cd50d36d6f3b1a9d2902ccab2e08e89a85e3caf9/crates/apollo-router-core/src/request.rs#L135-L141

let name = fragment_spread
    .fragment_name()
    .expect("the node FragmentName is not optional in the spec; qed")
    .name()
    .unwrap()
    .text()
    .to_string();

Stripping quotes from string arguments

https://github.com/apollographql/router/blob/cd50d36d6f3b1a9d2902ccab2e08e89a85e3caf9/crates/apollo-router-core/src/schema.rs#L118-L125

let arg_value =
    argument.value().and_then(|s| {
        s.to_string()
            .trim_end()
            .strip_prefix('"')
            .and_then(|s| s.strip_suffix('"'))
            .map(|s| s.to_owned())
    });

Iterating over all definitions

https://github.com/apollographql/router/blob/cd50d36d6f3b1a9d2902ccab2e08e89a85e3caf9/crates/apollo-router-core/src/schema.rs#L71-L148

Geal avatar Nov 15 '21 09:11 Geal