leptos icon indicating copy to clipboard operation
leptos copied to clipboard

Generic Server Fn

Open sjud opened this issue 2 months ago • 4 comments

Hello,

I know there is another generic SeverFn PR open https://github.com/leptos-rs/leptos/pull/3008 but I decided to try my hand at it anyways since it's been something I've wanted for a while. I had needs that were not covered by the other PR. I hope I am not stepping on anyones toes @rakshith-ravi .

This PR covers implementing generic server functions without touching any non-macro code. Specifically I've added an attribute for registering the types of a particular generic function and extending the macro path logic. Instead of impl<T> ServerFn for SomeStruct<T>, for each registered type set the macro generates a specific impl ServerFn for SometStruct<SpecificT>.

My implementation is generic over server function arguments (the focus of the other PR) as well as, generic over non input types. For any type that isn't in the input of the server function, we add a _marker type with PhantomData<T,..,U> with the set of non input types.

It's also generic over the T in Result<T,ServerFnError<E>>, although not E (it'd be very easy to add that though.)

Something I also wanted which is kind of weird is a way to specify a generic server functions in the front end over a type that can only exist on the backend. This will let us (when generic components are expanded), build a component that is generic over a backend implementation. So you could have a GraphComponent which is generic over it's data source, and it uses the same server function to compile data from different data sources which are specified in the client code.

I've introduced some macros to build shims between generated front end types and the SSR only backend types, and logic within the server macro to map those client side types into their actualized server types.

I also refactored the server function macro, which I hope was OK. I wasn't able to perform any edits on it without doing a big (and yet painless) refactor.

I've added some examples to show off the the new code. This PR is based on my RFC (which got no comments lol) https://github.com/sjud/server-fn-generic-rfc , which is out of date since I wrote it before the implementation of it but covers what I was going for in more detail.

Best, Sam

sjud avatar Dec 21 '24 20:12 sjud