effect 4.0.2 → 4.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +24 -0
- package/CLAUDE.md +24 -0
- package/ai-docs/package.json +2 -2
- package/ai-docs/src/52_graphql/10_basics.ts +111 -0
- package/ai-docs/src/52_graphql/20_testing.ts +45 -0
- package/ai-docs/src/52_graphql/30_batching.ts +116 -0
- package/ai-docs/src/52_graphql/40_aliased-batching.ts +122 -0
- package/ai-docs/src/52_graphql/50_errors-and-retries.ts +74 -0
- package/ai-docs/src/52_graphql/index.md +6 -0
- package/dist/Context.d.ts.map +1 -1
- package/dist/Context.js +12 -3
- package/dist/Context.js.map +1 -1
- package/dist/Crypto.d.ts +33 -5
- package/dist/Crypto.d.ts.map +1 -1
- package/dist/Crypto.js +8 -2
- package/dist/Crypto.js.map +1 -1
- package/dist/DateTime.d.ts +9 -6
- package/dist/DateTime.d.ts.map +1 -1
- package/dist/DateTime.js +9 -6
- package/dist/DateTime.js.map +1 -1
- package/dist/Duration.d.ts +6 -6
- package/dist/Duration.d.ts.map +1 -1
- package/dist/Duration.js +27 -8
- package/dist/Duration.js.map +1 -1
- package/dist/FileSystem.d.ts +44 -2
- package/dist/FileSystem.d.ts.map +1 -1
- package/dist/FileSystem.js.map +1 -1
- package/dist/RequestResolver.d.ts.map +1 -1
- package/dist/RequestResolver.js +4 -10
- package/dist/RequestResolver.js.map +1 -1
- package/dist/Scheduler.d.ts +9 -0
- package/dist/Scheduler.d.ts.map +1 -1
- package/dist/Scheduler.js +9 -0
- package/dist/Scheduler.js.map +1 -1
- package/dist/Schema.d.ts +481 -1
- package/dist/Schema.d.ts.map +1 -1
- package/dist/Schema.js +362 -4
- package/dist/Schema.js.map +1 -1
- package/dist/SchemaGetter.d.ts +4 -0
- package/dist/SchemaGetter.d.ts.map +1 -1
- package/dist/SchemaGetter.js +52 -33
- package/dist/SchemaGetter.js.map +1 -1
- package/dist/Sink.d.ts.map +1 -1
- package/dist/Sink.js +38 -17
- package/dist/Sink.js.map +1 -1
- package/dist/Stdio.d.ts +7 -1
- package/dist/Stdio.d.ts.map +1 -1
- package/dist/Stdio.js +1 -0
- package/dist/Stdio.js.map +1 -1
- package/dist/Stream.d.ts +22 -11
- package/dist/Stream.d.ts.map +1 -1
- package/dist/Stream.js +21 -6
- package/dist/Stream.js.map +1 -1
- package/dist/Utils.js +8 -3
- package/dist/Utils.js.map +1 -1
- package/dist/ai/AnthropicStructuredOutput.js +0 -2
- package/dist/ai/AnthropicStructuredOutput.js.map +1 -1
- package/dist/ai/Chat.d.ts +2 -2
- package/dist/ai/Chat.d.ts.map +1 -1
- package/dist/ai/LanguageModel.d.ts +38 -7
- package/dist/ai/LanguageModel.d.ts.map +1 -1
- package/dist/ai/LanguageModel.js +25 -7
- package/dist/ai/LanguageModel.js.map +1 -1
- package/dist/ai/McpServer.d.ts +61 -0
- package/dist/ai/McpServer.d.ts.map +1 -1
- package/dist/ai/McpServer.js +196 -44
- package/dist/ai/McpServer.js.map +1 -1
- package/dist/ai/Prompt.d.ts.map +1 -1
- package/dist/ai/Prompt.js +28 -5
- package/dist/ai/Prompt.js.map +1 -1
- package/dist/ai/Response.d.ts +4 -3
- package/dist/ai/Response.d.ts.map +1 -1
- package/dist/ai/Response.js.map +1 -1
- package/dist/ai/internal/mcpProtocol/v2026_07_28.js +5 -0
- package/dist/ai/internal/mcpProtocol/v2026_07_28.js.map +1 -1
- package/dist/ai/internal/mcpProtocol.js.map +1 -1
- package/dist/ai/internal/mcpRuntime.js +1 -0
- package/dist/ai/internal/mcpRuntime.js.map +1 -1
- package/dist/cli/CliOutput.d.ts +27 -0
- package/dist/cli/CliOutput.d.ts.map +1 -1
- package/dist/cli/CliOutput.js +33 -10
- package/dist/cli/CliOutput.js.map +1 -1
- package/dist/cli/Command.d.ts.map +1 -1
- package/dist/cli/Command.js +6 -3
- package/dist/cli/Command.js.map +1 -1
- package/dist/cli/Completions.d.ts +3 -3
- package/dist/cli/Completions.d.ts.map +1 -1
- package/dist/cli/Completions.js +8 -5
- package/dist/cli/Completions.js.map +1 -1
- package/dist/cli/GlobalFlag.d.ts +5 -4
- package/dist/cli/GlobalFlag.d.ts.map +1 -1
- package/dist/cli/GlobalFlag.js +3 -3
- package/dist/cli/GlobalFlag.js.map +1 -1
- package/dist/cli/Prompt.d.ts +17 -1
- package/dist/cli/Prompt.d.ts.map +1 -1
- package/dist/cli/Prompt.js +119 -114
- package/dist/cli/Prompt.js.map +1 -1
- package/dist/cli/internal/ansi.d.ts +0 -1
- package/dist/cli/internal/ansi.d.ts.map +1 -1
- package/dist/cli/internal/ansi.js +20 -3
- package/dist/cli/internal/ansi.js.map +1 -1
- package/dist/cli/internal/completions/powershell.d.ts +2 -0
- package/dist/cli/internal/completions/powershell.d.ts.map +1 -0
- package/dist/cli/internal/completions/powershell.js +273 -0
- package/dist/cli/internal/completions/powershell.js.map +1 -0
- package/dist/cli/internal/completions/zsh.js +3 -2
- package/dist/cli/internal/completions/zsh.js.map +1 -1
- package/dist/cli/internal/wizard.d.ts +3 -3
- package/dist/cli/internal/wizard.d.ts.map +1 -1
- package/dist/cli/internal/wizard.js +21 -18
- package/dist/cli/internal/wizard.js.map +1 -1
- package/dist/cluster/ClusterSchema.d.ts +28 -0
- package/dist/cluster/ClusterSchema.d.ts.map +1 -1
- package/dist/cluster/ClusterSchema.js +30 -0
- package/dist/cluster/ClusterSchema.js.map +1 -1
- package/dist/cluster/ClusterWorkflowEngine.d.ts.map +1 -1
- package/dist/cluster/ClusterWorkflowEngine.js +56 -26
- package/dist/cluster/ClusterWorkflowEngine.js.map +1 -1
- package/dist/cluster/MessageStorage.d.ts +18 -3
- package/dist/cluster/MessageStorage.d.ts.map +1 -1
- package/dist/cluster/MessageStorage.js +31 -11
- package/dist/cluster/MessageStorage.js.map +1 -1
- package/dist/cluster/Runners.d.ts.map +1 -1
- package/dist/cluster/Runners.js +8 -2
- package/dist/cluster/Runners.js.map +1 -1
- package/dist/cluster/Sharding.d.ts.map +1 -1
- package/dist/cluster/Sharding.js +187 -66
- package/dist/cluster/Sharding.js.map +1 -1
- package/dist/cluster/SqlMessageStorage.d.ts +59 -19
- package/dist/cluster/SqlMessageStorage.d.ts.map +1 -1
- package/dist/cluster/SqlMessageStorage.js +84 -55
- package/dist/cluster/SqlMessageStorage.js.map +1 -1
- package/dist/cluster/SqlRunnerStorage.d.ts +68 -19
- package/dist/cluster/SqlRunnerStorage.d.ts.map +1 -1
- package/dist/cluster/SqlRunnerStorage.js +191 -113
- package/dist/cluster/SqlRunnerStorage.js.map +1 -1
- package/dist/cluster/internal/entityManager.js +104 -37
- package/dist/cluster/internal/entityManager.js.map +1 -1
- package/dist/encoding/Sse.d.ts +6 -0
- package/dist/encoding/Sse.d.ts.map +1 -1
- package/dist/encoding/Sse.js +62 -70
- package/dist/encoding/Sse.js.map +1 -1
- package/dist/graphql/GraphQL.d.ts +349 -0
- package/dist/graphql/GraphQL.d.ts.map +1 -0
- package/dist/graphql/GraphQL.js +207 -0
- package/dist/graphql/GraphQL.js.map +1 -0
- package/dist/graphql/GraphQLClient.d.ts +562 -0
- package/dist/graphql/GraphQLClient.d.ts.map +1 -0
- package/dist/graphql/GraphQLClient.js +498 -0
- package/dist/graphql/GraphQLClient.js.map +1 -0
- package/dist/graphql/GraphQLClientError.d.ts +445 -0
- package/dist/graphql/GraphQLClientError.d.ts.map +1 -0
- package/dist/graphql/GraphQLClientError.js +479 -0
- package/dist/graphql/GraphQLClientError.js.map +1 -0
- package/dist/graphql/GraphQLGroup.d.ts +118 -0
- package/dist/graphql/GraphQLGroup.d.ts.map +1 -0
- package/dist/graphql/GraphQLGroup.js +109 -0
- package/dist/graphql/GraphQLGroup.js.map +1 -0
- package/dist/graphql/GraphQLMiddleware.d.ts +249 -0
- package/dist/graphql/GraphQLMiddleware.d.ts.map +1 -0
- package/dist/graphql/GraphQLMiddleware.js +130 -0
- package/dist/graphql/GraphQLMiddleware.js.map +1 -0
- package/dist/graphql/GraphQLProtocol.d.ts +731 -0
- package/dist/graphql/GraphQLProtocol.d.ts.map +1 -0
- package/dist/graphql/GraphQLProtocol.js +719 -0
- package/dist/graphql/GraphQLProtocol.js.map +1 -0
- package/dist/graphql/GraphQLResolver.d.ts +453 -0
- package/dist/graphql/GraphQLResolver.d.ts.map +1 -0
- package/dist/graphql/GraphQLResolver.js +552 -0
- package/dist/graphql/GraphQLResolver.js.map +1 -0
- package/dist/graphql/index.d.ts +40 -0
- package/dist/graphql/index.d.ts.map +1 -0
- package/dist/graphql/index.js +41 -0
- package/dist/graphql/index.js.map +1 -0
- package/dist/http/FindMyWay/internal/router.js +3 -6
- package/dist/http/FindMyWay/internal/router.js.map +1 -1
- package/dist/http/HttpClient.d.ts +21 -0
- package/dist/http/HttpClient.d.ts.map +1 -1
- package/dist/http/HttpClient.js +63 -12
- package/dist/http/HttpClient.js.map +1 -1
- package/dist/http/HttpEffect.d.ts.map +1 -1
- package/dist/http/HttpEffect.js +14 -7
- package/dist/http/HttpEffect.js.map +1 -1
- package/dist/http/HttpMiddleware.d.ts.map +1 -1
- package/dist/http/HttpMiddleware.js +31 -32
- package/dist/http/HttpMiddleware.js.map +1 -1
- package/dist/http/HttpRouter.d.ts +35 -0
- package/dist/http/HttpRouter.d.ts.map +1 -1
- package/dist/http/HttpRouter.js +35 -0
- package/dist/http/HttpRouter.js.map +1 -1
- package/dist/http/HttpServerResponse.d.ts +8 -6
- package/dist/http/HttpServerResponse.d.ts.map +1 -1
- package/dist/http/HttpServerResponse.js +27 -16
- package/dist/http/HttpServerResponse.js.map +1 -1
- package/dist/http/HttpTraceContext.d.ts.map +1 -1
- package/dist/http/HttpTraceContext.js +4 -2
- package/dist/http/HttpTraceContext.js.map +1 -1
- package/dist/http/Multipart.d.ts.map +1 -1
- package/dist/http/Multipart.js +15 -1
- package/dist/http/Multipart.js.map +1 -1
- package/dist/http-api/HttpApiScalar.d.ts +5 -0
- package/dist/http-api/HttpApiScalar.d.ts.map +1 -1
- package/dist/http-api/HttpApiScalar.js.map +1 -1
- package/dist/internal/dateTime.js +40 -35
- package/dist/internal/dateTime.js.map +1 -1
- package/dist/internal/effect.js +19 -9
- package/dist/internal/effect.js.map +1 -1
- package/dist/internal/graphql.d.ts +2 -0
- package/dist/internal/graphql.d.ts.map +1 -0
- package/dist/internal/graphql.js +195 -0
- package/dist/internal/graphql.js.map +1 -0
- package/dist/internal/graphqlHeaders.d.ts +4 -0
- package/dist/internal/graphqlHeaders.d.ts.map +1 -0
- package/dist/internal/graphqlHeaders.js +11 -0
- package/dist/internal/graphqlHeaders.js.map +1 -0
- package/dist/internal/request.js +20 -1
- package/dist/internal/request.js.map +1 -1
- package/dist/internal/schema/toCodeDocument.js +4 -1
- package/dist/internal/schema/toCodeDocument.js.map +1 -1
- package/dist/internal/schema/toJsonSchemaDocument.js +29 -5
- package/dist/internal/schema/toJsonSchemaDocument.js.map +1 -1
- package/dist/internal/version.js +1 -1
- package/dist/net/AddressResolver.d.ts +145 -0
- package/dist/net/AddressResolver.d.ts.map +1 -0
- package/dist/net/AddressResolver.js +114 -0
- package/dist/net/AddressResolver.js.map +1 -0
- package/dist/net/Dns.d.ts +596 -0
- package/dist/net/Dns.d.ts.map +1 -0
- package/dist/net/Dns.js +549 -0
- package/dist/net/Dns.js.map +1 -0
- package/dist/net/Host.d.ts +369 -0
- package/dist/net/Host.d.ts.map +1 -0
- package/dist/net/Host.js +397 -0
- package/dist/net/Host.js.map +1 -0
- package/dist/net/IpInterface.d.ts +76 -3
- package/dist/net/IpInterface.d.ts.map +1 -1
- package/dist/net/IpInterface.js +53 -4
- package/dist/net/IpInterface.js.map +1 -1
- package/dist/net/IpNetwork.d.ts +82 -8
- package/dist/net/IpNetwork.d.ts.map +1 -1
- package/dist/net/IpNetwork.js +60 -4
- package/dist/net/IpNetwork.js.map +1 -1
- package/dist/net/NetAddress.d.ts +396 -35
- package/dist/net/NetAddress.d.ts.map +1 -1
- package/dist/net/NetAddress.js +358 -34
- package/dist/net/NetAddress.js.map +1 -1
- package/dist/net/index.d.ts +15 -0
- package/dist/net/index.d.ts.map +1 -1
- package/dist/net/index.js +15 -0
- package/dist/net/index.js.map +1 -1
- package/dist/observability/OtlpMetrics.d.ts.map +1 -1
- package/dist/observability/OtlpMetrics.js +15 -21
- package/dist/observability/OtlpMetrics.js.map +1 -1
- package/dist/observability/PrometheusMetrics.js +1 -0
- package/dist/observability/PrometheusMetrics.js.map +1 -1
- package/dist/persistence/PersistedQueue.d.ts +32 -3
- package/dist/persistence/PersistedQueue.d.ts.map +1 -1
- package/dist/persistence/PersistedQueue.js +75 -16
- package/dist/persistence/PersistedQueue.js.map +1 -1
- package/dist/rpc/RpcClient.d.ts +22 -6
- package/dist/rpc/RpcClient.d.ts.map +1 -1
- package/dist/rpc/RpcClient.js +12 -5
- package/dist/rpc/RpcClient.js.map +1 -1
- package/dist/rpc/RpcServer.d.ts +6 -0
- package/dist/rpc/RpcServer.d.ts.map +1 -1
- package/dist/rpc/RpcServer.js +78 -29
- package/dist/rpc/RpcServer.js.map +1 -1
- package/dist/socket/DatagramSocket.d.ts +456 -0
- package/dist/socket/DatagramSocket.d.ts.map +1 -0
- package/dist/socket/DatagramSocket.js +535 -0
- package/dist/socket/DatagramSocket.js.map +1 -0
- package/dist/socket/Socket.d.ts +20 -1
- package/dist/socket/Socket.d.ts.map +1 -1
- package/dist/socket/Socket.js +9 -1
- package/dist/socket/Socket.js.map +1 -1
- package/dist/socket/index.d.ts +5 -0
- package/dist/socket/index.d.ts.map +1 -1
- package/dist/socket/index.js +5 -0
- package/dist/socket/index.js.map +1 -1
- package/dist/sql/Migrator.d.ts.map +1 -1
- package/dist/sql/Migrator.js +7 -2
- package/dist/sql/Migrator.js.map +1 -1
- package/dist/sql/SqlClient.d.ts +7 -1
- package/dist/sql/SqlClient.d.ts.map +1 -1
- package/dist/sql/SqlClient.js +31 -6
- package/dist/sql/SqlClient.js.map +1 -1
- package/dist/testing/TestCrypto.d.ts +73 -0
- package/dist/testing/TestCrypto.d.ts.map +1 -0
- package/dist/testing/TestCrypto.js +87 -0
- package/dist/testing/TestCrypto.js.map +1 -0
- package/dist/testing/index.d.ts +5 -0
- package/dist/testing/index.d.ts.map +1 -1
- package/dist/testing/index.js +5 -0
- package/dist/testing/index.js.map +1 -1
- package/dist/workflow/DurableDeferred.d.ts +54 -0
- package/dist/workflow/DurableDeferred.d.ts.map +1 -1
- package/dist/workflow/DurableDeferred.js +108 -50
- package/dist/workflow/DurableDeferred.js.map +1 -1
- package/dist/workflow/WorkflowEngine.d.ts +24 -2
- package/dist/workflow/WorkflowEngine.d.ts.map +1 -1
- package/dist/workflow/WorkflowEngine.js +13 -3
- package/dist/workflow/WorkflowEngine.js.map +1 -1
- package/package.json +6 -3
- package/src/Context.ts +12 -3
- package/src/Crypto.ts +43 -9
- package/src/DateTime.ts +9 -6
- package/src/Duration.ts +36 -16
- package/src/FileSystem.ts +48 -2
- package/src/RequestResolver.ts +4 -10
- package/src/Scheduler.ts +9 -0
- package/src/Schema.ts +677 -5
- package/src/SchemaGetter.ts +47 -35
- package/src/Sink.ts +45 -18
- package/src/Stdio.ts +9 -2
- package/src/Stream.ts +44 -15
- package/src/Utils.ts +8 -5
- package/src/ai/AnthropicStructuredOutput.ts +2 -2
- package/src/ai/Chat.ts +2 -2
- package/src/ai/LanguageModel.ts +96 -24
- package/src/ai/McpServer.ts +288 -94
- package/src/ai/Prompt.ts +24 -10
- package/src/ai/Response.ts +6 -3
- package/src/ai/internal/mcpProtocol/v2026_07_28.ts +5 -0
- package/src/ai/internal/mcpProtocol.ts +3 -0
- package/src/ai/internal/mcpRuntime.ts +2 -0
- package/src/cli/CliOutput.ts +33 -16
- package/src/cli/Command.ts +4 -3
- package/src/cli/Completions.ts +9 -6
- package/src/cli/GlobalFlag.ts +19 -11
- package/src/cli/Prompt.ts +159 -149
- package/src/cli/internal/ansi.ts +26 -3
- package/src/cli/internal/completions/powershell.ts +322 -0
- package/src/cli/internal/completions/zsh.ts +4 -2
- package/src/cli/internal/wizard.ts +34 -26
- package/src/cluster/ClusterSchema.ts +32 -0
- package/src/cluster/ClusterWorkflowEngine.ts +64 -36
- package/src/cluster/MessageStorage.ts +45 -14
- package/src/cluster/Runners.ts +8 -2
- package/src/cluster/Sharding.ts +219 -58
- package/src/cluster/SqlMessageStorage.ts +118 -84
- package/src/cluster/SqlRunnerStorage.ts +224 -128
- package/src/cluster/internal/entityManager.ts +151 -55
- package/src/encoding/Sse.ts +69 -79
- package/src/graphql/GraphQL.ts +494 -0
- package/src/graphql/GraphQLClient.ts +912 -0
- package/src/graphql/GraphQLClientError.ts +542 -0
- package/src/graphql/GraphQLGroup.ts +167 -0
- package/src/graphql/GraphQLMiddleware.ts +253 -0
- package/src/graphql/GraphQLProtocol.ts +1286 -0
- package/src/graphql/GraphQLResolver.ts +1010 -0
- package/src/graphql/index.ts +48 -0
- package/src/http/FindMyWay/internal/router.ts +4 -7
- package/src/http/HttpClient.ts +110 -12
- package/src/http/HttpEffect.ts +11 -5
- package/src/http/HttpMiddleware.ts +33 -34
- package/src/http/HttpRouter.ts +35 -0
- package/src/http/HttpServerResponse.ts +28 -16
- package/src/http/HttpTraceContext.ts +8 -2
- package/src/http/Multipart.ts +17 -1
- package/src/http-api/HttpApiScalar.ts +5 -0
- package/src/internal/dateTime.ts +13 -10
- package/src/internal/effect.ts +22 -15
- package/src/internal/graphql.ts +263 -0
- package/src/internal/graphqlHeaders.ts +11 -0
- package/src/internal/request.ts +31 -3
- package/src/internal/schema/toCodeDocument.ts +7 -1
- package/src/internal/schema/toJsonSchemaDocument.ts +34 -2
- package/src/internal/version.ts +1 -1
- package/src/net/AddressResolver.ts +222 -0
- package/src/net/Dns.ts +1035 -0
- package/src/net/Host.ts +544 -0
- package/src/net/IpInterface.ts +117 -7
- package/src/net/IpNetwork.ts +116 -17
- package/src/net/NetAddress.ts +620 -76
- package/src/net/index.ts +18 -0
- package/src/observability/OtlpMetrics.ts +12 -23
- package/src/observability/PrometheusMetrics.ts +1 -0
- package/src/persistence/PersistedQueue.ts +146 -53
- package/src/rpc/RpcClient.ts +41 -19
- package/src/rpc/RpcServer.ts +115 -40
- package/src/socket/DatagramSocket.ts +919 -0
- package/src/socket/Socket.ts +28 -2
- package/src/socket/index.ts +6 -0
- package/src/sql/Migrator.ts +21 -5
- package/src/sql/SqlClient.ts +39 -15
- package/src/testing/TestCrypto.ts +94 -0
- package/src/testing/index.ts +6 -0
- package/src/workflow/DurableDeferred.ts +160 -47
- package/src/workflow/WorkflowEngine.ts +50 -5
|
@@ -0,0 +1,1010 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Batch lookups through a GraphQL client method with `RequestResolver`.
|
|
3
|
+
* {@link ordered} matches results by position; {@link findById} matches by
|
|
4
|
+
* key; {@link aliased} repeats an operation under aliases in one request.
|
|
5
|
+
* {@link request} turns any of them into `(key) => Effect`.
|
|
6
|
+
*
|
|
7
|
+
* Client middleware still run. When a method needs services, such as a
|
|
8
|
+
* middleware's `requires`, `batchKey` keeps lookups with different services
|
|
9
|
+
* in separate batches. Compose `RequestResolver.setDelay` and
|
|
10
|
+
* `RequestResolver.batchN` with `.pipe` to control batching.
|
|
11
|
+
*
|
|
12
|
+
* @stability experimental
|
|
13
|
+
* @since 4.0.0
|
|
14
|
+
*/
|
|
15
|
+
import * as Arr from "../Array.ts"
|
|
16
|
+
import * as Cause from "../Cause.ts"
|
|
17
|
+
import type * as Context from "../Context.ts"
|
|
18
|
+
import * as Effect from "../Effect.ts"
|
|
19
|
+
import * as Exit from "../Exit.ts"
|
|
20
|
+
import { dual } from "../Function.ts"
|
|
21
|
+
import * as Headers from "../http/Headers.ts"
|
|
22
|
+
import * as UrlParams from "../http/UrlParams.ts"
|
|
23
|
+
import * as internalGraphQL from "../internal/graphql.ts"
|
|
24
|
+
import * as MutableHashMap from "../MutableHashMap.ts"
|
|
25
|
+
import * as Request from "../Request.ts"
|
|
26
|
+
import * as RequestResolver from "../RequestResolver.ts"
|
|
27
|
+
import type * as Types from "../Types.ts"
|
|
28
|
+
import type * as GraphQL from "./GraphQL.ts"
|
|
29
|
+
import type { OperationMethod, PartialResult } from "./GraphQLClient.ts"
|
|
30
|
+
import { DecodeError, type GraphQLClientError, type GraphQLError } from "./GraphQLClientError.ts"
|
|
31
|
+
import type { ExecutionResult, GraphQLRequest } from "./GraphQLProtocol.ts"
|
|
32
|
+
|
|
33
|
+
// -----------------------------------------------------------------------------
|
|
34
|
+
// Types
|
|
35
|
+
// -----------------------------------------------------------------------------
|
|
36
|
+
|
|
37
|
+
type NonNull<A> = Exclude<A, null | undefined>
|
|
38
|
+
|
|
39
|
+
type Step<A, K> = K extends keyof NonNull<A> ? NonNull<A>[K] : never
|
|
40
|
+
|
|
41
|
+
// Check one segment at a time for autocomplete without enumerating all paths.
|
|
42
|
+
// The path must end at a list and cannot cross one.
|
|
43
|
+
type CheckPath<A, P> = NonNull<A> extends ReadonlyArray<any> ? readonly []
|
|
44
|
+
: P extends readonly [infer Head, ...infer Tail]
|
|
45
|
+
? readonly [Head extends keyof NonNull<A> ? Head : keyof NonNull<A>, ...CheckPath<Step<A, Head>, Tail>]
|
|
46
|
+
: readonly [keyof NonNull<A>]
|
|
47
|
+
|
|
48
|
+
type Path<A, P> = P extends CheckPath<A, P> ? P : CheckPath<A, P>
|
|
49
|
+
|
|
50
|
+
type AtPath<A, P> = P extends readonly [infer Head, ...infer Tail] ? AtPath<Step<A, Head>, Tail> : A
|
|
51
|
+
|
|
52
|
+
type Item<A, P> = NonNull<AtPath<A, P>> extends ReadonlyArray<infer I> ? NonNull<I> : never
|
|
53
|
+
|
|
54
|
+
type Typenames<I> = Types.IsUnion<I> extends true ?
|
|
55
|
+
I extends { readonly __typename: infer T extends string } ? T : never
|
|
56
|
+
: never
|
|
57
|
+
|
|
58
|
+
type Narrow<I, T> = [T] extends [never] ? I : Extract<I, { readonly __typename: T }>
|
|
59
|
+
|
|
60
|
+
type BatchKey<Op extends GraphQL.Any> = [GraphQL.Services<Op>] extends [never] ? { readonly batchKey?: never }
|
|
61
|
+
: { readonly batchKey: (context: Context.Context<GraphQL.Services<Op>>) => unknown }
|
|
62
|
+
|
|
63
|
+
interface KeyRequest<K, A, E, R> extends Request.Request<A, E, R> {
|
|
64
|
+
readonly key: K
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// Requests are structural, so two requests with equal keys are one request.
|
|
68
|
+
const makeRequest = <K, A, E, R>(key: K): KeyRequest<K, A, E, R> => Request.of<KeyRequest<K, A, E, R>>()({ key })
|
|
69
|
+
|
|
70
|
+
// -----------------------------------------------------------------------------
|
|
71
|
+
// Running
|
|
72
|
+
// -----------------------------------------------------------------------------
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Looks up a key with an {@link ordered}, {@link findById} or {@link aliased}
|
|
76
|
+
* resolver, using `request(resolver)(key)` or `request(key, resolver)`.
|
|
77
|
+
*
|
|
78
|
+
* **Details**
|
|
79
|
+
*
|
|
80
|
+
* Concurrent lookups are batched. Keys equal under `Equal` and `Hash`
|
|
81
|
+
* are sent once per batch and share the result.
|
|
82
|
+
*
|
|
83
|
+
* **Example** (Looking up repositories by id)
|
|
84
|
+
*
|
|
85
|
+
* ```ts import.meta.vitest
|
|
86
|
+
* import { Effect, Layer, Schema, Stream } from "effect"
|
|
87
|
+
* import { GraphQL, GraphQLClient, GraphQLGroup, GraphQLProtocol, GraphQLResolver } from "effect/graphql"
|
|
88
|
+
*
|
|
89
|
+
* const RepoNodes = GraphQL.query("RepoNodes", {
|
|
90
|
+
* document: "query RepoNodes($ids:[ID!]!){nodes(ids:$ids){... on Repository{name}}}",
|
|
91
|
+
* variables: { ids: Schema.Array(Schema.String) },
|
|
92
|
+
* result: Schema.Struct({ nodes: Schema.Array(Schema.NullOr(Schema.Struct({ name: Schema.String }))) })
|
|
93
|
+
* })
|
|
94
|
+
*
|
|
95
|
+
* let calls = 0
|
|
96
|
+
* const Scripted = Layer.succeed(GraphQLProtocol.GraphQLProtocol, {
|
|
97
|
+
* execute: (request) => {
|
|
98
|
+
* calls++
|
|
99
|
+
* const { ids } = request.variables as { ids: Array<string> }
|
|
100
|
+
* return Effect.succeed({ body: { data: { nodes: ids.map((id) => ({ name: `repo-${id}` })) } } })
|
|
101
|
+
* },
|
|
102
|
+
* subscribe: () => Stream.empty
|
|
103
|
+
* })
|
|
104
|
+
*
|
|
105
|
+
* const program = Effect.gen(function*() {
|
|
106
|
+
* const client = yield* GraphQLClient.make(GraphQLGroup.make(RepoNodes))
|
|
107
|
+
* const getRepo = GraphQLResolver.request(GraphQLResolver.ordered(client.RepoNodes, {
|
|
108
|
+
* variables: (ids: ReadonlyArray<string>) => ({ ids }),
|
|
109
|
+
* path: ["nodes"]
|
|
110
|
+
* }))
|
|
111
|
+
* const repos = yield* Effect.forEach(["1", "2", "1"], getRepo, { concurrency: "unbounded" })
|
|
112
|
+
* return [repos.map((repo) => repo.name), calls]
|
|
113
|
+
* })
|
|
114
|
+
*
|
|
115
|
+
* await Effect.runPromise(program.pipe(Effect.provide(Scripted))) // => [["repo-1", "repo-2", "repo-1"], 1]
|
|
116
|
+
* ```
|
|
117
|
+
*
|
|
118
|
+
* @stability experimental
|
|
119
|
+
* @category running
|
|
120
|
+
* @since 4.0.0
|
|
121
|
+
*/
|
|
122
|
+
export const request: {
|
|
123
|
+
// -----------------------------------------------------------------------------
|
|
124
|
+
// Running
|
|
125
|
+
// -----------------------------------------------------------------------------
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Looks up a key with an {@link ordered}, {@link findById} or {@link aliased}
|
|
129
|
+
* resolver, using `request(resolver)(key)` or `request(key, resolver)`.
|
|
130
|
+
*
|
|
131
|
+
* **Details**
|
|
132
|
+
*
|
|
133
|
+
* Concurrent lookups are batched. Keys equal under `Equal` and `Hash`
|
|
134
|
+
* are sent once per batch and share the result.
|
|
135
|
+
*
|
|
136
|
+
* **Example** (Looking up repositories by id)
|
|
137
|
+
*
|
|
138
|
+
* ```ts import.meta.vitest
|
|
139
|
+
* import { Effect, Layer, Schema, Stream } from "effect"
|
|
140
|
+
* import { GraphQL, GraphQLClient, GraphQLGroup, GraphQLProtocol, GraphQLResolver } from "effect/graphql"
|
|
141
|
+
*
|
|
142
|
+
* const RepoNodes = GraphQL.query("RepoNodes", {
|
|
143
|
+
* document: "query RepoNodes($ids:[ID!]!){nodes(ids:$ids){... on Repository{name}}}",
|
|
144
|
+
* variables: { ids: Schema.Array(Schema.String) },
|
|
145
|
+
* result: Schema.Struct({ nodes: Schema.Array(Schema.NullOr(Schema.Struct({ name: Schema.String }))) })
|
|
146
|
+
* })
|
|
147
|
+
*
|
|
148
|
+
* let calls = 0
|
|
149
|
+
* const Scripted = Layer.succeed(GraphQLProtocol.GraphQLProtocol, {
|
|
150
|
+
* execute: (request) => {
|
|
151
|
+
* calls++
|
|
152
|
+
* const { ids } = request.variables as { ids: Array<string> }
|
|
153
|
+
* return Effect.succeed({ body: { data: { nodes: ids.map((id) => ({ name: `repo-${id}` })) } } })
|
|
154
|
+
* },
|
|
155
|
+
* subscribe: () => Stream.empty
|
|
156
|
+
* })
|
|
157
|
+
*
|
|
158
|
+
* const program = Effect.gen(function*() {
|
|
159
|
+
* const client = yield* GraphQLClient.make(GraphQLGroup.make(RepoNodes))
|
|
160
|
+
* const getRepo = GraphQLResolver.request(GraphQLResolver.ordered(client.RepoNodes, {
|
|
161
|
+
* variables: (ids: ReadonlyArray<string>) => ({ ids }),
|
|
162
|
+
* path: ["nodes"]
|
|
163
|
+
* }))
|
|
164
|
+
* const repos = yield* Effect.forEach(["1", "2", "1"], getRepo, { concurrency: "unbounded" })
|
|
165
|
+
* return [repos.map((repo) => repo.name), calls]
|
|
166
|
+
* })
|
|
167
|
+
*
|
|
168
|
+
* await Effect.runPromise(program.pipe(Effect.provide(Scripted))) // => [["repo-1", "repo-2", "repo-1"], 1]
|
|
169
|
+
* ```
|
|
170
|
+
*
|
|
171
|
+
* @stability experimental
|
|
172
|
+
* @category running
|
|
173
|
+
* @since 4.0.0
|
|
174
|
+
*/
|
|
175
|
+
<K, A, E, R>(resolver: RequestResolver.RequestResolver<KeyRequest<K, A, E, R>>): (key: K) => Effect.Effect<A, E, R>
|
|
176
|
+
// -----------------------------------------------------------------------------
|
|
177
|
+
// Running
|
|
178
|
+
// -----------------------------------------------------------------------------
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Looks up a key with an {@link ordered}, {@link findById} or {@link aliased}
|
|
182
|
+
* resolver, using `request(resolver)(key)` or `request(key, resolver)`.
|
|
183
|
+
*
|
|
184
|
+
* **Details**
|
|
185
|
+
*
|
|
186
|
+
* Concurrent lookups are batched. Keys equal under `Equal` and `Hash`
|
|
187
|
+
* are sent once per batch and share the result.
|
|
188
|
+
*
|
|
189
|
+
* **Example** (Looking up repositories by id)
|
|
190
|
+
*
|
|
191
|
+
* ```ts import.meta.vitest
|
|
192
|
+
* import { Effect, Layer, Schema, Stream } from "effect"
|
|
193
|
+
* import { GraphQL, GraphQLClient, GraphQLGroup, GraphQLProtocol, GraphQLResolver } from "effect/graphql"
|
|
194
|
+
*
|
|
195
|
+
* const RepoNodes = GraphQL.query("RepoNodes", {
|
|
196
|
+
* document: "query RepoNodes($ids:[ID!]!){nodes(ids:$ids){... on Repository{name}}}",
|
|
197
|
+
* variables: { ids: Schema.Array(Schema.String) },
|
|
198
|
+
* result: Schema.Struct({ nodes: Schema.Array(Schema.NullOr(Schema.Struct({ name: Schema.String }))) })
|
|
199
|
+
* })
|
|
200
|
+
*
|
|
201
|
+
* let calls = 0
|
|
202
|
+
* const Scripted = Layer.succeed(GraphQLProtocol.GraphQLProtocol, {
|
|
203
|
+
* execute: (request) => {
|
|
204
|
+
* calls++
|
|
205
|
+
* const { ids } = request.variables as { ids: Array<string> }
|
|
206
|
+
* return Effect.succeed({ body: { data: { nodes: ids.map((id) => ({ name: `repo-${id}` })) } } })
|
|
207
|
+
* },
|
|
208
|
+
* subscribe: () => Stream.empty
|
|
209
|
+
* })
|
|
210
|
+
*
|
|
211
|
+
* const program = Effect.gen(function*() {
|
|
212
|
+
* const client = yield* GraphQLClient.make(GraphQLGroup.make(RepoNodes))
|
|
213
|
+
* const getRepo = GraphQLResolver.request(GraphQLResolver.ordered(client.RepoNodes, {
|
|
214
|
+
* variables: (ids: ReadonlyArray<string>) => ({ ids }),
|
|
215
|
+
* path: ["nodes"]
|
|
216
|
+
* }))
|
|
217
|
+
* const repos = yield* Effect.forEach(["1", "2", "1"], getRepo, { concurrency: "unbounded" })
|
|
218
|
+
* return [repos.map((repo) => repo.name), calls]
|
|
219
|
+
* })
|
|
220
|
+
*
|
|
221
|
+
* await Effect.runPromise(program.pipe(Effect.provide(Scripted))) // => [["repo-1", "repo-2", "repo-1"], 1]
|
|
222
|
+
* ```
|
|
223
|
+
*
|
|
224
|
+
* @stability experimental
|
|
225
|
+
* @category running
|
|
226
|
+
* @since 4.0.0
|
|
227
|
+
*/
|
|
228
|
+
<K, A, E, R>(key: K, resolver: RequestResolver.RequestResolver<KeyRequest<K, A, E, R>>): Effect.Effect<A, E, R>
|
|
229
|
+
} = dual(
|
|
230
|
+
2,
|
|
231
|
+
<K, A, E, R>(key: K, resolver: RequestResolver.RequestResolver<KeyRequest<K, A, E, R>>): Effect.Effect<A, E, R> =>
|
|
232
|
+
Effect.request(makeRequest<// -----------------------------------------------------------------------------
|
|
233
|
+
// Running
|
|
234
|
+
// -----------------------------------------------------------------------------
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Looks up a key with an {@link ordered}, {@link findById} or {@link aliased}
|
|
238
|
+
* resolver, using `request(resolver)(key)` or `request(key, resolver)`.
|
|
239
|
+
*
|
|
240
|
+
* **Details**
|
|
241
|
+
*
|
|
242
|
+
* Concurrent lookups are batched. Keys equal under `Equal` and `Hash`
|
|
243
|
+
* are sent once per batch and share the result.
|
|
244
|
+
*
|
|
245
|
+
* **Example** (Looking up repositories by id)
|
|
246
|
+
*
|
|
247
|
+
* ```ts import.meta.vitest
|
|
248
|
+
* import { Effect, Layer, Schema, Stream } from "effect"
|
|
249
|
+
* import { GraphQL, GraphQLClient, GraphQLGroup, GraphQLProtocol, GraphQLResolver } from "effect/graphql"
|
|
250
|
+
*
|
|
251
|
+
* const RepoNodes = GraphQL.query("RepoNodes", {
|
|
252
|
+
* document: "query RepoNodes($ids:[ID!]!){nodes(ids:$ids){... on Repository{name}}}",
|
|
253
|
+
* variables: { ids: Schema.Array(Schema.String) },
|
|
254
|
+
* result: Schema.Struct({ nodes: Schema.Array(Schema.NullOr(Schema.Struct({ name: Schema.String }))) })
|
|
255
|
+
* })
|
|
256
|
+
*
|
|
257
|
+
* let calls = 0
|
|
258
|
+
* const Scripted = Layer.succeed(GraphQLProtocol.GraphQLProtocol, {
|
|
259
|
+
* execute: (request) => {
|
|
260
|
+
* calls++
|
|
261
|
+
* const { ids } = request.variables as { ids: Array<string> }
|
|
262
|
+
* return Effect.succeed({ body: { data: { nodes: ids.map((id) => ({ name: `repo-${id}` })) } } })
|
|
263
|
+
* },
|
|
264
|
+
* subscribe: () => Stream.empty
|
|
265
|
+
* })
|
|
266
|
+
*
|
|
267
|
+
* const program = Effect.gen(function*() {
|
|
268
|
+
* const client = yield* GraphQLClient.make(GraphQLGroup.make(RepoNodes))
|
|
269
|
+
* const getRepo = GraphQLResolver.request(GraphQLResolver.ordered(client.RepoNodes, {
|
|
270
|
+
* variables: (ids: ReadonlyArray<string>) => ({ ids }),
|
|
271
|
+
* path: ["nodes"]
|
|
272
|
+
* }))
|
|
273
|
+
* const repos = yield* Effect.forEach(["1", "2", "1"], getRepo, { concurrency: "unbounded" })
|
|
274
|
+
* return [repos.map((repo) => repo.name), calls]
|
|
275
|
+
* })
|
|
276
|
+
*
|
|
277
|
+
* await Effect.runPromise(program.pipe(Effect.provide(Scripted))) // => [["repo-1", "repo-2", "repo-1"], 1]
|
|
278
|
+
* ```
|
|
279
|
+
*
|
|
280
|
+
* @stability experimental
|
|
281
|
+
* @category running
|
|
282
|
+
* @since 4.0.0
|
|
283
|
+
*/
|
|
284
|
+
K, // -----------------------------------------------------------------------------
|
|
285
|
+
// Running
|
|
286
|
+
// -----------------------------------------------------------------------------
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* Looks up a key with an {@link ordered}, {@link findById} or {@link aliased}
|
|
290
|
+
* resolver, using `request(resolver)(key)` or `request(key, resolver)`.
|
|
291
|
+
*
|
|
292
|
+
* **Details**
|
|
293
|
+
*
|
|
294
|
+
* Concurrent lookups are batched. Keys equal under `Equal` and `Hash`
|
|
295
|
+
* are sent once per batch and share the result.
|
|
296
|
+
*
|
|
297
|
+
* **Example** (Looking up repositories by id)
|
|
298
|
+
*
|
|
299
|
+
* ```ts import.meta.vitest
|
|
300
|
+
* import { Effect, Layer, Schema, Stream } from "effect"
|
|
301
|
+
* import { GraphQL, GraphQLClient, GraphQLGroup, GraphQLProtocol, GraphQLResolver } from "effect/graphql"
|
|
302
|
+
*
|
|
303
|
+
* const RepoNodes = GraphQL.query("RepoNodes", {
|
|
304
|
+
* document: "query RepoNodes($ids:[ID!]!){nodes(ids:$ids){... on Repository{name}}}",
|
|
305
|
+
* variables: { ids: Schema.Array(Schema.String) },
|
|
306
|
+
* result: Schema.Struct({ nodes: Schema.Array(Schema.NullOr(Schema.Struct({ name: Schema.String }))) })
|
|
307
|
+
* })
|
|
308
|
+
*
|
|
309
|
+
* let calls = 0
|
|
310
|
+
* const Scripted = Layer.succeed(GraphQLProtocol.GraphQLProtocol, {
|
|
311
|
+
* execute: (request) => {
|
|
312
|
+
* calls++
|
|
313
|
+
* const { ids } = request.variables as { ids: Array<string> }
|
|
314
|
+
* return Effect.succeed({ body: { data: { nodes: ids.map((id) => ({ name: `repo-${id}` })) } } })
|
|
315
|
+
* },
|
|
316
|
+
* subscribe: () => Stream.empty
|
|
317
|
+
* })
|
|
318
|
+
*
|
|
319
|
+
* const program = Effect.gen(function*() {
|
|
320
|
+
* const client = yield* GraphQLClient.make(GraphQLGroup.make(RepoNodes))
|
|
321
|
+
* const getRepo = GraphQLResolver.request(GraphQLResolver.ordered(client.RepoNodes, {
|
|
322
|
+
* variables: (ids: ReadonlyArray<string>) => ({ ids }),
|
|
323
|
+
* path: ["nodes"]
|
|
324
|
+
* }))
|
|
325
|
+
* const repos = yield* Effect.forEach(["1", "2", "1"], getRepo, { concurrency: "unbounded" })
|
|
326
|
+
* return [repos.map((repo) => repo.name), calls]
|
|
327
|
+
* })
|
|
328
|
+
*
|
|
329
|
+
* await Effect.runPromise(program.pipe(Effect.provide(Scripted))) // => [["repo-1", "repo-2", "repo-1"], 1]
|
|
330
|
+
* ```
|
|
331
|
+
*
|
|
332
|
+
* @stability experimental
|
|
333
|
+
* @category running
|
|
334
|
+
* @since 4.0.0
|
|
335
|
+
*/
|
|
336
|
+
A, // -----------------------------------------------------------------------------
|
|
337
|
+
// Running
|
|
338
|
+
// -----------------------------------------------------------------------------
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* Looks up a key with an {@link ordered}, {@link findById} or {@link aliased}
|
|
342
|
+
* resolver, using `request(resolver)(key)` or `request(key, resolver)`.
|
|
343
|
+
*
|
|
344
|
+
* **Details**
|
|
345
|
+
*
|
|
346
|
+
* Concurrent lookups are batched. Keys equal under `Equal` and `Hash`
|
|
347
|
+
* are sent once per batch and share the result.
|
|
348
|
+
*
|
|
349
|
+
* **Example** (Looking up repositories by id)
|
|
350
|
+
*
|
|
351
|
+
* ```ts import.meta.vitest
|
|
352
|
+
* import { Effect, Layer, Schema, Stream } from "effect"
|
|
353
|
+
* import { GraphQL, GraphQLClient, GraphQLGroup, GraphQLProtocol, GraphQLResolver } from "effect/graphql"
|
|
354
|
+
*
|
|
355
|
+
* const RepoNodes = GraphQL.query("RepoNodes", {
|
|
356
|
+
* document: "query RepoNodes($ids:[ID!]!){nodes(ids:$ids){... on Repository{name}}}",
|
|
357
|
+
* variables: { ids: Schema.Array(Schema.String) },
|
|
358
|
+
* result: Schema.Struct({ nodes: Schema.Array(Schema.NullOr(Schema.Struct({ name: Schema.String }))) })
|
|
359
|
+
* })
|
|
360
|
+
*
|
|
361
|
+
* let calls = 0
|
|
362
|
+
* const Scripted = Layer.succeed(GraphQLProtocol.GraphQLProtocol, {
|
|
363
|
+
* execute: (request) => {
|
|
364
|
+
* calls++
|
|
365
|
+
* const { ids } = request.variables as { ids: Array<string> }
|
|
366
|
+
* return Effect.succeed({ body: { data: { nodes: ids.map((id) => ({ name: `repo-${id}` })) } } })
|
|
367
|
+
* },
|
|
368
|
+
* subscribe: () => Stream.empty
|
|
369
|
+
* })
|
|
370
|
+
*
|
|
371
|
+
* const program = Effect.gen(function*() {
|
|
372
|
+
* const client = yield* GraphQLClient.make(GraphQLGroup.make(RepoNodes))
|
|
373
|
+
* const getRepo = GraphQLResolver.request(GraphQLResolver.ordered(client.RepoNodes, {
|
|
374
|
+
* variables: (ids: ReadonlyArray<string>) => ({ ids }),
|
|
375
|
+
* path: ["nodes"]
|
|
376
|
+
* }))
|
|
377
|
+
* const repos = yield* Effect.forEach(["1", "2", "1"], getRepo, { concurrency: "unbounded" })
|
|
378
|
+
* return [repos.map((repo) => repo.name), calls]
|
|
379
|
+
* })
|
|
380
|
+
*
|
|
381
|
+
* await Effect.runPromise(program.pipe(Effect.provide(Scripted))) // => [["repo-1", "repo-2", "repo-1"], 1]
|
|
382
|
+
* ```
|
|
383
|
+
*
|
|
384
|
+
* @stability experimental
|
|
385
|
+
* @category running
|
|
386
|
+
* @since 4.0.0
|
|
387
|
+
*/
|
|
388
|
+
E, // -----------------------------------------------------------------------------
|
|
389
|
+
// Running
|
|
390
|
+
// -----------------------------------------------------------------------------
|
|
391
|
+
|
|
392
|
+
/**
|
|
393
|
+
* Looks up a key with an {@link ordered}, {@link findById} or {@link aliased}
|
|
394
|
+
* resolver, using `request(resolver)(key)` or `request(key, resolver)`.
|
|
395
|
+
*
|
|
396
|
+
* **Details**
|
|
397
|
+
*
|
|
398
|
+
* Concurrent lookups are batched. Keys equal under `Equal` and `Hash`
|
|
399
|
+
* are sent once per batch and share the result.
|
|
400
|
+
*
|
|
401
|
+
* **Example** (Looking up repositories by id)
|
|
402
|
+
*
|
|
403
|
+
* ```ts import.meta.vitest
|
|
404
|
+
* import { Effect, Layer, Schema, Stream } from "effect"
|
|
405
|
+
* import { GraphQL, GraphQLClient, GraphQLGroup, GraphQLProtocol, GraphQLResolver } from "effect/graphql"
|
|
406
|
+
*
|
|
407
|
+
* const RepoNodes = GraphQL.query("RepoNodes", {
|
|
408
|
+
* document: "query RepoNodes($ids:[ID!]!){nodes(ids:$ids){... on Repository{name}}}",
|
|
409
|
+
* variables: { ids: Schema.Array(Schema.String) },
|
|
410
|
+
* result: Schema.Struct({ nodes: Schema.Array(Schema.NullOr(Schema.Struct({ name: Schema.String }))) })
|
|
411
|
+
* })
|
|
412
|
+
*
|
|
413
|
+
* let calls = 0
|
|
414
|
+
* const Scripted = Layer.succeed(GraphQLProtocol.GraphQLProtocol, {
|
|
415
|
+
* execute: (request) => {
|
|
416
|
+
* calls++
|
|
417
|
+
* const { ids } = request.variables as { ids: Array<string> }
|
|
418
|
+
* return Effect.succeed({ body: { data: { nodes: ids.map((id) => ({ name: `repo-${id}` })) } } })
|
|
419
|
+
* },
|
|
420
|
+
* subscribe: () => Stream.empty
|
|
421
|
+
* })
|
|
422
|
+
*
|
|
423
|
+
* const program = Effect.gen(function*() {
|
|
424
|
+
* const client = yield* GraphQLClient.make(GraphQLGroup.make(RepoNodes))
|
|
425
|
+
* const getRepo = GraphQLResolver.request(GraphQLResolver.ordered(client.RepoNodes, {
|
|
426
|
+
* variables: (ids: ReadonlyArray<string>) => ({ ids }),
|
|
427
|
+
* path: ["nodes"]
|
|
428
|
+
* }))
|
|
429
|
+
* const repos = yield* Effect.forEach(["1", "2", "1"], getRepo, { concurrency: "unbounded" })
|
|
430
|
+
* return [repos.map((repo) => repo.name), calls]
|
|
431
|
+
* })
|
|
432
|
+
*
|
|
433
|
+
* await Effect.runPromise(program.pipe(Effect.provide(Scripted))) // => [["repo-1", "repo-2", "repo-1"], 1]
|
|
434
|
+
* ```
|
|
435
|
+
*
|
|
436
|
+
* @stability experimental
|
|
437
|
+
* @category running
|
|
438
|
+
* @since 4.0.0
|
|
439
|
+
*/
|
|
440
|
+
R>(key), resolver)
|
|
441
|
+
)
|
|
442
|
+
|
|
443
|
+
// -----------------------------------------------------------------------------
|
|
444
|
+
// Resolvers
|
|
445
|
+
// -----------------------------------------------------------------------------
|
|
446
|
+
|
|
447
|
+
/**
|
|
448
|
+
* Batches lookups for fields such as `nodes(ids:)` that return one entry per
|
|
449
|
+
* key in input order.
|
|
450
|
+
*
|
|
451
|
+
* **Details**
|
|
452
|
+
*
|
|
453
|
+
* `variables` maps batch keys to operation variables; annotate its parameter
|
|
454
|
+
* to set the key type. `path` selects a list through object fields, with
|
|
455
|
+
* autocomplete at each level. For `__typename` unions, `typename` narrows
|
|
456
|
+
* the success type and treats other types as missing.
|
|
457
|
+
*
|
|
458
|
+
* Null entries, typename mismatches and null parents fail with
|
|
459
|
+
* `Cause.NoSuchElementError`. GraphQL errors whose paths start with
|
|
460
|
+
* `[...path, i]` fail only entry `i`; its `ResponseError` contains those errors
|
|
461
|
+
* and the response status. Other GraphQL errors fail the batch with the same
|
|
462
|
+
* `ResponseError` as a non-partial call. Transport, encode and decode errors
|
|
463
|
+
* also fail the batch. A list length mismatch fails with `DecodeError`.
|
|
464
|
+
*
|
|
465
|
+
* `pageInfo.hasNextPage: true` on the list's parent fails the batch with
|
|
466
|
+
* `DecodeError` to avoid reporting unreturned entries as missing. Set the
|
|
467
|
+
* operation's page size at least as large as `RequestResolver.batchN`.
|
|
468
|
+
*
|
|
469
|
+
* A batch uses one lookup's services. Methods requiring services also require
|
|
470
|
+
* `batchKey`; only lookups with keys equal under `Equal` share a batch. Return
|
|
471
|
+
* the value that distinguishes those services, for example
|
|
472
|
+
* `(context) => Context.get(context, CurrentUser).tenantId`. Methods without
|
|
473
|
+
* services use one batch and do not accept `batchKey`.
|
|
474
|
+
*
|
|
475
|
+
* **Gotchas**
|
|
476
|
+
*
|
|
477
|
+
* Don't return the whole context from `batchKey`. It also holds the caller's
|
|
478
|
+
* span, so most lookups would get a batch of their own.
|
|
479
|
+
*
|
|
480
|
+
* A middleware that reads a `Context.Reference` with a default value doesn't
|
|
481
|
+
* add it to the method's services. `batchKey` isn't required for it, and
|
|
482
|
+
* lookups with different values can share a batch.
|
|
483
|
+
*
|
|
484
|
+
* **Example** (Looking up repositories in a `Node` union)
|
|
485
|
+
*
|
|
486
|
+
* ```ts import.meta.vitest
|
|
487
|
+
* import { Cause, Effect, Layer, RequestResolver, Schema, Stream } from "effect"
|
|
488
|
+
* import { GraphQL, GraphQLClient, GraphQLGroup, GraphQLProtocol, GraphQLResolver } from "effect/graphql"
|
|
489
|
+
*
|
|
490
|
+
* const Repository = Schema.Struct({ __typename: Schema.Literal("Repository"), nameWithOwner: Schema.String })
|
|
491
|
+
* const User = Schema.Struct({ __typename: Schema.Literal("User"), login: Schema.String })
|
|
492
|
+
*
|
|
493
|
+
* const RepoNodes = GraphQL.query("RepoNodes", {
|
|
494
|
+
* document: "query RepoNodes($ids:[ID!]!){nodes(ids:$ids){__typename ...on Repository{nameWithOwner} ...on User{login}}}",
|
|
495
|
+
* variables: { ids: Schema.Array(Schema.String) },
|
|
496
|
+
* result: Schema.Struct({ nodes: Schema.Array(Schema.NullOr(Schema.Union([Repository, User]))) })
|
|
497
|
+
* })
|
|
498
|
+
*
|
|
499
|
+
* const store: Record<string, unknown> = {
|
|
500
|
+
* R_1: { __typename: "Repository", nameWithOwner: "Effect-TS/effect" },
|
|
501
|
+
* U_1: { __typename: "User", login: "tim" }
|
|
502
|
+
* }
|
|
503
|
+
* const Scripted = Layer.succeed(GraphQLProtocol.GraphQLProtocol, {
|
|
504
|
+
* execute: (request) => {
|
|
505
|
+
* const { ids } = request.variables as { ids: Array<string> }
|
|
506
|
+
* return Effect.succeed({ body: { data: { nodes: ids.map((id) => store[id] ?? null) } } })
|
|
507
|
+
* },
|
|
508
|
+
* subscribe: () => Stream.empty
|
|
509
|
+
* })
|
|
510
|
+
*
|
|
511
|
+
* const program = Effect.gen(function*() {
|
|
512
|
+
* const client = yield* GraphQLClient.make(GraphQLGroup.make(RepoNodes))
|
|
513
|
+
* const RepoById = GraphQLResolver.ordered(client.RepoNodes, {
|
|
514
|
+
* variables: (ids: ReadonlyArray<string>) => ({ ids }),
|
|
515
|
+
* path: ["nodes"],
|
|
516
|
+
* typename: "Repository"
|
|
517
|
+
* }).pipe(RequestResolver.batchN(100))
|
|
518
|
+
* const getRepo = GraphQLResolver.request(RepoById)
|
|
519
|
+
* return yield* Effect.forEach(
|
|
520
|
+
* ["R_1", "U_1", "R_2"],
|
|
521
|
+
* (id) => getRepo(id).pipe(
|
|
522
|
+
* Effect.map((repo) => repo.nameWithOwner),
|
|
523
|
+
* Effect.catchIf(Cause.isNoSuchElementError, () => Effect.succeed("missing"))
|
|
524
|
+
* ),
|
|
525
|
+
* { concurrency: "unbounded" }
|
|
526
|
+
* )
|
|
527
|
+
* })
|
|
528
|
+
*
|
|
529
|
+
* await Effect.runPromise(program.pipe(Effect.provide(Scripted))) // => ["Effect-TS/effect", "missing", "missing"]
|
|
530
|
+
* ```
|
|
531
|
+
*
|
|
532
|
+
* @stability experimental
|
|
533
|
+
* @category resolvers
|
|
534
|
+
* @since 4.0.0
|
|
535
|
+
*/
|
|
536
|
+
export const ordered = <
|
|
537
|
+
Op extends GraphQL.Any,
|
|
538
|
+
K,
|
|
539
|
+
const P extends ReadonlyArray<string>,
|
|
540
|
+
T extends Typenames<Item<GraphQL.Result<Op>, P>> = never
|
|
541
|
+
>(
|
|
542
|
+
method: OperationMethod<Op>,
|
|
543
|
+
options: {
|
|
544
|
+
readonly variables: (keys: ReadonlyArray<K>) => GraphQL.Variables<Op>
|
|
545
|
+
readonly path: Path<GraphQL.Result<Op>, P>
|
|
546
|
+
readonly typename?: T | undefined
|
|
547
|
+
} & BatchKey<Op>
|
|
548
|
+
): RequestResolver.RequestResolver<
|
|
549
|
+
KeyRequest<
|
|
550
|
+
K,
|
|
551
|
+
Narrow<Item<GraphQL.Result<Op>, P>, T>,
|
|
552
|
+
GraphQL.Error<Op> | Cause.NoSuchElementError,
|
|
553
|
+
GraphQL.Services<Op>
|
|
554
|
+
>
|
|
555
|
+
> => {
|
|
556
|
+
const path = options.path as ReadonlyArray<string>
|
|
557
|
+
const codec = internalGraphQL.makeCodec(method.operation)
|
|
558
|
+
return makeResolver(
|
|
559
|
+
options.batchKey,
|
|
560
|
+
(entries) =>
|
|
561
|
+
Effect.flatMap(callBatch(method, entries, options.variables), ({ keys, targets, result }) => {
|
|
562
|
+
const byIndex = new Map<number, Arr.NonEmptyArray<GraphQLError>>()
|
|
563
|
+
for (const error of result.errors) {
|
|
564
|
+
const index = entryIndex(error, path, keys.length)
|
|
565
|
+
if (index === undefined) return batchError(codec, result)
|
|
566
|
+
const errors = byIndex.get(index)
|
|
567
|
+
if (errors === undefined) byIndex.set(index, [error])
|
|
568
|
+
else errors.push(error)
|
|
569
|
+
}
|
|
570
|
+
const list = findList(result.data, path)
|
|
571
|
+
// An error in a non-null item nulls the whole list, so every entry lost its data to it.
|
|
572
|
+
if (list === undefined) return result.errors.length > 0 ? batchError(codec, result) : completeAll(targets)
|
|
573
|
+
if (list.truncated) return Effect.fail(codec.fail(truncated(path)))
|
|
574
|
+
if (list.items.length !== keys.length) {
|
|
575
|
+
return Effect.fail(codec.fail(
|
|
576
|
+
new DecodeError({
|
|
577
|
+
description: `Expected ${keys.length} entries at ${path.join(".")}, received ${list.items.length}`
|
|
578
|
+
})
|
|
579
|
+
))
|
|
580
|
+
}
|
|
581
|
+
const response = internalGraphQL.partialResponses.get(result)
|
|
582
|
+
for (let i = 0; i < targets.length; i++) {
|
|
583
|
+
const errors = byIndex.get(i)
|
|
584
|
+
const item = list.items[i]
|
|
585
|
+
targets[i].completeUnsafe(
|
|
586
|
+
errors !== undefined
|
|
587
|
+
? Exit.fail(codec.fail(
|
|
588
|
+
internalGraphQL.responseError({ status: response?.status, headers: response?.headers }, errors)
|
|
589
|
+
))
|
|
590
|
+
: matchesTypename(item, options.typename)
|
|
591
|
+
? Exit.succeed(item)
|
|
592
|
+
: constNoSuchElement
|
|
593
|
+
)
|
|
594
|
+
}
|
|
595
|
+
return Effect.void
|
|
596
|
+
})
|
|
597
|
+
)
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
/**
|
|
601
|
+
* Batches lookups by key for searches and collections that return results
|
|
602
|
+
* in any order.
|
|
603
|
+
*
|
|
604
|
+
* **Details**
|
|
605
|
+
*
|
|
606
|
+
* Write `key` before `variables` to infer the key type from its return type.
|
|
607
|
+
* `variables` maps batch keys to operation variables. Keys are compared with
|
|
608
|
+
* `Equal` and `Hash`. `path` and `typename` work as in {@link ordered};
|
|
609
|
+
* `key` receives the narrowed item type.
|
|
610
|
+
*
|
|
611
|
+
* Missing keys, null parents, pagination and `batchKey` behave as in
|
|
612
|
+
* {@link ordered}.
|
|
613
|
+
* Any GraphQL error fails the batch with the same `ResponseError` as a
|
|
614
|
+
* non-partial call, since error paths cannot be matched to keys.
|
|
615
|
+
*
|
|
616
|
+
* **Example** (Finding repositories through search)
|
|
617
|
+
*
|
|
618
|
+
* ```ts import.meta.vitest
|
|
619
|
+
* import { Effect, Layer, Schema, Stream } from "effect"
|
|
620
|
+
* import { GraphQL, GraphQLClient, GraphQLGroup, GraphQLProtocol, GraphQLResolver } from "effect/graphql"
|
|
621
|
+
*
|
|
622
|
+
* const Repository = Schema.Struct({ __typename: Schema.Literal("Repository"), nameWithOwner: Schema.String })
|
|
623
|
+
* const User = Schema.Struct({ __typename: Schema.Literal("User"), login: Schema.String })
|
|
624
|
+
*
|
|
625
|
+
* const SearchRepos = GraphQL.query("SearchRepos", {
|
|
626
|
+
* document: "query SearchRepos($query:String!){search(query:$query,type:REPOSITORY,first:100){pageInfo{hasNextPage} nodes{__typename ...on Repository{nameWithOwner} ...on User{login}}}}",
|
|
627
|
+
* variables: { query: Schema.String },
|
|
628
|
+
* result: Schema.Struct({
|
|
629
|
+
* search: Schema.Struct({
|
|
630
|
+
* pageInfo: Schema.Struct({ hasNextPage: Schema.Boolean }),
|
|
631
|
+
* nodes: Schema.NullOr(Schema.Array(Schema.NullOr(Schema.Union([Repository, User]))))
|
|
632
|
+
* })
|
|
633
|
+
* })
|
|
634
|
+
* })
|
|
635
|
+
*
|
|
636
|
+
* const Scripted = Layer.succeed(GraphQLProtocol.GraphQLProtocol, {
|
|
637
|
+
* execute: (request) => {
|
|
638
|
+
* const { query } = request.variables as { query: string }
|
|
639
|
+
* const nodes = query.split(" ").map((term) => ({ __typename: "Repository", nameWithOwner: term.slice(5) }))
|
|
640
|
+
* return Effect.succeed({ body: { data: { search: { pageInfo: { hasNextPage: false }, nodes: nodes.reverse() } } } })
|
|
641
|
+
* },
|
|
642
|
+
* subscribe: () => Stream.empty
|
|
643
|
+
* })
|
|
644
|
+
*
|
|
645
|
+
* const program = Effect.gen(function*() {
|
|
646
|
+
* const client = yield* GraphQLClient.make(GraphQLGroup.make(SearchRepos))
|
|
647
|
+
* const RepoByName = GraphQLResolver.findById(client.SearchRepos, {
|
|
648
|
+
* key: (repo) => repo.nameWithOwner,
|
|
649
|
+
* variables: (names) => ({ query: names.map((name) => `repo:${name}`).join(" ") }),
|
|
650
|
+
* path: ["search", "nodes"],
|
|
651
|
+
* typename: "Repository"
|
|
652
|
+
* })
|
|
653
|
+
* const repos = yield* Effect.forEach(
|
|
654
|
+
* ["Effect-TS/effect", "Effect-TS/website"],
|
|
655
|
+
* GraphQLResolver.request(RepoByName),
|
|
656
|
+
* { concurrency: "unbounded" }
|
|
657
|
+
* )
|
|
658
|
+
* return repos.map((repo) => repo.nameWithOwner)
|
|
659
|
+
* })
|
|
660
|
+
*
|
|
661
|
+
* await Effect.runPromise(program.pipe(Effect.provide(Scripted))) // => ["Effect-TS/effect", "Effect-TS/website"]
|
|
662
|
+
* ```
|
|
663
|
+
*
|
|
664
|
+
* @stability experimental
|
|
665
|
+
* @category resolvers
|
|
666
|
+
* @since 4.0.0
|
|
667
|
+
*/
|
|
668
|
+
export const findById = <
|
|
669
|
+
Op extends GraphQL.Any,
|
|
670
|
+
K,
|
|
671
|
+
const P extends ReadonlyArray<string>,
|
|
672
|
+
T extends Typenames<Item<GraphQL.Result<Op>, P>> = never
|
|
673
|
+
>(
|
|
674
|
+
method: OperationMethod<Op>,
|
|
675
|
+
options: {
|
|
676
|
+
readonly variables: (keys: ReadonlyArray<K>) => GraphQL.Variables<Op>
|
|
677
|
+
readonly path: Path<GraphQL.Result<Op>, P>
|
|
678
|
+
readonly key: (item: Narrow<Item<GraphQL.Result<Op>, P>, T>) => K
|
|
679
|
+
readonly typename?: T | undefined
|
|
680
|
+
} & BatchKey<Op>
|
|
681
|
+
): RequestResolver.RequestResolver<
|
|
682
|
+
KeyRequest<
|
|
683
|
+
K,
|
|
684
|
+
Narrow<Item<GraphQL.Result<Op>, P>, T>,
|
|
685
|
+
GraphQL.Error<Op> | Cause.NoSuchElementError,
|
|
686
|
+
GraphQL.Services<Op>
|
|
687
|
+
>
|
|
688
|
+
> => {
|
|
689
|
+
const path = options.path as ReadonlyArray<string>
|
|
690
|
+
const codec = internalGraphQL.makeCodec(method.operation)
|
|
691
|
+
return makeResolver(
|
|
692
|
+
options.batchKey,
|
|
693
|
+
(entries) =>
|
|
694
|
+
Effect.flatMap(callBatch(method, entries, options.variables), ({ keys, targets, result }) => {
|
|
695
|
+
if (result.errors.length > 0) return batchError(codec, result)
|
|
696
|
+
const list = findList(result.data, path)
|
|
697
|
+
if (list === undefined) return completeAll(targets)
|
|
698
|
+
if (list.truncated) return Effect.fail(codec.fail(truncated(path)))
|
|
699
|
+
const pending = MutableHashMap.empty<K, Request.Entry<any>>()
|
|
700
|
+
for (let i = 0; i < keys.length; i++) MutableHashMap.set(pending, keys[i], targets[i])
|
|
701
|
+
for (const item of list.items) {
|
|
702
|
+
if (!matchesTypename(item, options.typename)) continue
|
|
703
|
+
const key = options.key(item as Narrow<Item<GraphQL.Result<Op>, P>, T>)
|
|
704
|
+
const target = MutableHashMap.get(pending, key)
|
|
705
|
+
if (target._tag === "None") continue
|
|
706
|
+
MutableHashMap.remove(pending, key)
|
|
707
|
+
target.value.completeUnsafe(Exit.succeed(item))
|
|
708
|
+
}
|
|
709
|
+
MutableHashMap.forEach(pending, (target) => target.completeUnsafe(constNoSuchElement))
|
|
710
|
+
return Effect.void
|
|
711
|
+
})
|
|
712
|
+
)
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
/**
|
|
716
|
+
* Batches calls to a generated query or mutation by repeating the operation
|
|
717
|
+
* under aliases in one request.
|
|
718
|
+
*
|
|
719
|
+
* **When to use**
|
|
720
|
+
*
|
|
721
|
+
* Use when the API has no list-key field, such as GitHub's pull requests by
|
|
722
|
+
* repository and number. Otherwise, {@link ordered} or {@link findById} send
|
|
723
|
+
* a smaller query.
|
|
724
|
+
*
|
|
725
|
+
* **Details**
|
|
726
|
+
*
|
|
727
|
+
* Use {@link request} to get `(variables) => Effect`. Variables that encode
|
|
728
|
+
* to the same JSON share a slice; each slice uses the operation's result Schema.
|
|
729
|
+
* Throws when the resolver is built if the operation has no document
|
|
730
|
+
* template, if an operation directive references a variable, or if a root
|
|
731
|
+
* selection is a fragment spread or inline fragment, since none of these can
|
|
732
|
+
* be repeated under aliases.
|
|
733
|
+
*
|
|
734
|
+
* Batches use `POST` even with `queryMethod: "GET"`. The default batch size
|
|
735
|
+
* is 10; change it with `RequestResolver.batchN`. Middleware run once per
|
|
736
|
+
* batch, and `batchKey` works as in {@link ordered}. Mock and custom methods
|
|
737
|
+
* are called once per slice instead.
|
|
738
|
+
*
|
|
739
|
+
* Errors with a matching `path[0]` fail only that slice, with the alias prefix
|
|
740
|
+
* removed from the error path. Errors without a matching path, transport errors
|
|
741
|
+
* and middleware failures fail the batch.
|
|
742
|
+
*
|
|
743
|
+
* **Gotchas**
|
|
744
|
+
*
|
|
745
|
+
* An error under a non-null root field can null the entire response, failing
|
|
746
|
+
* every slice. GitHub's `repository` and `pullRequest` are nullable.
|
|
747
|
+
*
|
|
748
|
+
* Middleware that hash queries must use `request.query`, not
|
|
749
|
+
* `operation.document`. Trusted-document allowlists don't support batching;
|
|
750
|
+
* query hashing does, since the same operation and slice count produce the
|
|
751
|
+
* same document.
|
|
752
|
+
*
|
|
753
|
+
* Mutations are allowed, but the caller cannot control root-field order.
|
|
754
|
+
*
|
|
755
|
+
* **Example** (Looking up pull requests by number)
|
|
756
|
+
*
|
|
757
|
+
* ```ts import.meta.vitest
|
|
758
|
+
* import { Effect, Layer, RequestResolver, Schema, Stream } from "effect"
|
|
759
|
+
* import { GraphQL, GraphQLClient, GraphQLGroup, GraphQLProtocol, GraphQLResolver } from "effect/graphql"
|
|
760
|
+
*
|
|
761
|
+
* // Generated from:
|
|
762
|
+
* // query PullRequest($owner: String!, $name: String!, $number: Int!) {
|
|
763
|
+
* // repository(owner: $owner, name: $name) { pullRequest(number: $number) { title } }
|
|
764
|
+
* // }
|
|
765
|
+
* const PullRequest = GraphQL.query("PullRequest", {
|
|
766
|
+
* document: {
|
|
767
|
+
* variables: [
|
|
768
|
+
* { name: "owner", body: "String!" },
|
|
769
|
+
* { name: "name", body: "String!" },
|
|
770
|
+
* { name: "number", body: "Int!" }
|
|
771
|
+
* ],
|
|
772
|
+
* selections: [{
|
|
773
|
+
* name: "repository",
|
|
774
|
+
* body: ["(owner:$", "owner", ",name:$", "name", "){pullRequest(number:$", "number", "){title}}"]
|
|
775
|
+
* }],
|
|
776
|
+
* fragments: []
|
|
777
|
+
* },
|
|
778
|
+
* variables: { owner: Schema.String, name: Schema.String, number: Schema.Int },
|
|
779
|
+
* result: Schema.Struct({
|
|
780
|
+
* repository: Schema.NullOr(Schema.Struct({
|
|
781
|
+
* pullRequest: Schema.NullOr(Schema.Struct({ title: Schema.String }))
|
|
782
|
+
* }))
|
|
783
|
+
* })
|
|
784
|
+
* })
|
|
785
|
+
*
|
|
786
|
+
* // A stand-in server that answers every aliased slice
|
|
787
|
+
* const queries: Array<string> = []
|
|
788
|
+
* const Scripted = Layer.succeed(GraphQLProtocol.GraphQLProtocol, {
|
|
789
|
+
* execute: (request) => {
|
|
790
|
+
* queries.push(request.query)
|
|
791
|
+
* const data: Record<string, unknown> = {}
|
|
792
|
+
* for (const [key, number] of Object.entries(request.variables as Record<string, unknown>)) {
|
|
793
|
+
* const prefix = /^(_\d+_)number$/.exec(key)?.[1]
|
|
794
|
+
* if (prefix !== undefined) data[`${prefix}repository`] = { pullRequest: { title: `PR ${number}` } }
|
|
795
|
+
* }
|
|
796
|
+
* return Effect.succeed({ body: { data } })
|
|
797
|
+
* },
|
|
798
|
+
* subscribe: () => Stream.empty
|
|
799
|
+
* })
|
|
800
|
+
*
|
|
801
|
+
* const program = Effect.gen(function*() {
|
|
802
|
+
* const github = yield* GraphQLClient.make(GraphQLGroup.make(PullRequest))
|
|
803
|
+
* const PullRequests = GraphQLResolver.aliased(github.PullRequest).pipe(RequestResolver.batchN(20))
|
|
804
|
+
* const getPullRequest = GraphQLResolver.request(PullRequests)
|
|
805
|
+
* const results = yield* Effect.forEach(
|
|
806
|
+
* [1, 2, 3],
|
|
807
|
+
* (number) => getPullRequest({ owner: "Effect-TS", name: "effect", number }),
|
|
808
|
+
* { concurrency: "unbounded" }
|
|
809
|
+
* )
|
|
810
|
+
* return [results.map((result) => result.repository?.pullRequest?.title), queries.length]
|
|
811
|
+
* })
|
|
812
|
+
*
|
|
813
|
+
* await Effect.runPromise(program.pipe(Effect.provide(Scripted))) // => [["PR 1", "PR 2", "PR 3"], 1]
|
|
814
|
+
* ```
|
|
815
|
+
*
|
|
816
|
+
* @stability experimental
|
|
817
|
+
* @category resolvers
|
|
818
|
+
* @since 4.0.0
|
|
819
|
+
*/
|
|
820
|
+
export const aliased = <Op extends GraphQL.Any>(
|
|
821
|
+
method: OperationMethod<Op>,
|
|
822
|
+
...[options]: {} extends BatchKey<Op> ? [options?: BatchKey<Op>] : [options: BatchKey<Op>]
|
|
823
|
+
): RequestResolver.RequestResolver<AliasedRequest<Op>> => {
|
|
824
|
+
const operation = method.operation
|
|
825
|
+
const template = operation.template
|
|
826
|
+
if (template === undefined) {
|
|
827
|
+
throw new Error(`GraphQLResolver.aliased: operation ${operation.name} has no document template`)
|
|
828
|
+
}
|
|
829
|
+
const unsliceable = internalGraphQL.templateUnsliceableReason(template)
|
|
830
|
+
if (unsliceable !== undefined) {
|
|
831
|
+
throw new Error(`GraphQLResolver.aliased: cannot batch operation ${operation.name}: ${unsliceable}`)
|
|
832
|
+
}
|
|
833
|
+
const codec = internalGraphQL.makeCodec(operation)
|
|
834
|
+
// The registered hook uses this operation's middleware errors and services.
|
|
835
|
+
const execute = internalGraphQL.rawExecutors.get(method) as
|
|
836
|
+
| ((request: GraphQLRequest) => Effect.Effect<ExecutionResult, GraphQL.Error<Op>, GraphQL.Services<Op>>)
|
|
837
|
+
| undefined
|
|
838
|
+
// Generic conditional parameters prevent calling the strict overload directly.
|
|
839
|
+
const call = method as unknown as (
|
|
840
|
+
variables: GraphQL.Variables<Op>
|
|
841
|
+
) => Effect.Effect<GraphQL.Result<Op>, GraphQL.Error<Op>, GraphQL.Services<Op>>
|
|
842
|
+
|
|
843
|
+
return makeResolver<AliasedRequest<Op>>(options?.batchKey, (entries) =>
|
|
844
|
+
Effect.flatMap(
|
|
845
|
+
Effect.forEach(entries, (entry) => Effect.exit(codec.encodeVariables(entry.request.key))),
|
|
846
|
+
(encoded) => {
|
|
847
|
+
const slices: Array<Slice<Op>> = []
|
|
848
|
+
const byJson = new Map<string, Slice<Op>>()
|
|
849
|
+
for (let i = 0; i < entries.length; i++) {
|
|
850
|
+
const exit = encoded[i]
|
|
851
|
+
if (exit._tag === "Failure") {
|
|
852
|
+
entries[i].completeUnsafe(exit)
|
|
853
|
+
continue
|
|
854
|
+
}
|
|
855
|
+
const json = internalGraphQL.canonicalJson(exit.value)
|
|
856
|
+
const slice = byJson.get(json)
|
|
857
|
+
if (slice !== undefined) {
|
|
858
|
+
slice.entries.push(entries[i])
|
|
859
|
+
continue
|
|
860
|
+
}
|
|
861
|
+
const created = { variables: entries[i].request.key, encoded: exit.value, entries: [entries[i]] }
|
|
862
|
+
byJson.set(json, created)
|
|
863
|
+
slices.push(created)
|
|
864
|
+
}
|
|
865
|
+
const complete = <R>(slice: Slice<Op>, effect: Effect.Effect<GraphQL.Result<Op>, GraphQL.Error<Op>, R>) =>
|
|
866
|
+
Effect.map(Effect.exit(effect), (exit) => {
|
|
867
|
+
for (const entry of slice.entries) entry.completeUnsafe(exit)
|
|
868
|
+
})
|
|
869
|
+
if (execute === undefined) {
|
|
870
|
+
return Effect.forEach(slices, (slice) => complete(slice, call(slice.variables)), { discard: true })
|
|
871
|
+
}
|
|
872
|
+
if (!Arr.isReadonlyArrayNonEmpty(slices)) return Effect.void
|
|
873
|
+
const prefixes = Arr.map(slices, (_, i) => `_${i}_`)
|
|
874
|
+
return execute({
|
|
875
|
+
kind: operation.kind,
|
|
876
|
+
query: internalGraphQL.renderSlices(operation.kind, operation.name, template, prefixes),
|
|
877
|
+
operationName: operation.name,
|
|
878
|
+
variables: Object.fromEntries(
|
|
879
|
+
slices.flatMap((slice, i) =>
|
|
880
|
+
Object.entries(slice.encoded ?? {}).map(([name, value]) => [prefixes[i] + name, value])
|
|
881
|
+
)
|
|
882
|
+
),
|
|
883
|
+
headers: Headers.empty,
|
|
884
|
+
urlParams: UrlParams.empty
|
|
885
|
+
}).pipe(
|
|
886
|
+
Effect.flatMap((result) => {
|
|
887
|
+
const results = internalGraphQL.splitSlices(result, template, prefixes)
|
|
888
|
+
return results === undefined
|
|
889
|
+
? codec.failResponse(result)
|
|
890
|
+
: Effect.forEach(slices, (slice, i) => complete(slice, codec.decodeStrict(results[i])), { discard: true })
|
|
891
|
+
})
|
|
892
|
+
)
|
|
893
|
+
}
|
|
894
|
+
).pipe(Effect.provideContext(entries[0].context))).pipe(RequestResolver.batchN(10))
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
type AliasedRequest<Op extends GraphQL.Any> = KeyRequest<
|
|
898
|
+
GraphQL.Variables<Op>,
|
|
899
|
+
GraphQL.Result<Op>,
|
|
900
|
+
GraphQL.Error<Op>,
|
|
901
|
+
GraphQL.Services<Op>
|
|
902
|
+
>
|
|
903
|
+
|
|
904
|
+
interface Slice<Op extends GraphQL.Any> {
|
|
905
|
+
readonly variables: GraphQL.Variables<Op>
|
|
906
|
+
readonly encoded: unknown
|
|
907
|
+
readonly entries: Array<Request.Entry<AliasedRequest<Op>>>
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
// -----------------------------------------------------------------------------
|
|
911
|
+
// Internals
|
|
912
|
+
// -----------------------------------------------------------------------------
|
|
913
|
+
|
|
914
|
+
const constNoSuchElement = Exit.fail(new Cause.NoSuchElementError())
|
|
915
|
+
|
|
916
|
+
/**
|
|
917
|
+
* Without `batchKey`, all entries share one batch. With it, each batch holds
|
|
918
|
+
* entries with equal keys, so the first entry's context stands for the batch.
|
|
919
|
+
*/
|
|
920
|
+
const makeResolver = <A extends Request.Any>(
|
|
921
|
+
batchKey: ((context: Context.Context<any>) => unknown) | undefined,
|
|
922
|
+
runAll: (entries: Arr.NonEmptyArray<Request.Entry<A>>) => Effect.Effect<void, Request.Error<A>>
|
|
923
|
+
): RequestResolver.RequestResolver<A> =>
|
|
924
|
+
batchKey === undefined
|
|
925
|
+
? RequestResolver.make(runAll)
|
|
926
|
+
: RequestResolver.makeGrouped({ key: (entry) => batchKey(entry.context), resolver: runAll })
|
|
927
|
+
|
|
928
|
+
/**
|
|
929
|
+
* Calls the method in the first entry's context with deduplicated keys.
|
|
930
|
+
* Each target completes all entries sharing its key.
|
|
931
|
+
*/
|
|
932
|
+
const callBatch = <Op extends GraphQL.Any, K>(
|
|
933
|
+
method: OperationMethod<Op>,
|
|
934
|
+
entries: Arr.NonEmptyArray<Request.Entry<KeyRequest<K, any, any, any>>>,
|
|
935
|
+
variables: (keys: ReadonlyArray<K>) => GraphQL.Variables<Op>
|
|
936
|
+
) => {
|
|
937
|
+
const keys: Array<K> = []
|
|
938
|
+
const targets: Array<Request.Entry<KeyRequest<K, any, any, any>>> = []
|
|
939
|
+
const indices = MutableHashMap.empty<K, number>()
|
|
940
|
+
for (const entry of entries) {
|
|
941
|
+
const index = MutableHashMap.get(indices, entry.request.key)
|
|
942
|
+
if (index._tag === "None") {
|
|
943
|
+
MutableHashMap.set(indices, entry.request.key, keys.length)
|
|
944
|
+
keys.push(entry.request.key)
|
|
945
|
+
targets.push(entry)
|
|
946
|
+
continue
|
|
947
|
+
}
|
|
948
|
+
const previous = targets[index.value]
|
|
949
|
+
targets[index.value] = {
|
|
950
|
+
...previous,
|
|
951
|
+
completeUnsafe(exit) {
|
|
952
|
+
previous.completeUnsafe(exit)
|
|
953
|
+
entry.completeUnsafe(exit)
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
// Generic conditional parameters prevent calling the partial overload directly.
|
|
958
|
+
const call = method as unknown as (
|
|
959
|
+
variables: GraphQL.Variables<Op>,
|
|
960
|
+
options: { readonly partial: true }
|
|
961
|
+
) => Effect.Effect<PartialResult<GraphQL.Result<Op>>, GraphQL.Error<Op>, GraphQL.Services<Op>>
|
|
962
|
+
return call(variables(keys), { partial: true }).pipe(
|
|
963
|
+
Effect.map((result) => ({ keys, targets, result })),
|
|
964
|
+
Effect.provideContext(entries[0].context)
|
|
965
|
+
)
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
// Fails the batch with the response's errors and transport metadata.
|
|
969
|
+
const batchError = (
|
|
970
|
+
codec: { readonly failResponse: (result: ExecutionResult) => Effect.Effect<never, GraphQLClientError> },
|
|
971
|
+
result: PartialResult<unknown>
|
|
972
|
+
) => codec.failResponse(internalGraphQL.partialResponses.get(result) ?? { errors: result.errors })
|
|
973
|
+
|
|
974
|
+
const truncated = (path: ReadonlyArray<string>) =>
|
|
975
|
+
new DecodeError({
|
|
976
|
+
description: `pageInfo.hasNextPage is true next to ${
|
|
977
|
+
path.join(".")
|
|
978
|
+
}, so results beyond the page would be reported missing. Make the page size at least the RequestResolver.batchN size`
|
|
979
|
+
})
|
|
980
|
+
|
|
981
|
+
const completeAll = (targets: ReadonlyArray<Request.Entry<any>>) => {
|
|
982
|
+
for (const target of targets) target.completeUnsafe(constNoSuchElement)
|
|
983
|
+
return Effect.void
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
const entryIndex = (error: GraphQLError, path: ReadonlyArray<string>, length: number): number | undefined => {
|
|
987
|
+
const errorPath = error.path
|
|
988
|
+
if (errorPath === undefined || errorPath.length <= path.length) return undefined
|
|
989
|
+
for (let i = 0; i < path.length; i++) {
|
|
990
|
+
if (errorPath[i] !== path[i]) return undefined
|
|
991
|
+
}
|
|
992
|
+
const index = errorPath[path.length]
|
|
993
|
+
return typeof index === "number" && Number.isInteger(index) && index >= 0 && index < length ? index : undefined
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
const findList = (
|
|
997
|
+
data: unknown,
|
|
998
|
+
path: ReadonlyArray<string>
|
|
999
|
+
): { readonly items: ReadonlyArray<unknown>; readonly truncated: boolean } | undefined => {
|
|
1000
|
+
// Path guarantees object fields leading to a list.
|
|
1001
|
+
let parent = data as Record<string, any> | null | undefined
|
|
1002
|
+
for (let i = 0; i < path.length - 1; i++) parent = parent?.[path[i]]
|
|
1003
|
+
const items = parent?.[path[path.length - 1]] as ReadonlyArray<unknown> | null | undefined
|
|
1004
|
+
if (items === null || items === undefined) return undefined
|
|
1005
|
+
return { items, truncated: parent!.pageInfo?.hasNextPage === true }
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
const matchesTypename = (item: unknown, typename: string | undefined): boolean =>
|
|
1009
|
+
item !== null && item !== undefined &&
|
|
1010
|
+
(typename === undefined || (item as { readonly __typename?: unknown }).__typename === typename)
|