From 8ed9a98843335711004499677c1a0b2634197312 Mon Sep 17 00:00:00 2001 From: Joel Wachsler Date: Tue, 12 Jul 2022 13:06:07 +0000 Subject: [PATCH] Add method builder --- .../group/method/method_without_params.rs | 71 ++++++++++++------- 1 file changed, 47 insertions(+), 24 deletions(-) diff --git a/qbittorrent-web-api-gen/src/generate/group/method/method_without_params.rs b/qbittorrent-web-api-gen/src/generate/group/method/method_without_params.rs index 185b023..91c3a51 100644 --- a/qbittorrent-web-api-gen/src/generate/group/method/method_without_params.rs +++ b/qbittorrent-web-api-gen/src/generate/group/method/method_without_params.rs @@ -3,6 +3,49 @@ use quote::quote; use super::return_type::create_return_type; +struct MethodBuilder { + method_name: syn::Ident, + url: String, + return_type: Option, +} + +impl MethodBuilder { + fn new(method_name: &syn::Ident, url: &str) -> Self { + Self { + method_name: method_name.clone(), + url: url.to_string(), + return_type: None, + } + } + + fn return_type(mut self, value: &proc_macro2::TokenStream) -> Self { + self.return_type = Some(value.clone()); + self + } + + fn build(&self) -> proc_macro2::TokenStream { + let method_name = &self.method_name; + let (return_type, parse_type) = match &self.return_type { + Some(t) => (t.clone(), quote! { .json::<#t>() }), + None => (quote! { String }, quote! { .text() }), + }; + let url = &self.url; + + quote! { + pub async fn #method_name(&self) -> Result<#return_type> { + let res = self.auth + .authenticated_client(#url) + .send() + .await? + #parse_type + .await?; + + Ok(res) + } + } + } +} + pub fn create_method_without_params( group: &parser::ApiGroup, method: &parser::ApiMethod, @@ -11,33 +54,13 @@ pub fn create_method_without_params( ) -> (proc_macro2::TokenStream, Option) { let res = match create_return_type(group, method) { Some((return_type_name, return_type)) => ( - quote! { - pub async fn #method_name(&self) -> Result<#return_type_name> { - let res = self.auth - .authenticated_client(#url) - .send() - .await? - .json::<#return_type_name>() - .await?; - - Ok(res) - } - }, + MethodBuilder::new(&method_name, url) + .return_type(&return_type_name) + .build(), Some(return_type), ), None => ( - quote! { - pub async fn #method_name(&self) -> Result { - let res = self.auth - .authenticated_client(#url) - .send() - .await? - .text() - .await?; - - Ok(res) - } - }, + MethodBuilder::new(&method_name, url).build(), // assume that all methods without a return type returns a string None, ),