A Gratos resolver may return an Effect: the compiler reads Effect.Effect<A, E, R> as a field of type A, as Grats reads Promise<A>, and Stream.Stream<A, E, R> as a subscription whose events are its items. The error type E stays yours, and so do the services R: the server's Effect layer runs every resolver in its request's fiber context, with your services, and maps your typed failures to GraphQL errors (see The Effect layer).

Return types

What the compiler accepts:

A resolver returns The field's type Where
Effect.Effect<A, E, R> A (like Promise<A>) any field except a Subscription field
Stream.Stream<A, E, R> A, one event per item @gqlSubscriptionField only
A, Promise<A>, AsyncIterable<A> as in Grats as in Grats (AsyncIterable<A> on subscriptions)

An Effect resolver reads its services with yield*, and fails with a tagged error, also with yield*. Here is a query field over a service, and the schema Gratos writes from it: the error and the services are not in the schema, only A.

Order.ts
import type { ID, Float } from "gratos";
import { Context, Effect, Schema } from "effect";

/** An order, as the store keeps it. */
interface OrderRow {
  readonly id: string;
  readonly total: number;
}

/** The order store: a service, so a test provides its own. */
export class Orders extends Context.Service<
  Orders,
  { readonly byId: (id: string) => Effect.Effect<OrderRow | undefined> }
>()("sample/Orders") {}

/** The typed failure of a lookup that finds nothing. */
export class NotFound extends Schema.TaggedError<NotFound>()("NotFound", {
  id: Schema.String,
}) {}

/** @gqlType */
export class Order {
  /** @gqlField */
  readonly id: ID;
  /** @gqlField */
  readonly total: Float;

  constructor(row: OrderRow) {
    this.id = row.id;
    this.total = row.total;
  }
}

/** One order, by its id. @gqlQueryField */
export function order(id: ID): Effect.Effect<Order, NotFound, Orders> {
  return Effect.gen(function* () {
    const orders = yield* Orders;
    const row = yield* orders.byId(id);
    if (row === undefined) {
      return yield* new NotFound({ id });
    }
    return new Order(row);
  });
}

A subscription returns the Stream.Stream itself. Each item is one event, and the subscription completes when the Stream ends:

countdown.ts
import type { Int } from "gratos";
import { Schedule, Stream } from "effect";

/**
 * Counts down from `from` to 0, one number a second: each number is one event, and the
 * subscription completes after 0.
 * @gqlSubscriptionField
 */
export function countdown(from: Int): Stream.Stream<Int> {
  return Stream.iterate(from, (n) => n - 1).pipe(
    Stream.take(from + 1),
    Stream.schedule(Schedule.spaced("1 second")),
  );
}

// graphql-js serves no schema without a query type, so this one has a query field too.
/** @gqlQueryField */
export function ping(): string {
  return "pong";
}

A subscription never returns an Effect.Effect, not even Effect.Effect<Stream.Stream<A>>: the compiler rejects it and asks for the Stream. A source that needs an Effect to set up is a Stream built from it, with Stream.unwrap, or with the guard's guardStream (see The Effect layer).

The rules

The compiler enforces these, each with its own error:

  • Only the qualified names count: Effect.Effect and Stream.Stream, from import { Effect, Stream } from "effect". A bare Effect<A> gets an error that suggests Effect.Effect<A>. A type of your own named Effect stays a normal type. A renamed import (import { Effect as Fx }, or import * as Fx from "effect/Effect") is not detected either: it gets an error that suggests importing Effect under its own name.
  • The Effect is the outermost wrapper. Effect.Effect<Promise<A>>, Promise<Effect.Effect<A>>, Array<Effect.Effect<A>> and an Effect around a Stream are errors, so the field's type and its markers come from one outer Effect.
  • A Stream is a subscription. On a query or object field, Stream.Stream is an error: it would compile to a list and fail at run time.
  • Neither is an input. An argument, an input field, or the return type of a @gqlContext function cannot be an Effect or a Stream.

The runtime is more lenient than the compiler, for hand-written schemas passed to effectSchema: a resolve may return an Effect, an Exit, a plain value, or a Promise of any of them, and a subscribe may return a Stream, an AsyncIterable, or an Effect or a Promise of either. In a Gratos model, keep to the table above.

