relay icon indicating copy to clipboard operation
relay copied to clipboard

Add context to relay resolvers

Open Markionium opened this issue 8 months ago • 3 comments

This is a draft PR to implement an approach mentioned in #4000.

I've currently put the resolverContext on the Store instead of the Environment. It seems that the Store might be a better place than the Environment?

If defined on the environment the context would need to go from the environment into the store down to the reader? Since a store could be used by different environments if the resolverContext would be on the environment that might cause more issues than it being on the store?

The following is an example of how this would be used.

One would provide the context as follows.

const store = new LiveResolverStore(source, {
    resolverContext: {
      counter: createObservableCounter(),
      world: "World!"
    },
  });

Then the resolvers could use the context similar to readFragment

/**
 * @RelayResolver Query.hello_context: String
 *
 * Say `Hello, ${world}!`
 */
import {resolverContext} from '../../ResolverFragments';

function hello_context(): string {
  const world = resolverContext<{world: string}>().world;
  return `Hello, ${world}!`;
}
/**
 * @RelayResolver Query.hello_world_with_context: String
 * @live
 *
 * Say `Hello ${world}!`
 */
function hello_world_with_context(): LiveState<string> {
  const dependency = resolverContext<{greeting: string}>();

  return {
    read() {
      return `Hello ${dependency.greeting}!`;
    },

    subscribe(callback) {
      return () => {
        // no-op
      };
    },
  };
}

Markionium avatar Jun 04 '24 12:06 Markionium