elysiajs / eden

Fully type-safe Elysia client
MIT License
147 stars 37 forks source link

RFC: expose resolve function #93

Open ap0nia opened 3 months ago

ap0nia commented 3 months ago

Details

Treaty calls an IIFE to resolve the request here. It would be nice if this function was exported from the eden/treaty package.

Context

I'm working on a proof of concept for integrating eden + tanstack-query, and something that would be useful is if this function was exposed so I could import it from upstream. tRPC has a general purpose TRPCUntypedClient that exposes a low level "fetch" API for making requests.

Implementation

I can open a PR if this writeup looks good.

The implementation that seems to work for me right now is this.

The function signature is

export async function resolveTreatyRequest(
  /**
   * Endpoint. Can be relative or absolute, as long as the fetcher can handle it.
   *
   * @example
   * '/api/a/b'
   * ['api', 'a', 'b']
   */
  endpointsOrPaths: string | string[],

  /**
   * HTTP method.
   */
  method = 'get',

  /**
   * Options when first parameter of GET request.
   * Body when first parameter of POST, PUT, etc. request.
   */
  bodyOrOptions: any,

  /**
   * Options when second parameter of POST, PUT, etc. request.
   */
  optionsOrUndefined: any,
  domain: string = '',
  config: EdenResolveOptions = {},
  elysia?: Elysia<any, any, any, any, any, any>,
) {
  //
}

Reasoning

For my own use case, I found that allowing endpointsOrPaths could theoretically allow eden-fetch to use the same resolve function; treaty would invoke it with an array of path segments, and fetch would invoke it with the endpoint URL string.

Because my parent function needed to "pop" the method from the end of the array, and for keeping the first parameter consistent by only describing the actual path, making method a dedicated second parameter made sense for my usecase.

The next two parameters represents the [body, options] spread argument that is provided by the apply method in the proxy, and either may be defined/undefined based on the method.

The last arguments are just additional variables that the IIFE captured from the outer scope, and I needed to provide it to the function.