fn generate_body()

in sdk/typespec/typespec_macros/src/model.rs [23:63]


fn generate_body(ast: DeriveInput) -> Result<TokenStream> {
    let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
    let name = &ast.ident;

    // Parse attributes
    let attrs = Attrs::from_attrs(&ast.attrs)?;

    let format = attrs.format.unwrap_or(Format::Json);
    let deserialize_body = match format {
        Format::Json => quote::quote! {
            body.json().await
        },
        Format::Xml => quote::quote! {
            body.xml().await
        },
    };

    // If the standard path is used, we need to add 'extern crate', because it's possible the calling code
    // depends on typespec_client_core transitively, which means it's not in scope by default.
    // That's not necessary when using a custom path because we assume the user has done that work.
    let typespec_import = match attrs.typespec_path {
        Some(path) => quote::quote! {
            use #path as _typespec_client_core;
        },
        None => quote::quote! {
            #[allow(unused_extern_crates, clippy::useless_attribute)]
            extern crate typespec_client_core as _typespec_client_core;
        },
    };

    Ok(quote::quote! {
        #typespec_import

        #[automatically_derived]
        impl #impl_generics _typespec_client_core::http::Model for #name #ty_generics #where_clause {
            async fn from_response_body(body: _typespec_client_core::http::response::ResponseBody) -> _typespec_client_core::Result<Self> {
                #deserialize_body
            }
        }
    })
}