Skip to content

Commit 51cf91d

Browse files
committed
WIP Support query_string macro attribute
1 parent c52e89e commit 51cf91d

File tree

2 files changed

+86
-49
lines changed
  • graphql_client_codegen/src
  • graphql_query_derive/src

2 files changed

+86
-49
lines changed

graphql_client_codegen/src/lib.rs

Lines changed: 53 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -44,29 +44,24 @@ impl std::error::Error for GeneralError {}
4444

4545
type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
4646
type CacheMap<T> = std::sync::Mutex<BTreeMap<std::path::PathBuf, T>>;
47+
type CachedQuery = (String, graphql_parser::query::Document<'static, String>);
4748

4849
lazy_static! {
4950
static ref SCHEMA_CACHE: CacheMap<schema::Schema> = CacheMap::default();
50-
static ref QUERY_CACHE: CacheMap<(String, graphql_parser::query::Document<'static, String>)> =
51-
CacheMap::default();
51+
static ref QUERY_CACHE: CacheMap<CachedQuery> = CacheMap::default();
5252
}
5353

54-
/// Generates Rust code given a query document, a schema and options.
55-
pub fn generate_module_token_stream(
56-
query_path: std::path::PathBuf,
57-
schema_path: &std::path::Path,
58-
options: GraphQLClientCodegenOptions,
59-
) -> Result<TokenStream, BoxError> {
54+
fn get_schema(schema_path: &std::path::Path) -> Result<schema::Schema, BoxError> {
6055
use std::collections::btree_map;
6156

6257
let schema_extension = schema_path
6358
.extension()
6459
.and_then(std::ffi::OsStr::to_str)
6560
.unwrap_or("INVALID");
66-
let schema_string;
61+
let schema_string: String;
6762

6863
// Check the schema cache.
69-
let schema: schema::Schema = {
64+
let cached_schema: schema::Schema = {
7065
let mut lock = SCHEMA_CACHE.lock().expect("schema cache is poisoned");
7166
match lock.entry(schema_path.to_path_buf()) {
7267
btree_map::Entry::Occupied(o) => o.get().clone(),
@@ -89,37 +84,68 @@ pub fn generate_module_token_stream(
8984
}
9085
};
9186

92-
// We need to qualify the query with the path to the crate it is part of
93-
let (query_string, query) = {
94-
let mut lock = QUERY_CACHE.lock().expect("query cache is poisoned");
95-
match lock.entry(query_path) {
96-
btree_map::Entry::Occupied(o) => o.get().clone(),
97-
btree_map::Entry::Vacant(v) => {
98-
let query_string = read_file(v.key())?;
99-
let query = graphql_parser::parse_query(&query_string)
100-
.map_err(|err| GeneralError(format!("Query parser error: {}", err)))?
101-
.into_static();
102-
v.insert((query_string, query)).clone()
103-
}
87+
Ok(cached_schema)
88+
}
89+
90+
fn get_query(query_path: std::path::PathBuf) -> Result<CachedQuery, BoxError> {
91+
use std::collections::btree_map;
92+
93+
let mut lock = QUERY_CACHE.lock().expect("query cache is poisoned");
94+
let cached_query = match lock.entry(query_path) {
95+
btree_map::Entry::Occupied(o) => o.get().clone(),
96+
btree_map::Entry::Vacant(v) => {
97+
let query_string = read_file(v.key())?;
98+
let query_document = graphql_parser::parse_query(&query_string)
99+
.map_err(|err| GeneralError(format!("Query parser error: {}", err)))?
100+
.into_static();
101+
v.insert((query_string, query_document)).clone()
104102
}
105103
};
106104

107-
let query = crate::query::resolve(&schema, &query)?;
105+
Ok(cached_query)
106+
}
107+
108+
/// Generates Rust code given a path to a query file, a path to a schema file, and options.
109+
pub fn generate_module_token_stream(
110+
query_path: std::path::PathBuf,
111+
schema_path: &std::path::Path,
112+
options: GraphQLClientCodegenOptions,
113+
) -> Result<TokenStream, BoxError> {
114+
let (query_string, _) = get_query(query_path)?;
115+
116+
generate_module_token_stream_from_string(query_string, schema_path, options)
117+
}
118+
119+
/// Generates Rust code given a query string, a path to a schema file, and options.
120+
pub fn generate_module_token_stream_from_string(
121+
query_string: String,
122+
schema_path: &std::path::Path,
123+
options: GraphQLClientCodegenOptions,
124+
) -> Result<TokenStream, BoxError> {
125+
let schema = get_schema(schema_path)?;
126+
let query_document = graphql_parser::parse_query(&query_string)
127+
.map_err(|err| GeneralError(format!("Query parser error: {}", err)))?
128+
.into_static();
129+
130+
// We need to qualify the query with the path to the crate it is part of
131+
let generated_query = crate::query::resolve(&schema, &query_document)?;
108132

109133
// Determine which operation we are generating code for. This will be used in operationName.
110134
let operations = options
111135
.operation_name
112136
.as_ref()
113-
.and_then(|operation_name| query.select_operation(operation_name, *options.normalization()))
137+
.and_then(|operation_name| {
138+
generated_query.select_operation(operation_name, *options.normalization())
139+
})
114140
.map(|op| vec![op]);
115141

116142
let operations = match (operations, &options.mode) {
117143
(Some(ops), _) => ops,
118-
(None, &CodegenMode::Cli) => query.operations().collect(),
144+
(None, &CodegenMode::Cli) => generated_query.operations().collect(),
119145
(None, &CodegenMode::Derive) => {
120146
return Err(GeneralError(derive_operation_not_found_error(
121147
options.struct_ident(),
122-
&query,
148+
&generated_query,
123149
))
124150
.into());
125151
}
@@ -132,7 +158,7 @@ pub fn generate_module_token_stream(
132158
let generated = generated_module::GeneratedModule {
133159
query_string: query_string.as_str(),
134160
schema: &schema,
135-
resolved_query: &query,
161+
resolved_query: &generated_query,
136162
operation: &operation.1.name,
137163
options: &options,
138164
}

graphql_query_derive/src/lib.rs

Lines changed: 33 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@ extern crate proc_macro;
44
mod attributes;
55

66
use graphql_client_codegen::{
7-
generate_module_token_stream, CodegenMode, GraphQLClientCodegenOptions,
7+
generate_module_token_stream, generate_module_token_stream_from_string, CodegenMode,
8+
GraphQLClientCodegenOptions,
89
};
910
use std::{
1011
env,
@@ -26,38 +27,44 @@ fn graphql_query_derive_inner(
2627
) -> Result<proc_macro::TokenStream, syn::Error> {
2728
let input = TokenStream::from(input);
2829
let ast = syn::parse2(input)?;
29-
let (query_path, schema_path) = build_query_and_schema_path(&ast)?;
30-
let options = build_graphql_client_derive_options(&ast, query_path.clone())?;
31-
32-
generate_module_token_stream(query_path, &schema_path, options)
33-
.map(Into::into)
34-
.map_err(|err| {
35-
syn::Error::new_spanned(
36-
ast,
37-
format!("Failed to generate GraphQLQuery impl: {}", err),
38-
)
39-
})
40-
}
4130

42-
fn build_query_and_schema_path(input: &syn::DeriveInput) -> Result<(PathBuf, PathBuf), syn::Error> {
4331
let cargo_manifest_dir = env::var("CARGO_MANIFEST_DIR").map_err(|_err| {
4432
syn::Error::new_spanned(
45-
input,
33+
&ast,
4634
"Error checking that the CARGO_MANIFEST_DIR env variable is defined.",
4735
)
4836
})?;
4937

50-
let query_path = attributes::extract_attr(input, "query_path")?;
51-
let query_path = format!("{}/{}", cargo_manifest_dir, query_path);
52-
let query_path = Path::new(&query_path).to_path_buf();
53-
let schema_path = attributes::extract_attr(input, "schema_path")?;
38+
let schema_path = attributes::extract_attr(&ast, "schema_path")?;
5439
let schema_path = Path::new(&cargo_manifest_dir).join(schema_path);
55-
Ok((query_path, schema_path))
40+
41+
let query_string = attributes::extract_attr(&ast, "query_string").ok();
42+
let module_token_stream = match query_string {
43+
Some(query_string) => {
44+
let options = build_graphql_client_derive_options(&ast, None)?;
45+
generate_module_token_stream_from_string(query_string, schema_path.as_path(), options)
46+
}
47+
None => {
48+
let query_path = attributes::extract_attr(&ast, "query_path")?;
49+
let query_path = format!("{}/{}", cargo_manifest_dir, query_path);
50+
let query_path = Path::new(&query_path).to_path_buf();
51+
let options = build_graphql_client_derive_options(&ast, Some(query_path.clone()))?;
52+
53+
generate_module_token_stream(query_path, &schema_path, options)
54+
}
55+
};
56+
57+
module_token_stream.map(Into::into).map_err(|err| {
58+
syn::Error::new_spanned(
59+
ast,
60+
format!("Failed to generate GraphQLQuery impl: {}", err),
61+
)
62+
})
5663
}
5764

5865
fn build_graphql_client_derive_options(
5966
input: &syn::DeriveInput,
60-
query_path: PathBuf,
67+
query_path: Option<PathBuf>,
6168
) -> Result<GraphQLClientCodegenOptions, syn::Error> {
6269
let variables_derives = attributes::extract_attr(input, "variables_derives").ok();
6370
let response_derives = attributes::extract_attr(input, "response_derives").ok();
@@ -67,7 +74,11 @@ fn build_graphql_client_derive_options(
6774
let skip_serializing_none: bool = attributes::extract_skip_serializing_none(input);
6875

6976
let mut options = GraphQLClientCodegenOptions::new(CodegenMode::Derive);
70-
options.set_query_file(query_path);
77+
78+
if let Some(query_path) = query_path {
79+
options.set_query_file(query_path);
80+
}
81+
7182
options.set_fragments_other_variant(fragments_other_variant);
7283
options.set_skip_serializing_none(skip_serializing_none);
7384

0 commit comments

Comments
 (0)