mirror of
https://github.com/Effect-TS/effect.git
synced 2026-12-06 03:59:09 +08:00
feat(graphql): effect/graphql runtime core
Add the experimental effect/graphql module: GraphQL operations as plain
values, groups with group-level middleware, a client with one method per
operation, GraphQL-level middleware tags with { execute, subscribe } and
mapRequest, the GraphQLProtocol service with an HTTP transport for
queries and mutations, the GraphQLClientError model with five
Schema.TaggedError reasons and isRetryable, per-call partial results,
the pages / items cursor paging helpers, and the otherTypename /
enumLiterals lenient decoding helpers for generated code.
Register the ./graphql export, add the effect/graphql test path alias,
and add the effect changeset.
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"effect": patch
|
||||
---
|
||||
|
||||
Add the experimental `effect/graphql` module: a typed GraphQL client built from operation values and groups, with GraphQL-level middleware, an HTTP transport, a serializable error model, partial results, cursor paging helpers, and the lenient `otherTypename` / `enumLiterals` decoding helpers used by generated code.
|
||||
@@ -46,6 +46,7 @@
|
||||
"./persistence": "./src/persistence/index.ts",
|
||||
"./process": "./src/process/index.ts",
|
||||
"./reactivity": "./src/reactivity/index.ts",
|
||||
"./graphql": "./src/graphql/index.ts",
|
||||
"./rpc": "./src/rpc/index.ts",
|
||||
"./schema": "./src/schema/index.ts",
|
||||
"./socket": "./src/socket/index.ts",
|
||||
@@ -89,6 +90,7 @@
|
||||
"./persistence": "./dist/persistence/index.js",
|
||||
"./process": "./dist/process/index.js",
|
||||
"./reactivity": "./dist/reactivity/index.js",
|
||||
"./graphql": "./dist/graphql/index.js",
|
||||
"./rpc": "./dist/rpc/index.js",
|
||||
"./schema": "./dist/schema/index.js",
|
||||
"./socket": "./dist/socket/index.js",
|
||||
|
||||
@@ -0,0 +1,432 @@
|
||||
/**
|
||||
* GraphQL operations as plain values.
|
||||
*
|
||||
* **Details**
|
||||
*
|
||||
* An operation carries its printed document, its name, a variables Schema and
|
||||
* a result Schema. `@effect/graphql-generator` emits one per operation in a
|
||||
* `.graphql` file; they can also be written by hand. Operations are grouped
|
||||
* with `GraphQLGroup` and turned into a client with `GraphQLClient.make`.
|
||||
*
|
||||
* This module also holds the two lenient decoding helpers the generator
|
||||
* emits: {@link otherTypename} and {@link enumLiterals}.
|
||||
*
|
||||
* @stability experimental
|
||||
* @since 4.0.0
|
||||
*/
|
||||
import { dual } from "../Function.ts"
|
||||
import { type Pipeable, pipeArguments } from "../Pipeable.ts"
|
||||
import { hasProperty } from "../Predicate.ts"
|
||||
import * as Schema from "../Schema.ts"
|
||||
import type { GraphQLClientError } from "./GraphQLClientError.ts"
|
||||
import type * as GraphQLMiddleware from "./GraphQLMiddleware.ts"
|
||||
|
||||
const TypeId = "~effect/graphql/GraphQL"
|
||||
|
||||
/**
|
||||
* The three kinds of GraphQL operation.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category models
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export type Kind = "query" | "mutation" | "subscription"
|
||||
|
||||
/**
|
||||
* A GraphQL operation: the document to send, the operation name, the
|
||||
* variables Schema (encoded before sending) and the result Schema (decoded
|
||||
* from `data`), plus the middleware attached to this operation.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category models
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export interface Operation<
|
||||
out K extends Kind,
|
||||
out Name extends string,
|
||||
out Variables extends Schema.Top,
|
||||
out Result extends Schema.Top,
|
||||
out Middleware = never
|
||||
> extends Pipeable {
|
||||
readonly [TypeId]: typeof TypeId
|
||||
readonly kind: K
|
||||
readonly name: Name
|
||||
/** The printed document, sent as-is. It is never parsed at runtime. */
|
||||
readonly document: string
|
||||
readonly variables: Variables
|
||||
readonly result: Result
|
||||
/** Middleware attached to this operation, outermost first. */
|
||||
readonly middlewares: ReadonlyArray<GraphQLMiddleware.AnyService>
|
||||
readonly "~middleware"?: Middleware
|
||||
}
|
||||
|
||||
/**
|
||||
* Any operation, with its type parameters erased.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category utility types
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export type Any = Operation<Kind, string, Schema.Top, Schema.Top, any>
|
||||
|
||||
/**
|
||||
* Extracts the union of middleware attached to an operation.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category utility types
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export type Middleware<Op> = Op extends Operation<any, any, any, any, infer M> ? M : never
|
||||
|
||||
/**
|
||||
* The decoded variables type of an operation, which is what a client method
|
||||
* takes.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category utility types
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export type Variables<Op extends Any> = Op["variables"]["Type"]
|
||||
|
||||
/**
|
||||
* The decoded result type of an operation.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category utility types
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export type Result<Op extends Any> = Op["result"]["Type"]
|
||||
|
||||
/**
|
||||
* The error type of a client method for an operation: `GraphQLClientError`
|
||||
* plus the errors of every attached middleware.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category utility types
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export type Error<Op extends Any> = GraphQLClientError | GraphQLMiddleware.Error<Middleware<Op>>
|
||||
|
||||
/**
|
||||
* The services a client method for an operation requires: the Schemas'
|
||||
* encoding and decoding services plus the requirements of every attached
|
||||
* middleware.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category utility types
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export type Services<Op extends Any> =
|
||||
| Op["variables"]["EncodingServices"]
|
||||
| Op["result"]["DecodingServices"]
|
||||
| GraphQLMiddleware.Requires<Middleware<Op>>
|
||||
|
||||
/**
|
||||
* The type of an operation after attaching middleware `M`.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category utility types
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export type AddMiddleware<Op, M> = Op extends Operation<infer K, infer N, infer V, infer R, infer Old>
|
||||
? Operation<K, N, V, R, Old | M>
|
||||
: never
|
||||
|
||||
/**
|
||||
* Tests whether a value is an {@link Operation}.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category guards
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export const isOperation = (u: unknown): u is Any => hasProperty(u, TypeId)
|
||||
|
||||
const Proto = {
|
||||
[TypeId]: TypeId,
|
||||
pipe() {
|
||||
return pipeArguments(this, arguments)
|
||||
}
|
||||
}
|
||||
|
||||
const makeProto = (fields: Omit<Any, typeof TypeId | "pipe">): Any => Object.assign(Object.create(Proto), fields)
|
||||
|
||||
/**
|
||||
* The options accepted by {@link query}, {@link mutation} and
|
||||
* {@link subscription}. `variables` takes struct fields or any Schema; leaving
|
||||
* it out means the operation has no variables.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category models
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export interface Options<Variables extends Schema.Top | Schema.Struct.Fields, Result extends Schema.Top> {
|
||||
readonly document: string
|
||||
readonly variables?: Variables | undefined
|
||||
readonly result: Result
|
||||
}
|
||||
|
||||
const makeOperation = <const K extends Kind>(kind: K) =>
|
||||
<
|
||||
const Name extends string,
|
||||
Result extends Schema.Top,
|
||||
Variables extends Schema.Top | Schema.Struct.Fields = Schema.Struct<{}>
|
||||
>(
|
||||
name: Name,
|
||||
options: Options<Variables, Result>
|
||||
): Operation<K, Name, Variables extends Schema.Struct.Fields ? Schema.Struct<Variables> : Variables, Result> =>
|
||||
makeProto({
|
||||
kind,
|
||||
name,
|
||||
document: options.document,
|
||||
variables: options.variables === undefined
|
||||
? Schema.Struct({})
|
||||
: Schema.isSchema(options.variables)
|
||||
? options.variables
|
||||
: Schema.Struct(options.variables as Schema.Struct.Fields),
|
||||
result: options.result,
|
||||
middlewares: []
|
||||
}) as any
|
||||
|
||||
/**
|
||||
* Defines a query. Variables are passed to the client as their decoded type
|
||||
* and encoded through the Schema, so custom scalar codecs apply to inputs as
|
||||
* well as results.
|
||||
*
|
||||
* **Example** (A query with variables)
|
||||
*
|
||||
* ```ts import.meta.vitest
|
||||
* import { Schema } from "effect"
|
||||
* import { GraphQL } from "effect/graphql"
|
||||
*
|
||||
* const RepoIssues = GraphQL.query("RepoIssues", {
|
||||
* document: "query RepoIssues($owner:String!,$name:String!){repository(owner:$owner,name:$name){issues(first:10){nodes{number title}}}}",
|
||||
* variables: { owner: Schema.String, name: Schema.String },
|
||||
* result: Schema.Struct({
|
||||
* repository: Schema.NullOr(Schema.Struct({
|
||||
* issues: Schema.Struct({
|
||||
* nodes: Schema.NullOr(Schema.Array(Schema.NullOr(Schema.Struct({ number: Schema.Int, title: Schema.String }))))
|
||||
* })
|
||||
* }))
|
||||
* })
|
||||
* })
|
||||
*
|
||||
* RepoIssues.kind // => "query"
|
||||
* RepoIssues.name // => "RepoIssues"
|
||||
* ```
|
||||
*
|
||||
* @stability experimental
|
||||
* @category constructors
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export const query: <
|
||||
const Name extends string,
|
||||
Result extends Schema.Top,
|
||||
Variables extends Schema.Top | Schema.Struct.Fields = Schema.Struct<{}>
|
||||
>(
|
||||
name: Name,
|
||||
options: Options<Variables, Result>
|
||||
) => Operation<"query", Name, Variables extends Schema.Struct.Fields ? Schema.Struct<Variables> : Variables, Result> =
|
||||
makeOperation("query")
|
||||
|
||||
/**
|
||||
* Defines a mutation. Same shape as {@link query}.
|
||||
*
|
||||
* **Example** (A mutation)
|
||||
*
|
||||
* ```ts import.meta.vitest
|
||||
* import { Schema } from "effect"
|
||||
* import { GraphQL } from "effect/graphql"
|
||||
*
|
||||
* const AddComment = GraphQL.mutation("AddComment", {
|
||||
* document: "mutation AddComment($subjectId:ID!,$body:String!){addComment(input:{subjectId:$subjectId,body:$body}){clientMutationId}}",
|
||||
* variables: { subjectId: Schema.String, body: Schema.String },
|
||||
* result: Schema.Struct({ addComment: Schema.NullOr(Schema.Struct({ clientMutationId: Schema.NullOr(Schema.String) })) })
|
||||
* })
|
||||
*
|
||||
* AddComment.kind // => "mutation"
|
||||
* ```
|
||||
*
|
||||
* @stability experimental
|
||||
* @category constructors
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export const mutation: <
|
||||
const Name extends string,
|
||||
Result extends Schema.Top,
|
||||
Variables extends Schema.Top | Schema.Struct.Fields = Schema.Struct<{}>
|
||||
>(
|
||||
name: Name,
|
||||
options: Options<Variables, Result>
|
||||
) => Operation<
|
||||
"mutation",
|
||||
Name,
|
||||
Variables extends Schema.Struct.Fields ? Schema.Struct<Variables> : Variables,
|
||||
Result
|
||||
> = makeOperation("mutation")
|
||||
|
||||
/**
|
||||
* Defines a subscription. The client method for a subscription returns a
|
||||
* `Stream` of decoded events instead of an `Effect`.
|
||||
*
|
||||
* **Example** (A subscription)
|
||||
*
|
||||
* ```ts import.meta.vitest
|
||||
* import { Schema } from "effect"
|
||||
* import { GraphQL } from "effect/graphql"
|
||||
*
|
||||
* const IssueUpdated = GraphQL.subscription("IssueUpdated", {
|
||||
* document: "subscription IssueUpdated($id:ID!){issueUpdated(id:$id){title}}",
|
||||
* variables: { id: Schema.String },
|
||||
* result: Schema.Struct({ issueUpdated: Schema.Struct({ title: Schema.String }) })
|
||||
* })
|
||||
*
|
||||
* IssueUpdated.kind // => "subscription"
|
||||
* ```
|
||||
*
|
||||
* @stability experimental
|
||||
* @category constructors
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export const subscription: <
|
||||
const Name extends string,
|
||||
Result extends Schema.Top,
|
||||
Variables extends Schema.Top | Schema.Struct.Fields = Schema.Struct<{}>
|
||||
>(
|
||||
name: Name,
|
||||
options: Options<Variables, Result>
|
||||
) => Operation<
|
||||
"subscription",
|
||||
Name,
|
||||
Variables extends Schema.Struct.Fields ? Schema.Struct<Variables> : Variables,
|
||||
Result
|
||||
> = makeOperation("subscription")
|
||||
|
||||
/**
|
||||
* Attaches a middleware to one operation. Operation middleware runs inside
|
||||
* any group middleware; within the operation, middleware run in the order
|
||||
* they were attached.
|
||||
*
|
||||
* **Example** (Auth on a single operation)
|
||||
*
|
||||
* ```ts import.meta.vitest
|
||||
* import { Schema } from "effect"
|
||||
* import { GraphQL, GraphQLMiddleware } from "effect/graphql"
|
||||
*
|
||||
* class Auth extends GraphQLMiddleware.Service<Auth>()("app/Auth") {}
|
||||
*
|
||||
* const Viewer = GraphQL.query("Viewer", {
|
||||
* document: "query Viewer{viewer{login}}",
|
||||
* result: Schema.Struct({ viewer: Schema.Struct({ login: Schema.String }) })
|
||||
* })
|
||||
*
|
||||
* const AuthedViewer = GraphQL.middleware(Viewer, Auth)
|
||||
*
|
||||
* AuthedViewer.middlewares.length // => 1
|
||||
* Viewer.middlewares.length // => 0
|
||||
* ```
|
||||
*
|
||||
* @stability experimental
|
||||
* @category combinators
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export const middleware: {
|
||||
<M extends GraphQLMiddleware.AnyService>(middleware: M): <Op extends Any>(self: Op) => AddMiddleware<Op, M>
|
||||
<Op extends Any, M extends GraphQLMiddleware.AnyService>(self: Op, middleware: M): AddMiddleware<Op, M>
|
||||
} = dual(
|
||||
2,
|
||||
<Op extends Any, M extends GraphQLMiddleware.AnyService>(self: Op, middleware: M): AddMiddleware<Op, M> =>
|
||||
makeProto({
|
||||
kind: self.kind,
|
||||
name: self.name,
|
||||
document: self.document,
|
||||
variables: self.variables,
|
||||
result: self.result,
|
||||
middlewares: [...self.middlewares, middleware]
|
||||
}) as any
|
||||
)
|
||||
|
||||
/**
|
||||
* The `__typename` Schema for the "every other type" member of a generated
|
||||
* union.
|
||||
*
|
||||
* **Details**
|
||||
*
|
||||
* When a document selects `... on Issue` from a `Node`, the generator emits
|
||||
* one struct per selected type and a last struct for everything else, whose
|
||||
* `__typename` is `otherTypename<Typename.Node>()(["Issue"])`. It is typed as
|
||||
* the possible names minus the selected ones, so narrowing on `__typename`
|
||||
* works. It decodes any other string, so a type the server adds later still
|
||||
* decodes, and it rejects the selected names, so a malformed `Issue` fails
|
||||
* instead of falling through to the last struct.
|
||||
*
|
||||
* **Example** (The catch-all member of a union)
|
||||
*
|
||||
* ```ts import.meta.vitest
|
||||
* import { Schema } from "effect"
|
||||
* import { GraphQL } from "effect/graphql"
|
||||
*
|
||||
* type Node = "Issue" | "PullRequest" | "Repository"
|
||||
*
|
||||
* const OtherNode = Schema.Struct({
|
||||
* __typename: GraphQL.otherTypename<Node>()(["Issue"]),
|
||||
* id: Schema.String
|
||||
* })
|
||||
*
|
||||
* Schema.decodeUnknownSync(OtherNode)({ __typename: "PullRequest", id: "1" }).__typename // => "PullRequest"
|
||||
* Schema.decodeUnknownSync(OtherNode)({ __typename: "AddedLater", id: "2" }).__typename // => "AddedLater"
|
||||
* Schema.is(OtherNode)({ __typename: "Issue", id: "3" }) // => false
|
||||
* ```
|
||||
*
|
||||
* @stability experimental
|
||||
* @category schemas
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export const otherTypename = <All extends string>() =>
|
||||
<const Selected extends ReadonlyArray<All>>(
|
||||
selected: Selected
|
||||
): Schema.Codec<Exclude<All, Selected[number]>, string> => {
|
||||
const rejected = new Set<string>(selected)
|
||||
return Schema.String.check(
|
||||
Schema.makeFilter(
|
||||
(name) =>
|
||||
rejected.has(name)
|
||||
? `Expected a __typename other than ${selected.map((s) => `"${s}"`).join(", ")}`
|
||||
: undefined,
|
||||
{ title: "otherTypename" }
|
||||
)
|
||||
) as any
|
||||
}
|
||||
|
||||
/**
|
||||
* The Schema for a GraphQL enum in a result position.
|
||||
*
|
||||
* **Details**
|
||||
*
|
||||
* It is typed as the declared literals but decodes any string, so a value the
|
||||
* server adds later does not fail the whole query. Inputs stay strict: the
|
||||
* generator uses `Schema.Literals` for enums in variables and input objects.
|
||||
*
|
||||
* **Example** (An enum that tolerates new values)
|
||||
*
|
||||
* ```ts import.meta.vitest
|
||||
* import { Schema } from "effect"
|
||||
* import { GraphQL } from "effect/graphql"
|
||||
*
|
||||
* const IssueState = GraphQL.enumLiterals(["OPEN", "CLOSED"])
|
||||
*
|
||||
* Schema.decodeUnknownSync(IssueState)("OPEN") // => "OPEN"
|
||||
* Schema.decodeUnknownSync(IssueState)("MERGED") // => "MERGED"
|
||||
* Schema.is(IssueState)(42) // => false
|
||||
* ```
|
||||
*
|
||||
* @stability experimental
|
||||
* @category schemas
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export const enumLiterals = <const Literals extends ReadonlyArray<string>>(
|
||||
literals: Literals
|
||||
): Schema.Codec<Literals[number], string> =>
|
||||
Schema.String.annotate({
|
||||
title: `enum(${literals.join(" | ")})`,
|
||||
description: `One of ${literals.map((l) => `"${l}"`).join(", ")}, or any string the server adds later`
|
||||
}) as any
|
||||
@@ -0,0 +1,651 @@
|
||||
/**
|
||||
* A typed GraphQL client built from a `GraphQLGroup`.
|
||||
*
|
||||
* **Details**
|
||||
*
|
||||
* `make(group)` returns an object with one method per operation. Queries and
|
||||
* mutations return an `Effect`, subscriptions return a `Stream`. The client
|
||||
* encodes variables, runs the middleware chain, sends the request through the
|
||||
* `GraphQLProtocol` in context, and decodes `data` with the result Schema.
|
||||
*
|
||||
* `pages` and `items` page through cursor connections with a client method.
|
||||
*
|
||||
* @stability experimental
|
||||
* @since 4.0.0
|
||||
*/
|
||||
import * as Context from "../Context.ts"
|
||||
import * as Duration from "../Duration.ts"
|
||||
import * as Effect from "../Effect.ts"
|
||||
import * as Schedule from "../Schedule.ts"
|
||||
import * as Schema from "../Schema.ts"
|
||||
import * as Stream from "../Stream.ts"
|
||||
import type * as GraphQL from "./GraphQL.ts"
|
||||
import {
|
||||
DecodeError,
|
||||
EncodeError,
|
||||
GraphQLClientError,
|
||||
type GraphQLError,
|
||||
isGraphQLClientError,
|
||||
PaginationError,
|
||||
type Reason,
|
||||
ResponseError
|
||||
} from "./GraphQLClientError.ts"
|
||||
import type { GraphQLGroup } from "./GraphQLGroup.ts"
|
||||
import type * as GraphQLMiddleware from "./GraphQLMiddleware.ts"
|
||||
import { ExecutionResult, GraphQLProtocol, type GraphQLRequest } from "./GraphQLProtocol.ts"
|
||||
|
||||
/**
|
||||
* What a query or mutation returns when called with `{ partial: true }`:
|
||||
* the decoded `data` together with the response `errors`, which may be empty.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category models
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export interface PartialResult<A> {
|
||||
readonly data: A
|
||||
readonly errors: ReadonlyArray<GraphQLError>
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-call options shared by every method. `headers` are sent by the HTTP
|
||||
* transport and visible to middleware. `context` provides services for this
|
||||
* call only, and removes them from the method's requirements.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category models
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export interface CallOptions<R = never> {
|
||||
readonly headers?: Readonly<Record<string, string>> | undefined
|
||||
readonly context?: Context.Context<R> | undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* The options of a query or mutation call that returns a {@link PartialResult}.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category models
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export interface PartialCallOptions<R = never> extends CallOptions<R> {
|
||||
readonly partial: true
|
||||
}
|
||||
|
||||
/**
|
||||
* The options of a query or mutation call that fails on any `errors`.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category models
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export interface StrictCallOptions<R = never> extends CallOptions<R> {
|
||||
readonly partial?: false | undefined
|
||||
}
|
||||
|
||||
type Args<Variables, Options> = {} extends Variables ? [variables?: Variables, options?: Options]
|
||||
: [variables: Variables, options?: Options]
|
||||
|
||||
type ArgsWithOptions<Variables, Options> = {} extends Variables ? [variables: Variables | undefined, options: Options]
|
||||
: [variables: Variables, options: Options]
|
||||
|
||||
/**
|
||||
* The client method for a query or mutation.
|
||||
*
|
||||
* **Details**
|
||||
*
|
||||
* Called as `(variables?, options?)`. Without `partial`, or with
|
||||
* `partial: false`, it returns the decoded result and fails with a
|
||||
* `ResponseError` on any `errors`. With `partial: true` it returns
|
||||
* `{ data, errors }`. The two overloads are explicit so that a `boolean`
|
||||
* `partial` does not compile.
|
||||
*
|
||||
* An operation without variables is called as `client.Viewer()` or, with
|
||||
* options, `client.Viewer(undefined, { headers })`.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category models
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export interface OperationMethod<Op extends GraphQL.Any> {
|
||||
/** The operation this method runs. */
|
||||
readonly operation: Op
|
||||
<R2 = never>(
|
||||
...args: ArgsWithOptions<GraphQL.Variables<Op>, PartialCallOptions<R2>>
|
||||
): Effect.Effect<PartialResult<GraphQL.Result<Op>>, GraphQL.Error<Op>, Exclude<GraphQL.Services<Op>, R2>>
|
||||
<R2 = never>(
|
||||
...args: Args<GraphQL.Variables<Op>, StrictCallOptions<R2>>
|
||||
): Effect.Effect<GraphQL.Result<Op>, GraphQL.Error<Op>, Exclude<GraphQL.Services<Op>, R2>>
|
||||
}
|
||||
|
||||
/**
|
||||
* The client method for a subscription. It returns a `Stream` of decoded
|
||||
* events; an event with `errors` fails the stream with a `ResponseError`.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category models
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export interface SubscriptionMethod<Op extends GraphQL.Any> {
|
||||
/** The operation this method runs. */
|
||||
readonly operation: Op
|
||||
<R2 = never>(
|
||||
...args: Args<GraphQL.Variables<Op>, CallOptions<R2>>
|
||||
): Stream.Stream<GraphQL.Result<Op>, GraphQL.Error<Op>, Exclude<GraphQL.Services<Op>, R2>>
|
||||
}
|
||||
|
||||
/**
|
||||
* The client method type for an operation, by its kind.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category models
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export type Method<Op extends GraphQL.Any> = Op["kind"] extends "subscription" ? SubscriptionMethod<Op>
|
||||
: OperationMethod<Op>
|
||||
|
||||
/**
|
||||
* A client: one method per operation, keyed by operation name.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category models
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export type GraphQLClient<Ops extends GraphQL.Any> = {
|
||||
readonly [Op in Ops as Op["name"]]: Method<Op>
|
||||
}
|
||||
|
||||
/**
|
||||
* Options for {@link make}.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category models
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export interface Options {
|
||||
/**
|
||||
* How a subscription is retried after the transport fails it with a
|
||||
* retryable `TransportError`. Defaults to {@link defaultSubscriptionRetry}.
|
||||
* Fatal errors are never retried, whatever the schedule.
|
||||
*/
|
||||
readonly subscriptionRetry?: Schedule.Schedule<unknown, GraphQLClientError> | undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* The default subscription retry schedule: exponential from 500 milliseconds
|
||||
* with factor 1.5, capped at 5 seconds, and never shorter than the server's
|
||||
* `retryAfter`.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category constants
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export const defaultSubscriptionRetry: Schedule.Schedule<Duration.Duration, GraphQLClientError> = Schedule.exponential(
|
||||
"500 millis",
|
||||
1.5
|
||||
).pipe(
|
||||
Schedule.setInputType<GraphQLClientError>(),
|
||||
Schedule.modifyDelay(({ duration, input }) => {
|
||||
const capped = Duration.toMillis(duration) > 5_000 ? Duration.seconds(5) : duration
|
||||
const retryAfter = input.retryAfter
|
||||
return Effect.succeed(
|
||||
retryAfter !== undefined && Duration.toMillis(retryAfter) > Duration.toMillis(capped) ? retryAfter : capped
|
||||
)
|
||||
})
|
||||
)
|
||||
|
||||
/**
|
||||
* Builds a client from a group. The effect requires the `GraphQLProtocol` and
|
||||
* every middleware tag attached to the group or its operations, so a missing
|
||||
* middleware layer is a type error where the client is built.
|
||||
*
|
||||
* **Details**
|
||||
*
|
||||
* Group middleware runs outside operation middleware. Within each level,
|
||||
* middleware run in the order attached.
|
||||
*
|
||||
* **Example** (A client as a service)
|
||||
*
|
||||
* ```ts import.meta.vitest
|
||||
* import { Context, Effect, Layer, Schema, Stream } from "effect"
|
||||
* import { GraphQL, GraphQLClient, GraphQLGroup, GraphQLProtocol } from "effect/graphql"
|
||||
*
|
||||
* // What the generator emits for viewer.graphql
|
||||
* const Viewer = GraphQL.query("Viewer", {
|
||||
* document: "query Viewer{viewer{login}}",
|
||||
* result: Schema.Struct({ viewer: Schema.Struct({ login: Schema.String }) })
|
||||
* })
|
||||
* const ViewerGroup = GraphQLGroup.make(Viewer)
|
||||
*
|
||||
* class GitHub extends Context.Service<GitHub>()("app/GitHub", {
|
||||
* make: GraphQLClient.make(ViewerGroup)
|
||||
* }) {}
|
||||
*
|
||||
* // A scripted transport; use GraphQLProtocol.layerHttp({ url }) for a real server
|
||||
* const Scripted = Layer.succeed(GraphQLProtocol.GraphQLProtocol, {
|
||||
* execute: () => Effect.succeed({ data: { viewer: { login: "tim" } } }),
|
||||
* subscribe: () => Stream.empty
|
||||
* })
|
||||
*
|
||||
* const program = GitHub.use((github) => github.Viewer()).pipe(
|
||||
* Effect.provide(Layer.effect(GitHub, GitHub.make).pipe(Layer.provide(Scripted)))
|
||||
* )
|
||||
*
|
||||
* await Effect.runPromise(program) // => { viewer: { login: "tim" } }
|
||||
* ```
|
||||
*
|
||||
* **Example** (Partial results)
|
||||
*
|
||||
* ```ts import.meta.vitest
|
||||
* import { Effect, Layer, Schema, Stream } from "effect"
|
||||
* import { GraphQL, GraphQLClient, GraphQLGroup, GraphQLProtocol } from "effect/graphql"
|
||||
*
|
||||
* const Repos = GraphQL.query("Repos", {
|
||||
* document: "query Repos{a:repository(owner:\"x\",name:\"a\"){name} b:repository(owner:\"x\",name:\"b\"){name}}",
|
||||
* result: Schema.Struct({
|
||||
* a: Schema.NullOr(Schema.Struct({ name: Schema.String })),
|
||||
* b: Schema.NullOr(Schema.Struct({ name: Schema.String }))
|
||||
* })
|
||||
* })
|
||||
*
|
||||
* const Scripted = Layer.succeed(GraphQLProtocol.GraphQLProtocol, {
|
||||
* execute: () =>
|
||||
* Effect.succeed({
|
||||
* data: { a: { name: "a" }, b: null },
|
||||
* errors: [{ message: "Could not resolve to a Repository", path: ["b"] }]
|
||||
* }),
|
||||
* subscribe: () => Stream.empty
|
||||
* })
|
||||
*
|
||||
* const program = Effect.gen(function*() {
|
||||
* const client = yield* GraphQLClient.make(GraphQLGroup.make(Repos))
|
||||
* // The default call fails with a ResponseError because `errors` is non-empty
|
||||
* const failed = yield* Effect.flip(client.Repos())
|
||||
* // With partial: true the decoded data comes back together with the errors
|
||||
* const { data, errors } = yield* client.Repos(undefined, { partial: true })
|
||||
* return [failed.reason._tag, data.a?.name, errors[0].path?.[0]]
|
||||
* })
|
||||
*
|
||||
* await Effect.runPromise(program.pipe(Effect.provide(Scripted))) // => ["ResponseError", "a", "b"]
|
||||
* ```
|
||||
*
|
||||
* @stability experimental
|
||||
* @category constructors
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export const make = <Ops extends GraphQL.Any>(
|
||||
group: GraphQLGroup<Ops>,
|
||||
options?: Options | undefined
|
||||
): Effect.Effect<
|
||||
GraphQLClient<Ops>,
|
||||
never,
|
||||
GraphQLProtocol | GraphQLMiddleware.Identifier<GraphQL.Middleware<Ops>>
|
||||
> =>
|
||||
Effect.gen(function*() {
|
||||
const protocol = yield* GraphQLProtocol
|
||||
const context = yield* Effect.context<never>()
|
||||
const retryPolicy = Schedule.while(
|
||||
(options?.subscriptionRetry ?? defaultSubscriptionRetry) as Schedule.Schedule<unknown, unknown>,
|
||||
({ input }) => isGraphQLClientError(input) && input.isRetryable
|
||||
)
|
||||
const client: Record<string, unknown> = {}
|
||||
for (const operation of group.operations) {
|
||||
const chain = [...group.middlewares, ...operation.middlewares].map((tag) =>
|
||||
Context.getUnsafe(context, tag) as GraphQLMiddleware.Implementation<any, any>
|
||||
)
|
||||
client[operation.name] = makeMethod(operation, chain, protocol, retryPolicy)
|
||||
}
|
||||
return client as GraphQLClient<Ops>
|
||||
})
|
||||
|
||||
const decodeExecutionResult = Schema.decodeUnknownEffect(ExecutionResult)
|
||||
|
||||
const makeMethod = (
|
||||
operation: GraphQL.Any,
|
||||
chain: ReadonlyArray<GraphQLMiddleware.Implementation<any, any>>,
|
||||
protocol: GraphQLProtocol["Service"],
|
||||
retryPolicy: Schedule.Schedule<unknown, unknown>
|
||||
) => {
|
||||
const fail = (reason: Reason) => new GraphQLClientError({ operation: operation.name, reason })
|
||||
const schemaFail = (make: (description: string) => Reason) => (error: Schema.SchemaError) =>
|
||||
Effect.fail(fail(make(error.message)))
|
||||
const encodeVariables = Schema.encodeUnknownEffect(operation.variables)
|
||||
const decodeResult = Schema.decodeUnknownEffect(operation.result)
|
||||
|
||||
const notGraphQL = schemaFail((description) =>
|
||||
new DecodeError({ description: `Not a GraphQL response: ${description}` })
|
||||
)
|
||||
|
||||
const buildRequest = (
|
||||
variables: unknown,
|
||||
options: CallOptions<any> | undefined
|
||||
): Effect.Effect<GraphQLRequest, GraphQLClientError, any> =>
|
||||
encodeVariables(variables ?? {}).pipe(
|
||||
Effect.catch(schemaFail((description) => new EncodeError({ description }))),
|
||||
Effect.map((encoded) => ({
|
||||
query: operation.document,
|
||||
operationName: operation.name,
|
||||
variables: encoded,
|
||||
headers: options?.headers ?? {}
|
||||
}))
|
||||
)
|
||||
|
||||
const execute = (index: number, request: GraphQLRequest): Effect.Effect<ExecutionResult, any, any> =>
|
||||
index === chain.length
|
||||
? protocol.execute(request).pipe(
|
||||
Effect.mapError(fail),
|
||||
Effect.flatMap((body) => Effect.catch(decodeExecutionResult(body), notGraphQL))
|
||||
)
|
||||
: chain[index].execute({
|
||||
operation,
|
||||
request,
|
||||
next: (request) => execute(index + 1, request) as Effect.Effect<ExecutionResult, GraphQLClientError>
|
||||
})
|
||||
|
||||
const subscribe = (index: number, request: GraphQLRequest): Stream.Stream<ExecutionResult, any, any> =>
|
||||
index === chain.length
|
||||
? protocol.subscribe(request).pipe(
|
||||
Stream.mapError(fail),
|
||||
Stream.mapEffect((event) => Effect.catch(decodeExecutionResult(event), notGraphQL))
|
||||
)
|
||||
: chain[index].subscribe({
|
||||
operation,
|
||||
request,
|
||||
next: (request) => subscribe(index + 1, request) as Stream.Stream<ExecutionResult, GraphQLClientError>
|
||||
})
|
||||
|
||||
const decodeData = (result: ExecutionResult) =>
|
||||
Effect.catch(decodeResult(result.data), schemaFail((description) => new DecodeError({ description })))
|
||||
|
||||
const responseError = (result: ExecutionResult, errors: ReadonlyArray<GraphQLError>) =>
|
||||
Effect.fail(fail(
|
||||
new ResponseError({
|
||||
errors: errors as unknown as ConstructorParameters<typeof ResponseError>[0]["errors"],
|
||||
...(result.data === undefined ? {} : { data: result.data as Schema.Json }),
|
||||
...(result.extensions === undefined ? {} : { extensions: result.extensions })
|
||||
})
|
||||
))
|
||||
|
||||
const finish = (result: ExecutionResult, partial: boolean): Effect.Effect<unknown, any, any> => {
|
||||
const errors = result.errors ?? []
|
||||
if (errors.length > 0) {
|
||||
// Without partial results any error fails the call. With them, errors
|
||||
// and a missing data still mean there is nothing to return.
|
||||
if (!partial || result.data === null || result.data === undefined) {
|
||||
return responseError(result, errors)
|
||||
}
|
||||
return Effect.map(decodeData(result), (data) => ({ data, errors }))
|
||||
}
|
||||
return partial ? Effect.map(decodeData(result), (data) => ({ data, errors })) : decodeData(result)
|
||||
}
|
||||
|
||||
if (operation.kind === "subscription") {
|
||||
const method = (variables?: unknown, options?: CallOptions<any>) => {
|
||||
const stream = Stream.unwrap(
|
||||
Effect.map(buildRequest(variables, options), (request) => subscribe(0, request))
|
||||
).pipe(
|
||||
Stream.mapEffect((event) => finish(event, false)),
|
||||
Stream.retry(retryPolicy)
|
||||
)
|
||||
return options?.context === undefined
|
||||
? stream
|
||||
: Stream.updateContext(stream, (outer) => Context.merge(outer, options.context!))
|
||||
}
|
||||
return Object.assign(method, { operation })
|
||||
}
|
||||
|
||||
const method = (variables?: unknown, options?: StrictCallOptions<any> | PartialCallOptions<any>) => {
|
||||
const effect = buildRequest(variables, options).pipe(
|
||||
Effect.flatMap((request) => execute(0, request)),
|
||||
Effect.flatMap((result) => finish(result, options?.partial === true))
|
||||
)
|
||||
return options?.context === undefined
|
||||
? effect
|
||||
: Effect.updateContext(effect, (outer) => Context.merge(outer, options.context!))
|
||||
}
|
||||
return Object.assign(method, { operation })
|
||||
}
|
||||
|
||||
/**
|
||||
* The `pageInfo` a paged connection must select.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category paging
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export interface PageInfo {
|
||||
readonly hasNextPage: boolean
|
||||
readonly endCursor: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
* What the `connection` getter of {@link pages} must return.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category paging
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export interface Connection {
|
||||
readonly pageInfo: PageInfo
|
||||
}
|
||||
|
||||
/**
|
||||
* What the `connection` getter of {@link items} must return: a connection
|
||||
* that also selects `nodes`.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category paging
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export interface NodesConnection<Node> extends Connection {
|
||||
readonly nodes: ReadonlyArray<Node> | null
|
||||
}
|
||||
|
||||
/**
|
||||
* The type `variables` is given when the operation has no `$after` variable.
|
||||
* Nothing is assignable to it, so the mistake is a compile error at the call.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category paging
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export interface MissingAfterVariable {
|
||||
readonly "effect/graphql":
|
||||
"GraphQLClient.pages requires the operation to declare a nullable `$after: String` variable"
|
||||
}
|
||||
|
||||
/**
|
||||
* The `variables` accepted by {@link pages} and {@link items}: the method's
|
||||
* variables without `after`, which the helper supplies.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category paging
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export type PagingVariables<Variables> = "after" extends keyof Variables ? Omit<Variables, "after">
|
||||
: MissingAfterVariable
|
||||
|
||||
/**
|
||||
* Options for {@link pages} and {@link items}. `options` is forwarded to every
|
||||
* page and cannot carry `partial`: a page with errors fails the stream.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category paging
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export interface PagingOptions<Op extends GraphQL.Any, C, R2> {
|
||||
readonly variables: PagingVariables<GraphQL.Variables<Op>>
|
||||
readonly connection: (result: GraphQL.Result<Op>) => C | null | undefined
|
||||
readonly options?: CallOptions<R2> | undefined
|
||||
}
|
||||
|
||||
interface PagingState {
|
||||
readonly after: string | undefined
|
||||
readonly done: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Pages forward through a cursor connection, emitting one connection per
|
||||
* page.
|
||||
*
|
||||
* **Details**
|
||||
*
|
||||
* The cursor variable is always `$after`: the operation's variables must
|
||||
* accept `after?: string | null`, which is what a nullable `$after: String`
|
||||
* becomes. The first page is fetched without `after`; every later page sends
|
||||
* the previous page's `endCursor`. Pages are fetched one at a time and only
|
||||
* when pulled, so `Stream.take` stops further requests. Each page is a normal
|
||||
* method call, so middleware runs on every page.
|
||||
*
|
||||
* The stream ends after a page whose `hasNextPage` is `false`. A `null`
|
||||
* connection on the first page gives an empty stream; on a later page it
|
||||
* fails with a `PaginationError`, as does `hasNextPage: true` with a `null`
|
||||
* or unchanged `endCursor`.
|
||||
*
|
||||
* Root fields that come with every page, such as GitHub's `rateLimit`, are for
|
||||
* middleware to read from the raw `ExecutionResult`.
|
||||
*
|
||||
* **Example** (Paging issues, two per page)
|
||||
*
|
||||
* ```ts import.meta.vitest
|
||||
* import { Effect, Layer, Schema, Stream } from "effect"
|
||||
* import { GraphQL, GraphQLClient, GraphQLGroup, GraphQLProtocol } from "effect/graphql"
|
||||
*
|
||||
* const RepoIssues = GraphQL.query("RepoIssues", {
|
||||
* document: "query RepoIssues($owner:String!,$name:String!,$after:String){repository(owner:$owner,name:$name){issues(first:2,after:$after){pageInfo{hasNextPage endCursor}nodes{number}}}}",
|
||||
* variables: { owner: Schema.String, name: Schema.String, after: Schema.optional(Schema.NullOr(Schema.String)) },
|
||||
* result: Schema.Struct({
|
||||
* repository: Schema.NullOr(Schema.Struct({
|
||||
* issues: Schema.Struct({
|
||||
* pageInfo: Schema.Struct({ hasNextPage: Schema.Boolean, endCursor: Schema.NullOr(Schema.String) }),
|
||||
* nodes: Schema.NullOr(Schema.Array(Schema.NullOr(Schema.Struct({ number: Schema.Int }))))
|
||||
* })
|
||||
* }))
|
||||
* })
|
||||
* })
|
||||
*
|
||||
* // A scripted server with two pages
|
||||
* const Scripted = Layer.succeed(GraphQLProtocol.GraphQLProtocol, {
|
||||
* execute: (request) => {
|
||||
* const after = (request.variables as { after?: string }).after
|
||||
* const page = after === undefined
|
||||
* ? { pageInfo: { hasNextPage: true, endCursor: "c1" }, nodes: [{ number: 1 }, { number: 2 }] }
|
||||
* : { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [{ number: 3 }] }
|
||||
* return Effect.succeed({ data: { repository: { issues: page } } })
|
||||
* },
|
||||
* subscribe: () => Stream.empty
|
||||
* })
|
||||
*
|
||||
* const program = Effect.gen(function*() {
|
||||
* const client = yield* GraphQLClient.make(GraphQLGroup.make(RepoIssues))
|
||||
* const pages = GraphQLClient.pages(client.RepoIssues, {
|
||||
* variables: { owner: "Effect-TS", name: "effect" },
|
||||
* connection: (result) => result.repository?.issues
|
||||
* })
|
||||
* return yield* Stream.runCollect(Stream.map(pages, (page) => page.pageInfo.endCursor))
|
||||
* })
|
||||
*
|
||||
* await Effect.runPromise(program.pipe(Effect.provide(Scripted))) // => ["c1", null]
|
||||
* ```
|
||||
*
|
||||
* @stability experimental
|
||||
* @category paging
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export const pages = <Op extends GraphQL.Any, C extends Connection, R2 = never>(
|
||||
method: OperationMethod<Op>,
|
||||
options: PagingOptions<Op, C, R2>
|
||||
): Stream.Stream<C, GraphQL.Error<Op>, Exclude<GraphQL.Services<Op>, R2>> => {
|
||||
const call = method as unknown as (variables: unknown, options?: CallOptions<any>) => Effect.Effect<any, any, any>
|
||||
const paginationError = (description: string, cursor: string | null) =>
|
||||
Effect.fail(
|
||||
new GraphQLClientError({
|
||||
operation: method.operation.name,
|
||||
reason: new PaginationError({ description, cursor })
|
||||
})
|
||||
)
|
||||
const next = (connection: C, state: PagingState): readonly [C, PagingState] => [connection, state]
|
||||
return Stream.unfold<PagingState, C, GraphQL.Error<Op>, any>({ after: undefined, done: false }, (state) => {
|
||||
if (state.done) return Effect.succeed(undefined)
|
||||
const variables = state.after === undefined ? options.variables : { ...options.variables, after: state.after }
|
||||
return Effect.flatMap(call(variables, options.options), (result) => {
|
||||
const connection = options.connection(result)
|
||||
const cursor = state.after ?? null
|
||||
if (connection === null || connection === undefined) {
|
||||
return state.after === undefined
|
||||
? Effect.succeed(undefined)
|
||||
: paginationError("The connection was null on a page after the first", cursor)
|
||||
}
|
||||
const { endCursor, hasNextPage } = connection.pageInfo
|
||||
if (!hasNextPage) {
|
||||
return Effect.succeed(next(connection, { after: state.after, done: true }))
|
||||
}
|
||||
if (endCursor === null) {
|
||||
return paginationError("hasNextPage is true but endCursor is null", cursor)
|
||||
}
|
||||
if (endCursor === state.after) {
|
||||
return paginationError(`endCursor "${endCursor}" did not advance`, cursor)
|
||||
}
|
||||
return Effect.succeed(next(connection, { after: endCursor, done: false }))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Like {@link pages}, but emits each entry of the connection's `nodes` with
|
||||
* its decoded type. `null` entries are kept, because `nodes` on a nullable
|
||||
* list type such as GitHub's `[Issue]` can contain them; pipe through
|
||||
* `Stream.filter(Predicate.isNotNull)` to drop them. A connection that only
|
||||
* selects `edges` is paged with {@link pages} plus `Stream.flatMap`.
|
||||
*
|
||||
* **Example** (Flattening issue numbers across pages)
|
||||
*
|
||||
* ```ts import.meta.vitest
|
||||
* import { Effect, Layer, Schema, Stream } from "effect"
|
||||
* import { GraphQL, GraphQLClient, GraphQLGroup, GraphQLProtocol } from "effect/graphql"
|
||||
*
|
||||
* const RepoIssues = GraphQL.query("RepoIssues", {
|
||||
* document: "query RepoIssues($owner:String!,$name:String!,$after:String){repository(owner:$owner,name:$name){issues(first:2,after:$after){pageInfo{hasNextPage endCursor}nodes{number}}}}",
|
||||
* variables: { owner: Schema.String, name: Schema.String, after: Schema.optional(Schema.NullOr(Schema.String)) },
|
||||
* result: Schema.Struct({
|
||||
* repository: Schema.NullOr(Schema.Struct({
|
||||
* issues: Schema.Struct({
|
||||
* pageInfo: Schema.Struct({ hasNextPage: Schema.Boolean, endCursor: Schema.NullOr(Schema.String) }),
|
||||
* nodes: Schema.NullOr(Schema.Array(Schema.NullOr(Schema.Struct({ number: Schema.Int }))))
|
||||
* })
|
||||
* }))
|
||||
* })
|
||||
* })
|
||||
*
|
||||
* const Scripted = Layer.succeed(GraphQLProtocol.GraphQLProtocol, {
|
||||
* execute: (request) => {
|
||||
* const after = (request.variables as { after?: string }).after
|
||||
* const page = after === undefined
|
||||
* ? { pageInfo: { hasNextPage: true, endCursor: "c1" }, nodes: [{ number: 1 }, null] }
|
||||
* : { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [{ number: 3 }] }
|
||||
* return Effect.succeed({ data: { repository: { issues: page } } })
|
||||
* },
|
||||
* subscribe: () => Stream.empty
|
||||
* })
|
||||
*
|
||||
* const program = Effect.gen(function*() {
|
||||
* const client = yield* GraphQLClient.make(GraphQLGroup.make(RepoIssues))
|
||||
* const items = GraphQLClient.items(client.RepoIssues, {
|
||||
* variables: { owner: "Effect-TS", name: "effect" },
|
||||
* connection: (result) => result.repository?.issues
|
||||
* })
|
||||
* return yield* Stream.runCollect(Stream.map(items, (issue) => issue?.number ?? null))
|
||||
* })
|
||||
*
|
||||
* await Effect.runPromise(program.pipe(Effect.provide(Scripted))) // => [1, null, 3]
|
||||
* ```
|
||||
*
|
||||
* @stability experimental
|
||||
* @category paging
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export const items = <Op extends GraphQL.Any, Node, R2 = never>(
|
||||
method: OperationMethod<Op>,
|
||||
options: PagingOptions<Op, NodesConnection<Node>, R2>
|
||||
): Stream.Stream<Node, GraphQL.Error<Op>, Exclude<GraphQL.Services<Op>, R2>> =>
|
||||
Stream.flatMap(pages(method, options), (connection) => Stream.fromArray(connection.nodes ?? []))
|
||||
@@ -0,0 +1,419 @@
|
||||
/**
|
||||
* Errors raised by the experimental `effect/graphql` client.
|
||||
*
|
||||
* **Details**
|
||||
*
|
||||
* Every failure a client method can produce is one `GraphQLClientError` that
|
||||
* names the operation and carries a `reason`. The reasons are
|
||||
* `Schema.TaggedError` classes, so a `GraphQLClientError` encodes and decodes
|
||||
* through its Schema and can cross process boundaries.
|
||||
*
|
||||
* @stability experimental
|
||||
* @since 4.0.0
|
||||
*/
|
||||
import * as Duration from "../Duration.ts"
|
||||
import type * as HttpClientError from "../http/HttpClientError.ts"
|
||||
import { hasProperty } from "../Predicate.ts"
|
||||
import * as Schema from "../Schema.ts"
|
||||
|
||||
const TypeId = "~effect/graphql/GraphQLClientError"
|
||||
|
||||
/**
|
||||
* One entry of a GraphQL response's `errors` array, as described by the
|
||||
* GraphQL specification.
|
||||
*
|
||||
* **Details**
|
||||
*
|
||||
* `path[0]` is the response key the error belongs to, which is the alias when
|
||||
* the document used one, so callers can match an error to the field it hit.
|
||||
*
|
||||
* **Example** (Finding which alias an error belongs to)
|
||||
*
|
||||
* ```ts import.meta.vitest
|
||||
* import { Schema } from "effect"
|
||||
* import { GraphQLClientError } from "effect/graphql"
|
||||
*
|
||||
* const error = Schema.decodeUnknownSync(GraphQLClientError.GraphQLError)({
|
||||
* message: "Could not resolve to a Repository",
|
||||
* path: ["missing", "issues"],
|
||||
* extensions: { type: "NOT_FOUND" }
|
||||
* })
|
||||
*
|
||||
* error.path?.[0] // => "missing"
|
||||
* ```
|
||||
*
|
||||
* @stability experimental
|
||||
* @category schemas
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export const GraphQLError = Schema.Struct({
|
||||
message: Schema.String,
|
||||
locations: Schema.optional(Schema.Array(Schema.Struct({ line: Schema.Number, column: Schema.Number }))),
|
||||
path: Schema.optional(Schema.Array(Schema.Union([Schema.String, Schema.Number]))),
|
||||
extensions: Schema.optional(Schema.Record(Schema.String, Schema.Json))
|
||||
})
|
||||
|
||||
/**
|
||||
* The decoded type of {@link GraphQLError}.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category models
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export type GraphQLError = typeof GraphQLError.Type
|
||||
|
||||
/**
|
||||
* The server answered with a non-empty `errors` array.
|
||||
*
|
||||
* **Details**
|
||||
*
|
||||
* Any non-empty `errors` fails a query or mutation by default, even when
|
||||
* `data` is present. The reason is ambiguity: a field error nulls the nearest
|
||||
* nullable position, so a `null` caused by an error looks exactly like a
|
||||
* genuine `null`. On GitHub, a `NOT_FOUND` on one alias would otherwise read
|
||||
* as "no such repository". Callers who want the decoded partial `data` pass
|
||||
* `{ partial: true }` to the method and receive `{ data, errors }`.
|
||||
*
|
||||
* `data` is kept raw (not decoded) on the error. To find out which field an
|
||||
* error belongs to, look at `GraphQLError.path[0]`, which is the response key
|
||||
* (the alias when one was used).
|
||||
*
|
||||
* A 4xx HTTP response that carries a GraphQL body is also reported as a
|
||||
* `ResponseError`, never as a `TransportError`.
|
||||
*
|
||||
* **Example** (Inspecting the errors of a failed call)
|
||||
*
|
||||
* ```ts import.meta.vitest
|
||||
* import { GraphQLClientError } from "effect/graphql"
|
||||
*
|
||||
* const reason = new GraphQLClientError.ResponseError({
|
||||
* errors: [{ message: "Not found", path: ["repository"] }],
|
||||
* data: { repository: null }
|
||||
* })
|
||||
*
|
||||
* reason.isRetryable // => false
|
||||
* reason.errors.map((error) => error.path?.[0]) // => ["repository"]
|
||||
* ```
|
||||
*
|
||||
* @stability experimental
|
||||
* @category errors
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export class ResponseError
|
||||
extends Schema.TaggedError<ResponseError>("effect/graphql/GraphQLClientError/ResponseError")("ResponseError", {
|
||||
errors: Schema.NonEmptyArray(GraphQLError),
|
||||
data: Schema.optional(Schema.Json),
|
||||
extensions: Schema.optional(Schema.Record(Schema.String, Schema.Json))
|
||||
})
|
||||
{
|
||||
/**
|
||||
* A `ResponseError` is never retryable: the server executed the operation
|
||||
* and reported errors for it.
|
||||
*
|
||||
* @since 4.0.0
|
||||
*/
|
||||
get isRetryable(): boolean {
|
||||
return false
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return this.errors.map((error) => error.message).join("; ")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The graphql-ws close codes after which reconnecting cannot help: a bad
|
||||
* request, a failed authentication or authorization, an unsupported
|
||||
* subprotocol, a duplicate subscriber or connection, or too many requests.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category constants
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export const fatalCloseCodes: ReadonlySet<number> = new Set([4400, 4401, 4403, 4406, 4409, 4429])
|
||||
|
||||
/**
|
||||
* Parses a `Retry-After` header value, either a number of seconds or an HTTP
|
||||
* date, into a `Duration` measured from `now` (epoch milliseconds).
|
||||
*/
|
||||
const parseRetryAfter = (value: string | undefined, now: number): Duration.Duration | undefined => {
|
||||
if (value === undefined) return undefined
|
||||
const trimmed = value.trim()
|
||||
if (/^\d+$/.test(trimmed)) {
|
||||
return Duration.seconds(Number(trimmed))
|
||||
}
|
||||
const date = Date.parse(trimmed)
|
||||
if (Number.isNaN(date)) return undefined
|
||||
return Duration.millis(Math.max(0, date - now))
|
||||
}
|
||||
|
||||
/**
|
||||
* The client could not get a GraphQL response from the server: a network
|
||||
* failure, an HTTP response that is not a GraphQL response, or a closed
|
||||
* WebSocket connection.
|
||||
*
|
||||
* **Details**
|
||||
*
|
||||
* - `status` is only set for an HTTP response that is not a GraphQL response.
|
||||
* - `retryAfter` comes from the `Retry-After` header (numeric or HTTP-date
|
||||
* form) and is encoded as milliseconds.
|
||||
* - `closeCode` is set when a WebSocket connection closed.
|
||||
* - `cause` holds the original error, such as the `HttpClientError`. Once
|
||||
* encoded it shrinks to `{ name, message }`, the standard `Schema.Defect`
|
||||
* behaviour.
|
||||
*
|
||||
* **Example** (Retryability of transport failures)
|
||||
*
|
||||
* ```ts import.meta.vitest
|
||||
* import { GraphQLClientError } from "effect/graphql"
|
||||
*
|
||||
* new GraphQLClientError.TransportError({ description: "ECONNREFUSED" }).isRetryable // => true
|
||||
* new GraphQLClientError.TransportError({ description: "503", status: 503 }).isRetryable // => true
|
||||
* new GraphQLClientError.TransportError({ description: "404", status: 404 }).isRetryable // => false
|
||||
* new GraphQLClientError.TransportError({ description: "closed", closeCode: 4401 }).isRetryable // => false
|
||||
* ```
|
||||
*
|
||||
* @stability experimental
|
||||
* @category errors
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export class TransportError
|
||||
extends Schema.TaggedError<TransportError>("effect/graphql/GraphQLClientError/TransportError")("TransportError", {
|
||||
description: Schema.String,
|
||||
status: Schema.optional(Schema.Int),
|
||||
retryAfter: Schema.optional(Schema.DurationFromMillis),
|
||||
closeCode: Schema.optional(Schema.Int),
|
||||
cause: Schema.optional(Schema.Defect())
|
||||
})
|
||||
{
|
||||
/**
|
||||
* `true` for a network failure (no `status`), a `429` or `5xx` status, and
|
||||
* any close code that is not one of the {@link fatalCloseCodes}.
|
||||
*
|
||||
* @since 4.0.0
|
||||
*/
|
||||
get isRetryable(): boolean {
|
||||
if (this.closeCode !== undefined && fatalCloseCodes.has(this.closeCode)) {
|
||||
return false
|
||||
}
|
||||
if (this.status === undefined) {
|
||||
return true
|
||||
}
|
||||
return this.status === 429 || this.status >= 500
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return this.description
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts an `HttpClientError` into a `TransportError`, reading `status` and
|
||||
* `Retry-After` from the response when there is one.
|
||||
*
|
||||
* **Details**
|
||||
*
|
||||
* An HTTP-date `Retry-After` is measured from `options.now` (epoch
|
||||
* milliseconds), which defaults to `Date.now()`. Transports pass the Effect
|
||||
* clock's current time.
|
||||
*
|
||||
* @since 4.0.0
|
||||
*/
|
||||
static fromHttpClientError(
|
||||
error: HttpClientError.HttpClientError,
|
||||
options?: { readonly now?: number | undefined }
|
||||
): TransportError {
|
||||
const response = error.response
|
||||
return new TransportError({
|
||||
description: error.message,
|
||||
status: response?.status,
|
||||
retryAfter: response === undefined
|
||||
? undefined
|
||||
: parseRetryAfter(response.headers["retry-after"], options?.now ?? Date.now()),
|
||||
cause: error
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The variables Schema rejected the input, so nothing was sent.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category errors
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export class EncodeError
|
||||
extends Schema.TaggedError<EncodeError>("effect/graphql/GraphQLClientError/EncodeError")("EncodeError", {
|
||||
description: Schema.String
|
||||
})
|
||||
{
|
||||
/**
|
||||
* An `EncodeError` is never retryable.
|
||||
*
|
||||
* @since 4.0.0
|
||||
*/
|
||||
get isRetryable(): boolean {
|
||||
return false
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return this.description
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The response was not a GraphQL response, or `data` did not match the result
|
||||
* Schema.
|
||||
*
|
||||
* **Details**
|
||||
*
|
||||
* A `data: null` without `errors` is also a `DecodeError`: it breaks the
|
||||
* GraphQL specification but happens in practice, and `ResponseError.errors`
|
||||
* cannot hold an empty array.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category errors
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export class DecodeError
|
||||
extends Schema.TaggedError<DecodeError>("effect/graphql/GraphQLClientError/DecodeError")("DecodeError", {
|
||||
description: Schema.String
|
||||
})
|
||||
{
|
||||
/**
|
||||
* A `DecodeError` is never retryable.
|
||||
*
|
||||
* @since 4.0.0
|
||||
*/
|
||||
get isRetryable(): boolean {
|
||||
return false
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return this.description
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Cursor paging could not continue. Only `GraphQLClient.pages` and
|
||||
* `GraphQLClient.items` raise it, when a connection becomes `null` on a page
|
||||
* after the first, or when `hasNextPage` is `true` but `endCursor` is `null`
|
||||
* or did not advance.
|
||||
*
|
||||
* **Details**
|
||||
*
|
||||
* `cursor` is the last cursor that was sent, `null` on the first page.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category errors
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export class PaginationError
|
||||
extends Schema.TaggedError<PaginationError>("effect/graphql/GraphQLClientError/PaginationError")("PaginationError", {
|
||||
description: Schema.String,
|
||||
cursor: Schema.NullOr(Schema.String)
|
||||
})
|
||||
{
|
||||
/**
|
||||
* A `PaginationError` is never retryable.
|
||||
*
|
||||
* @since 4.0.0
|
||||
*/
|
||||
get isRetryable(): boolean {
|
||||
return false
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return this.description
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The union of every reason a {@link GraphQLClientError} can carry.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category models
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export type Reason = ResponseError | TransportError | EncodeError | DecodeError | PaginationError
|
||||
|
||||
/**
|
||||
* The error every `GraphQLClient` method fails with. It names the operation
|
||||
* and carries one of the five reasons; `cause` is the reason itself.
|
||||
*
|
||||
* **Example** (Retrying only what is retryable)
|
||||
*
|
||||
* ```ts import.meta.vitest
|
||||
* import { Duration, Schema } from "effect"
|
||||
* import { GraphQLClientError } from "effect/graphql"
|
||||
*
|
||||
* const error = new GraphQLClientError.GraphQLClientError({
|
||||
* operation: "Viewer",
|
||||
* reason: new GraphQLClientError.TransportError({
|
||||
* description: "503 Service Unavailable",
|
||||
* status: 503,
|
||||
* retryAfter: Duration.seconds(30)
|
||||
* })
|
||||
* })
|
||||
*
|
||||
* error.isRetryable // => true
|
||||
* error.retryAfter // => Duration.seconds(30)
|
||||
*
|
||||
* // Errors round-trip through their Schema
|
||||
* const encoded = Schema.encodeSync(GraphQLClientError.GraphQLClientError)(error)
|
||||
* Schema.decodeUnknownSync(GraphQLClientError.GraphQLClientError)(encoded).reason._tag // => "TransportError"
|
||||
* ```
|
||||
*
|
||||
* @stability experimental
|
||||
* @category errors
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export class GraphQLClientError extends Schema.TaggedError<GraphQLClientError>(TypeId)("GraphQLClientError", {
|
||||
operation: Schema.String,
|
||||
reason: Schema.Union([ResponseError, TransportError, EncodeError, DecodeError, PaginationError])
|
||||
}) {
|
||||
/**
|
||||
* Marks this value as a GraphQL client error for runtime guards.
|
||||
*
|
||||
* @stability experimental
|
||||
* @since 4.0.0
|
||||
*/
|
||||
readonly [TypeId] = TypeId
|
||||
|
||||
/**
|
||||
* The reason, exposed as the error's cause.
|
||||
*
|
||||
* @since 4.0.0
|
||||
*/
|
||||
override readonly cause = this.reason
|
||||
|
||||
/**
|
||||
* Delegates to the reason's `isRetryable`.
|
||||
*
|
||||
* @since 4.0.0
|
||||
*/
|
||||
get isRetryable(): boolean {
|
||||
return this.reason.isRetryable
|
||||
}
|
||||
|
||||
/**
|
||||
* The `Retry-After` hint of a `TransportError` reason, if any.
|
||||
*
|
||||
* @since 4.0.0
|
||||
*/
|
||||
get retryAfter(): Duration.Duration | undefined {
|
||||
return this.reason._tag === "TransportError" ? this.reason.retryAfter : undefined
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `${this.operation}: ${this.reason._tag}: ${this.reason.message}`
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests whether a value is a {@link GraphQLClientError}.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category guards
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export const isGraphQLClientError = (u: unknown): u is GraphQLClientError => hasProperty(u, TypeId)
|
||||
@@ -0,0 +1,172 @@
|
||||
/**
|
||||
* Groups of GraphQL operations.
|
||||
*
|
||||
* **Details**
|
||||
*
|
||||
* `@effect/graphql-generator` emits one group per `.graphql` file. Groups are
|
||||
* merged to build one client, and middleware attached to a group runs outside
|
||||
* the middleware of every operation in it.
|
||||
*
|
||||
* @stability experimental
|
||||
* @since 4.0.0
|
||||
*/
|
||||
import { type Pipeable, pipeArguments } from "../Pipeable.ts"
|
||||
import { hasProperty } from "../Predicate.ts"
|
||||
import type * as GraphQL from "./GraphQL.ts"
|
||||
import type * as GraphQLMiddleware from "./GraphQLMiddleware.ts"
|
||||
|
||||
const TypeId = "~effect/graphql/GraphQLGroup"
|
||||
|
||||
/**
|
||||
* A set of operations plus the middleware attached at the group level.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category models
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export interface GraphQLGroup<out Ops extends GraphQL.Any> extends Pipeable {
|
||||
readonly [TypeId]: typeof TypeId
|
||||
readonly operations: ReadonlyArray<Ops>
|
||||
/** Middleware attached to the group, outermost first. */
|
||||
readonly middlewares: ReadonlyArray<GraphQLMiddleware.AnyService>
|
||||
/**
|
||||
* Attaches a middleware to every operation in the group. Group middleware
|
||||
* runs outside operation middleware; several group middleware run in the
|
||||
* order attached.
|
||||
*/
|
||||
middleware<M extends GraphQLMiddleware.AnyService>(middleware: M): GraphQLGroup<GraphQL.AddMiddleware<Ops, M>>
|
||||
}
|
||||
|
||||
/**
|
||||
* Any group, with its operations erased.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category utility types
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export type Any = GraphQLGroup<GraphQL.Any>
|
||||
|
||||
/**
|
||||
* Extracts the union of operations in a group.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category utility types
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export type Operations<G> = G extends GraphQLGroup<infer Ops> ? Ops : never
|
||||
|
||||
/**
|
||||
* Tests whether a value is a {@link GraphQLGroup}.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category guards
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export const isGraphQLGroup = (u: unknown): u is Any => hasProperty(u, TypeId)
|
||||
|
||||
const Proto = {
|
||||
[TypeId]: TypeId,
|
||||
pipe() {
|
||||
return pipeArguments(this, arguments)
|
||||
},
|
||||
middleware(this: Any, middleware: GraphQLMiddleware.AnyService) {
|
||||
return makeProto(this.operations, [...this.middlewares, middleware])
|
||||
}
|
||||
}
|
||||
|
||||
const makeProto = (
|
||||
operations: ReadonlyArray<GraphQL.Any>,
|
||||
middlewares: ReadonlyArray<GraphQLMiddleware.AnyService>
|
||||
): Any => {
|
||||
const byName = new Map<string, GraphQL.Any>()
|
||||
for (const operation of operations) {
|
||||
const existing = byName.get(operation.name)
|
||||
if (existing !== undefined && existing !== operation) {
|
||||
throw new Error(`GraphQLGroup: duplicate operation name "${operation.name}"`)
|
||||
}
|
||||
byName.set(operation.name, operation)
|
||||
}
|
||||
return Object.assign(Object.create(Proto), { operations: Array.from(byName.values()), middlewares })
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a group from operations. Operation names must be unique within a
|
||||
* group, because they become the client's method names.
|
||||
*
|
||||
* **Example** (One group per `.graphql` file)
|
||||
*
|
||||
* ```ts import.meta.vitest
|
||||
* import { Schema } from "effect"
|
||||
* import { GraphQL, GraphQLGroup } from "effect/graphql"
|
||||
*
|
||||
* const Viewer = GraphQL.query("Viewer", {
|
||||
* document: "query Viewer{viewer{login}}",
|
||||
* result: Schema.Struct({ viewer: Schema.Struct({ login: Schema.String }) })
|
||||
* })
|
||||
*
|
||||
* const ViewerGroup = GraphQLGroup.make(Viewer)
|
||||
*
|
||||
* ViewerGroup.operations.map((op) => op.name) // => ["Viewer"]
|
||||
* ```
|
||||
*
|
||||
* @stability experimental
|
||||
* @category constructors
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export const make = <const Ops extends ReadonlyArray<GraphQL.Any>>(...operations: Ops): GraphQLGroup<Ops[number]> =>
|
||||
makeProto(operations, []) as any
|
||||
|
||||
/**
|
||||
* Merges groups into one. Middleware attached to a source group stays
|
||||
* attached to that group's operations; middleware attached to the merged
|
||||
* group afterwards runs outside all of it.
|
||||
*
|
||||
* **Example** (Auth on one file, logging on everything)
|
||||
*
|
||||
* ```ts import.meta.vitest
|
||||
* import { Schema } from "effect"
|
||||
* import { GraphQL, GraphQLGroup, GraphQLMiddleware } from "effect/graphql"
|
||||
*
|
||||
* class Auth extends GraphQLMiddleware.Service<Auth>()("app/Auth") {}
|
||||
* class Logging extends GraphQLMiddleware.Service<Logging>()("app/Logging") {}
|
||||
*
|
||||
* const Viewer = GraphQL.query("Viewer", {
|
||||
* document: "query Viewer{viewer{login}}",
|
||||
* result: Schema.Struct({ viewer: Schema.Struct({ login: Schema.String }) })
|
||||
* })
|
||||
* const Rate = GraphQL.query("Rate", {
|
||||
* document: "query Rate{rateLimit{remaining}}",
|
||||
* result: Schema.Struct({ rateLimit: Schema.Struct({ remaining: Schema.Int }) })
|
||||
* })
|
||||
*
|
||||
* const all = GraphQLGroup.merge(GraphQLGroup.make(Viewer).middleware(Auth), GraphQLGroup.make(Rate))
|
||||
* .middleware(Logging)
|
||||
*
|
||||
* all.operations.map((op) => op.name) // => ["Viewer", "Rate"]
|
||||
* all.middlewares.map((m) => m.key) // => ["app/Logging"]
|
||||
* all.operations[0].middlewares.map((m) => m.key) // => ["app/Auth"]
|
||||
* ```
|
||||
*
|
||||
* @stability experimental
|
||||
* @category combinators
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export const merge = <const Groups extends ReadonlyArray<Any>>(
|
||||
...groups: Groups
|
||||
): GraphQLGroup<Operations<Groups[number]>> =>
|
||||
makeProto(
|
||||
groups.flatMap((group) =>
|
||||
group.middlewares.length === 0
|
||||
? group.operations
|
||||
: group.operations.map((operation) => withMiddlewares(operation, group.middlewares))
|
||||
),
|
||||
[]
|
||||
) as any
|
||||
|
||||
const withMiddlewares = (
|
||||
operation: GraphQL.Any,
|
||||
outer: ReadonlyArray<GraphQLMiddleware.AnyService>
|
||||
): GraphQL.Any =>
|
||||
Object.assign(Object.create(Object.getPrototypeOf(operation)), operation, {
|
||||
middlewares: [...outer, ...operation.middlewares]
|
||||
})
|
||||
@@ -0,0 +1,266 @@
|
||||
/**
|
||||
* GraphQL-level client middleware.
|
||||
*
|
||||
* **Details**
|
||||
*
|
||||
* A middleware is a `Context.Service` tag whose value is the implementation,
|
||||
* so it is provided with `Layer.succeed` or `Layer.effect` and mocked in tests
|
||||
* like any other service. It wraps every operation it is attached to at the
|
||||
* GraphQL level: it can rewrite the request (headers, extensions, variables)
|
||||
* before it reaches the transport and inspect the raw `ExecutionResult` that
|
||||
* comes back.
|
||||
*
|
||||
* @stability experimental
|
||||
* @since 4.0.0
|
||||
*/
|
||||
import * as Context from "../Context.ts"
|
||||
import * as Effect from "../Effect.ts"
|
||||
import { getStackTraceLimit, setStackTraceLimit } from "../internal/stackTraceLimit.ts"
|
||||
import * as Stream from "../Stream.ts"
|
||||
import type * as Types from "../Types.ts"
|
||||
import type * as GraphQL from "./GraphQL.ts"
|
||||
import type { GraphQLClientError } from "./GraphQLClientError.ts"
|
||||
import type { ExecutionResult, GraphQLRequest } from "./GraphQLProtocol.ts"
|
||||
|
||||
const TypeId = "~effect/graphql/GraphQLMiddleware"
|
||||
|
||||
/**
|
||||
* What a middleware's `execute` member receives: the operation being run, the
|
||||
* request so far, and `next`, which runs the rest of the chain and returns
|
||||
* the raw `ExecutionResult`.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category models
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export interface ExecuteOptions {
|
||||
readonly operation: GraphQL.Any
|
||||
readonly request: GraphQLRequest
|
||||
readonly next: (request: GraphQLRequest) => Effect.Effect<ExecutionResult, GraphQLClientError>
|
||||
}
|
||||
|
||||
/**
|
||||
* What a middleware's `subscribe` member receives. `next` subscribes with the
|
||||
* given request and returns the stream of raw `ExecutionResult` events.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category models
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export interface SubscribeOptions {
|
||||
readonly operation: GraphQL.Any
|
||||
readonly request: GraphQLRequest
|
||||
readonly next: (request: GraphQLRequest) => Stream.Stream<ExecutionResult, GraphQLClientError>
|
||||
}
|
||||
|
||||
/**
|
||||
* A middleware implementation. Both members are required, so a middleware can
|
||||
* never silently skip subscriptions.
|
||||
*
|
||||
* **Details**
|
||||
*
|
||||
* `execute` runs once per query or mutation. `subscribe` runs once per
|
||||
* subscription attempt (the client re-runs the whole chain when it retries a
|
||||
* subscription) and can map or tap the event stream.
|
||||
*
|
||||
* Use {@link mapRequest} when the middleware only needs to transform the
|
||||
* request.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category models
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export interface Implementation<E = never, R = never> {
|
||||
readonly execute: (options: ExecuteOptions) => Effect.Effect<ExecutionResult, GraphQLClientError | E, R>
|
||||
readonly subscribe: (options: SubscribeOptions) => Stream.Stream<ExecutionResult, GraphQLClientError | E, R>
|
||||
}
|
||||
|
||||
/**
|
||||
* The class returned by {@link Service}: a `Context.Service` for an
|
||||
* {@link Implementation}, carrying the declared `error` and `requires` types.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category services
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export interface ServiceClass<Self, Key extends string, E, R> extends Context.Service<Self, Implementation<E, R>> {
|
||||
new(_: never): Context.ServiceClass.Shape<Key, Implementation<E, R>> & {
|
||||
readonly [TypeId]: { readonly error: E; readonly requires: R }
|
||||
}
|
||||
readonly [TypeId]: { readonly error: E; readonly requires: R }
|
||||
readonly key: Key
|
||||
}
|
||||
|
||||
/**
|
||||
* Any middleware service class, with its error and requirement types erased.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category utility types
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export interface AnyService extends Context.Service<any, Implementation<any, any>> {
|
||||
readonly [TypeId]: { readonly error: any; readonly requires: any }
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts the service identifier of a middleware, which is what
|
||||
* `GraphQLClient.make` requires.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category utility types
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export type Identifier<M> = M extends Context.Service<infer I, any> ? I : never
|
||||
|
||||
/**
|
||||
* Extracts the error type a middleware declared.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category utility types
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export type Error<M> = M extends { readonly [TypeId]: { readonly error: infer E } } ? E : never
|
||||
|
||||
/**
|
||||
* Extracts the services a middleware declared it requires per call.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category utility types
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export type Requires<M> = M extends { readonly [TypeId]: { readonly requires: infer R } } ? R : never
|
||||
|
||||
/**
|
||||
* Declares a middleware tag. `requires` are services the implementation needs
|
||||
* on every call, and `error` is what it can fail with; both show up on the
|
||||
* requirements and error type of every client method the middleware is
|
||||
* attached to.
|
||||
*
|
||||
* **Example** (An auth middleware that needs the current user)
|
||||
*
|
||||
* ```ts import.meta.vitest
|
||||
* import { Context, Effect, Layer, Schema, Stream } from "effect"
|
||||
* import { GraphQL, GraphQLClient, GraphQLGroup, GraphQLMiddleware, GraphQLProtocol } from "effect/graphql"
|
||||
*
|
||||
* class CurrentUser extends Context.Service<CurrentUser, { readonly token: string }>()("CurrentUser") {}
|
||||
* class TokenExpired extends Schema.TaggedError<TokenExpired>()("TokenExpired", {}) {}
|
||||
*
|
||||
* class Auth extends GraphQLMiddleware.Service<Auth, {
|
||||
* requires: CurrentUser
|
||||
* error: TokenExpired
|
||||
* }>()("app/Auth") {}
|
||||
*
|
||||
* const AuthLive = Layer.succeed(
|
||||
* Auth,
|
||||
* GraphQLMiddleware.mapRequest(Effect.fnUntraced(function*(request) {
|
||||
* const user = yield* CurrentUser
|
||||
* if (user.token === "") return yield* new TokenExpired()
|
||||
* return { ...request, headers: { ...request.headers, authorization: `Bearer ${user.token}` } }
|
||||
* }))
|
||||
* )
|
||||
*
|
||||
* const Viewer = GraphQL.query("Viewer", {
|
||||
* document: "query Viewer{viewer{login}}",
|
||||
* result: Schema.Struct({ viewer: Schema.Struct({ login: Schema.String }) })
|
||||
* })
|
||||
*
|
||||
* const Scripted = Layer.succeed(GraphQLProtocol.GraphQLProtocol, {
|
||||
* execute: (request) => Effect.succeed({ data: { viewer: { login: request.headers.authorization } } }),
|
||||
* subscribe: () => Stream.empty
|
||||
* })
|
||||
*
|
||||
* const program = Effect.gen(function*() {
|
||||
* const client = yield* GraphQLClient.make(GraphQLGroup.make(Viewer).middleware(Auth))
|
||||
* // CurrentUser is required by the method because Auth is attached
|
||||
* return yield* client.Viewer().pipe(Effect.provideService(CurrentUser, { token: "abc" }))
|
||||
* })
|
||||
*
|
||||
* await Effect.runPromise(program.pipe(Effect.provide([Scripted, AuthLive]))) // => { viewer: { login: "Bearer abc" } }
|
||||
* ```
|
||||
*
|
||||
* @stability experimental
|
||||
* @category constructors
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export const Service = <
|
||||
Self,
|
||||
Config extends {
|
||||
readonly requires?: any
|
||||
readonly error?: any
|
||||
} = {}
|
||||
>(): <const Key extends string>(key: Key) => ServiceClass<
|
||||
Self,
|
||||
Key,
|
||||
Config extends { readonly error: infer E } ? E : never,
|
||||
Config extends { readonly requires: infer R } ? R : never
|
||||
> =>
|
||||
(key: string) => {
|
||||
const limit = getStackTraceLimit()
|
||||
let creationError: globalThis.Error | undefined
|
||||
if (limit !== 0) {
|
||||
setStackTraceLimit(2)
|
||||
creationError = new globalThis.Error()
|
||||
setStackTraceLimit(limit)
|
||||
}
|
||||
|
||||
function ServiceClass() {}
|
||||
const ServiceClass_ = ServiceClass as any as Types.Mutable<AnyService>
|
||||
Object.setPrototypeOf(ServiceClass, Object.getPrototypeOf(Context.Service<Self, any>(key)))
|
||||
ServiceClass.key = key
|
||||
Object.defineProperty(ServiceClass, "stack", {
|
||||
get() {
|
||||
return creationError?.stack
|
||||
}
|
||||
})
|
||||
ServiceClass_[TypeId] = TypeId as any
|
||||
return ServiceClass as any
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a full {@link Implementation} from one request transform, applied to
|
||||
* queries, mutations and subscriptions alike. This is the one-liner for
|
||||
* headers, auth and extensions.
|
||||
*
|
||||
* **Example** (Adding a header to every request)
|
||||
*
|
||||
* ```ts import.meta.vitest
|
||||
* import { Effect, Layer, Schema, Stream } from "effect"
|
||||
* import { GraphQL, GraphQLClient, GraphQLGroup, GraphQLMiddleware, GraphQLProtocol } from "effect/graphql"
|
||||
*
|
||||
* class RequestId extends GraphQLMiddleware.Service<RequestId>()("app/RequestId") {}
|
||||
*
|
||||
* const RequestIdLive = Layer.succeed(
|
||||
* RequestId,
|
||||
* GraphQLMiddleware.mapRequest((request) =>
|
||||
* Effect.succeed({ ...request, headers: { ...request.headers, "x-request-id": "abc" } })
|
||||
* )
|
||||
* )
|
||||
*
|
||||
* const Viewer = GraphQL.query("Viewer", {
|
||||
* document: "query Viewer{viewer{login}}",
|
||||
* result: Schema.Struct({ viewer: Schema.Struct({ login: Schema.String }) })
|
||||
* })
|
||||
*
|
||||
* const Scripted = Layer.succeed(GraphQLProtocol.GraphQLProtocol, {
|
||||
* execute: (request) => Effect.succeed({ data: { viewer: { login: request.headers["x-request-id"] } } }),
|
||||
* subscribe: () => Stream.empty
|
||||
* })
|
||||
*
|
||||
* const program = Effect.gen(function*() {
|
||||
* const client = yield* GraphQLClient.make(GraphQLGroup.make(Viewer).middleware(RequestId))
|
||||
* return yield* client.Viewer()
|
||||
* })
|
||||
*
|
||||
* await Effect.runPromise(program.pipe(Effect.provide([Scripted, RequestIdLive]))) // => { viewer: { login: "abc" } }
|
||||
* ```
|
||||
*
|
||||
* @stability experimental
|
||||
* @category constructors
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export const mapRequest = <E = never, R = never>(
|
||||
f: (request: GraphQLRequest, operation: GraphQL.Any) => Effect.Effect<GraphQLRequest, E, R>
|
||||
): Implementation<E, R> => ({
|
||||
execute: ({ next, operation, request }) => Effect.flatMap(f(request, operation), next),
|
||||
subscribe: ({ next, operation, request }) => Stream.unwrap(Effect.map(f(request, operation), next))
|
||||
})
|
||||
@@ -0,0 +1,241 @@
|
||||
/**
|
||||
* The raw transport under `GraphQLClient`.
|
||||
*
|
||||
* **Details**
|
||||
*
|
||||
* A `GraphQLProtocol` takes an already-encoded request and returns the raw
|
||||
* `ExecutionResult`. It knows nothing about operations, Schemas or middleware;
|
||||
* those live in `GraphQLClient`. `layerHttp` is the HTTP transport for queries
|
||||
* and mutations. The graphql-ws and graphql-sse transports are added
|
||||
* separately.
|
||||
*
|
||||
* @stability experimental
|
||||
* @since 4.0.0
|
||||
*/
|
||||
import * as Clock from "../Clock.ts"
|
||||
import * as Context from "../Context.ts"
|
||||
import * as Effect from "../Effect.ts"
|
||||
import * as HttpClient from "../http/HttpClient.ts"
|
||||
import * as HttpClientError from "../http/HttpClientError.ts"
|
||||
import * as HttpClientRequest from "../http/HttpClientRequest.ts"
|
||||
import * as HttpClientResponse from "../http/HttpClientResponse.ts"
|
||||
import * as Layer from "../Layer.ts"
|
||||
import * as Schema from "../Schema.ts"
|
||||
import * as Stream from "../Stream.ts"
|
||||
import { GraphQLError, TransportError } from "./GraphQLClientError.ts"
|
||||
|
||||
/**
|
||||
* The request a transport sends. Middleware sees and may rewrite it before it
|
||||
* reaches the transport.
|
||||
*
|
||||
* **Details**
|
||||
*
|
||||
* `variables` are already encoded through the operation's variables Schema.
|
||||
* `headers` are applied by the HTTP transport; a WebSocket transport ignores
|
||||
* them because graphql-ws has no per-operation headers.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category models
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export interface GraphQLRequest {
|
||||
readonly query: string
|
||||
readonly operationName: string
|
||||
readonly variables: unknown
|
||||
readonly extensions?: Record<string, unknown> | undefined
|
||||
readonly headers: Readonly<Record<string, string>>
|
||||
}
|
||||
|
||||
/**
|
||||
* The raw result of executing a GraphQL operation, before `data` is decoded
|
||||
* with the result Schema. Middleware receive this from `next`, which is how
|
||||
* they read response `extensions` such as a rate-limit cost.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category schemas
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export const ExecutionResult = Schema.Struct({
|
||||
data: Schema.optional(Schema.Unknown),
|
||||
errors: Schema.optional(Schema.Array(GraphQLError)),
|
||||
extensions: Schema.optional(Schema.Record(Schema.String, Schema.Json))
|
||||
})
|
||||
|
||||
/**
|
||||
* The decoded type of {@link ExecutionResult}.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category models
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export type ExecutionResult = typeof ExecutionResult.Type
|
||||
|
||||
/**
|
||||
* The transport service. `execute` answers a query or mutation with the raw
|
||||
* JSON body, and `subscribe` turns a subscription into a stream of raw events.
|
||||
* Both fail only with `TransportError`; GraphQL `errors` are left in the body
|
||||
* for the client to interpret.
|
||||
*
|
||||
* **Example** (A scripted transport for tests)
|
||||
*
|
||||
* ```ts import.meta.vitest
|
||||
* import { Effect, Layer, Schema, Stream } from "effect"
|
||||
* import { GraphQL, GraphQLClient, GraphQLGroup, GraphQLProtocol } from "effect/graphql"
|
||||
*
|
||||
* const Viewer = GraphQL.query("Viewer", {
|
||||
* document: "query Viewer{viewer{login}}",
|
||||
* result: Schema.Struct({ viewer: Schema.Struct({ login: Schema.String }) })
|
||||
* })
|
||||
*
|
||||
* const Scripted = Layer.succeed(GraphQLProtocol.GraphQLProtocol, {
|
||||
* execute: () => Effect.succeed({ data: { viewer: { login: "tim" } } }),
|
||||
* subscribe: () => Stream.empty
|
||||
* })
|
||||
*
|
||||
* const program = Effect.gen(function*() {
|
||||
* const client = yield* GraphQLClient.make(GraphQLGroup.make(Viewer))
|
||||
* return yield* client.Viewer()
|
||||
* })
|
||||
*
|
||||
* await Effect.runPromise(program.pipe(Effect.provide(Scripted))) // => { viewer: { login: "tim" } }
|
||||
* ```
|
||||
*
|
||||
* @stability experimental
|
||||
* @category services
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export class GraphQLProtocol extends Context.Service<GraphQLProtocol, {
|
||||
readonly execute: (request: GraphQLRequest) => Effect.Effect<unknown, TransportError>
|
||||
readonly subscribe: (request: GraphQLRequest) => Stream.Stream<unknown, TransportError>
|
||||
}>()("effect/graphql/GraphQLProtocol") {}
|
||||
|
||||
const graphqlResponseContentType = "application/graphql-response+json"
|
||||
const jsonContentType = "application/json"
|
||||
|
||||
const isGraphQLBody = (body: unknown): boolean =>
|
||||
typeof body === "object" && body !== null && !Array.isArray(body) && ("data" in body || "errors" in body)
|
||||
|
||||
/**
|
||||
* Builds the HTTP transport as an effect, for composing transports by hand.
|
||||
* Most code uses {@link layerHttp}.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category constructors
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export const makeHttp = (options: {
|
||||
readonly url: string
|
||||
}): Effect.Effect<GraphQLProtocol["Service"], never, HttpClient.HttpClient> =>
|
||||
Effect.map(HttpClient.HttpClient, (client) => {
|
||||
const execute = Effect.fnUntraced(function*(request: GraphQLRequest) {
|
||||
const now = yield* Clock.currentTimeMillis
|
||||
const httpRequest = HttpClientRequest.post(options.url).pipe(
|
||||
HttpClientRequest.setHeaders(request.headers),
|
||||
HttpClientRequest.setHeader("accept", `${graphqlResponseContentType}, ${jsonContentType}`),
|
||||
HttpClientRequest.bodyJsonUnsafe({
|
||||
query: request.query,
|
||||
operationName: request.operationName,
|
||||
variables: request.variables,
|
||||
extensions: request.extensions
|
||||
})
|
||||
)
|
||||
const response = yield* client.execute(httpRequest).pipe(
|
||||
Effect.flatMap((response) => {
|
||||
const contentType = response.headers["content-type"] ?? ""
|
||||
// The GraphQL-over-HTTP media type is authoritative, whatever the status.
|
||||
if (contentType.includes(graphqlResponseContentType)) {
|
||||
return response.json
|
||||
}
|
||||
// Legacy servers answer with application/json; only a body with the
|
||||
// GraphQL keys counts as a GraphQL response.
|
||||
if (contentType.includes(jsonContentType)) {
|
||||
return Effect.flatMap(response.json, (body) =>
|
||||
isGraphQLBody(body)
|
||||
? Effect.succeed(body)
|
||||
: Effect.as(HttpClientResponse.filterStatusOk(response), body))
|
||||
}
|
||||
return Effect.flatMap(
|
||||
HttpClientResponse.filterStatusOk(response),
|
||||
() =>
|
||||
Effect.fail(
|
||||
new TransportError({
|
||||
description: `Expected a GraphQL response, received ${
|
||||
contentType === "" ? "no Content-Type" : `Content-Type ${contentType}`
|
||||
}`,
|
||||
status: response.status
|
||||
})
|
||||
)
|
||||
)
|
||||
}),
|
||||
Effect.catch((error) =>
|
||||
Effect.fail(
|
||||
HttpClientError.isHttpClientError(error) ? TransportError.fromHttpClientError(error, { now }) : error
|
||||
)
|
||||
)
|
||||
)
|
||||
return response
|
||||
})
|
||||
return GraphQLProtocol.of({
|
||||
execute,
|
||||
subscribe: () =>
|
||||
Stream.die(
|
||||
"GraphQLProtocol.layerHttp does not support subscriptions yet; the graphql-sse and graphql-ws transports are a separate slice"
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
* The HTTP transport: queries and mutations are sent as `POST` with a JSON
|
||||
* body to `url`, using the `HttpClient` in context.
|
||||
*
|
||||
* **Details**
|
||||
*
|
||||
* A response is a GraphQL response when its `Content-Type` is
|
||||
* `application/graphql-response+json`, whatever the status, or when it is
|
||||
* `application/json` and the body has a `data` or `errors` key. Anything else
|
||||
* is a `TransportError` with the response `status`, and a `Retry-After`
|
||||
* header (numeric or HTTP-date) becomes `retryAfter`.
|
||||
*
|
||||
* **Example** (Building a client over HTTP)
|
||||
*
|
||||
* ```ts import.meta.vitest
|
||||
* import { Effect, Layer, Schema } from "effect"
|
||||
* import { GraphQL, GraphQLClient, GraphQLGroup, GraphQLProtocol } from "effect/graphql"
|
||||
* import { HttpClient, HttpClientResponse } from "effect/http"
|
||||
*
|
||||
* const Viewer = GraphQL.query("Viewer", {
|
||||
* document: "query Viewer{viewer{login}}",
|
||||
* result: Schema.Struct({ viewer: Schema.Struct({ login: Schema.String }) })
|
||||
* })
|
||||
*
|
||||
* // A stand-in for a real HttpClient layer such as FetchHttpClient.layer
|
||||
* const FakeServer = Layer.succeed(
|
||||
* HttpClient.HttpClient,
|
||||
* HttpClient.make((request) =>
|
||||
* Effect.succeed(HttpClientResponse.fromWeb(
|
||||
* request,
|
||||
* new Response(JSON.stringify({ data: { viewer: { login: "tim" } } }), {
|
||||
* headers: { "content-type": "application/graphql-response+json" }
|
||||
* })
|
||||
* ))
|
||||
* )
|
||||
* )
|
||||
*
|
||||
* const program = Effect.gen(function*() {
|
||||
* const client = yield* GraphQLClient.make(GraphQLGroup.make(Viewer))
|
||||
* return yield* client.Viewer()
|
||||
* }).pipe(
|
||||
* Effect.provide(GraphQLProtocol.layerHttp({ url: "https://api.github.com/graphql" })),
|
||||
* Effect.provide(FakeServer)
|
||||
* )
|
||||
*
|
||||
* await Effect.runPromise(program) // => { viewer: { login: "tim" } }
|
||||
* ```
|
||||
*
|
||||
* @stability experimental
|
||||
* @category layers
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export const layerHttp = (options: {
|
||||
readonly url: string
|
||||
}): Layer.Layer<GraphQLProtocol, never, HttpClient.HttpClient> => Layer.effect(GraphQLProtocol, makeHttp(options))
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* @stability experimental
|
||||
* @since 4.0.0
|
||||
*/
|
||||
|
||||
// @barrel: Auto-generated exports. Do not edit manually.
|
||||
|
||||
/**
|
||||
* @stability experimental
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export * as GraphQL from "./GraphQL.ts"
|
||||
|
||||
/**
|
||||
* @stability experimental
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export * as GraphQLClient from "./GraphQLClient.ts"
|
||||
|
||||
/**
|
||||
* @stability experimental
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export * as GraphQLClientError from "./GraphQLClientError.ts"
|
||||
|
||||
/**
|
||||
* @stability experimental
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export * as GraphQLGroup from "./GraphQLGroup.ts"
|
||||
|
||||
/**
|
||||
* @stability experimental
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export * as GraphQLMiddleware from "./GraphQLMiddleware.ts"
|
||||
|
||||
/**
|
||||
* @stability experimental
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export * as GraphQLProtocol from "./GraphQLProtocol.ts"
|
||||
@@ -26,6 +26,7 @@
|
||||
// that would otherwise be considered cyclic dependencies (e.g. loading `@effect/sql-sqlite-node` in the test
|
||||
// suite of `@effect/platform-node` which itself depends on `@effect/platform-node`).
|
||||
"effect": ["./packages/effect/src/index.ts"],
|
||||
"effect/graphql": ["./packages/effect/src/graphql/index.ts"],
|
||||
"effect/schema": ["./packages/effect/src/schema/index.ts"],
|
||||
"effect/*": ["./packages/effect/src/*.ts"],
|
||||
"@effect/ai-anthropic": ["./packages/ai/anthropic/src/index.ts"],
|
||||
|
||||
Reference in New Issue
Block a user