What the compiler generates

Every method field gets its own explicit resolve, and its arguments are passed positionally, in your parameter order. The resolver returns your Effect as it is; the Effect layer runs it:

generated/schema.ts
resolve(_source, args) {
    return queryOrderResolver(args.id);
}

Gratos writes two markers in a field's extensions.gratos:

  • semanticNonNull: true on an Effect field under strictSemanticNullability. Grats' assertNonNull cannot see inside an Effect, so the Effect layer checks the value the Effect succeeds with: a null becomes a field error ("Cannot return null for semantically non-nullable field."). This site's schema is strict, so its Effect fields carry it:

    src/generated/schema.ts
    extensions: {
        gratos: {
            semanticNonNull: true
        }
    },

    A subscription keeps Grats' assertNonNull on its per-event resolve, so a null item is one event with an error, and the subscription carries on.

  • jit: false on a field whose resolver takes a GqlInfo parameter: the jit() plugin keeps every operation that selects it on graphql-js, because graphql-jit's info has no getAbortSignal().

Testing a resolver

A resolver is a plain Effect: run it with a fake layer, with no server. Its typed failure is a value you compare:

test/samples.test.ts
describe("an Effect resolver", () => {
  it.effect("finds an order", () =>
    Effect.gen(function* () {
      const found = yield* order("o-1").pipe(Effect.provide(FakeOrders));
      expect(found.total).toBe(42);
    }),
  );

  it.effect("fails with its typed error when there is none", () =>
    Effect.gen(function* () {
      const exit = yield* order("o-2").pipe(Effect.provide(FakeOrders), Effect.exit);
      expect(exit).toEqual(Exit.fail(new NotFound({ id: "o-2" })));
    }),
  );
});

A Stream subscription is a plain Stream, and Effect's TestClock runs its schedule without waiting:

test/samples.test.ts
describe("a Stream subscription", () => {
  it.effect("counts down to 0, one number a second", () =>
    Effect.gen(function* () {
      const fiber = yield* countdown(3).pipe(Stream.runCollect, Effect.forkChild);
      yield* TestClock.adjust("4 seconds");
      expect(yield* Fiber.join(fiber)).toEqual([3, 2, 1, 0]);
    }),
  );
});

Compare a typed failure that crossed a span (Effect.withSpan, or Effect.fn with a name) with Effect.flip and the error itself: its Exit carries a stack annotation, so it is not equal to a fresh Exit.fail(error).

The development loop

gratos has no watch mode. Restart the app on save with node --watch-path, and boot it through the lazy gratos/dev entry: devSchema (an Effect) or loadSchema (a Promise of a Result) regenerates the schema, writing only the files that changed, and then calls your load to import the app. It starts no server and answers no request: when the models do not build, or the app does not load, it fails with a GratsDevError holding the diagnostics (loadSchema resolves to a failed Result, and never rejects). Serving that is the caller's job, since the caller owns the listener. error.response() builds the answer, a 500 with one GRATS_ERROR error and the diagnostics, new on each call. The orders app serves it for every request, on any path, until the next good save restarts the process:

examples/orders/src/server.ts
/** The app, or (in dev) why the models or the app do not build or load. */
const app: Effect.Effect<Result.Result<AppLayer, GratsDevError>, never, FileSystem.FileSystem> = dev
  ? Effect.promise(() => import("gratos/dev")).pipe(
      Effect.flatMap((gratos) =>
        gratos.devSchema({ tsconfig: new URL("tsconfig.json", import.meta.url), load: loadApp }),
      ),
      Effect.result,
    )
  : Effect.map(Effect.promise(loadApp), Result.succeed);

/**
 * The app, or GRATS_ERROR for every request: served by the HTTP server itself, with no router, so
 * no path (not even one the router could not decode, such as `/%FF`) misses it.
 */
const appLayer = Layer.unwrap(
  Effect.map(app, (loaded) => {
    if (Result.isSuccess(loaded)) {
      return loaded.success;
    }
    const error = loaded.failure;
    return HttpServer.serve(Effect.sync(() => HttpServerResponse.fromWeb(error.response())));
  }),
);

A production start loads the same modules directly, and never loads the compiler or TypeScript.