Last active
April 2, 2024 21:42
-
-
Save tim-smart/e10e4cbaeff35242d8352adead30bef9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as Http from "@effect/platform/HttpClient" | |
import { Context, Effect, Layer, pipe } from "effect" | |
const headers = { | |
Accept: | |
"application/graphql-response+json; charset=utf-8, application/json; charset=utf-8", | |
"Content-Type": "application/json", | |
} | |
export class GraphQLClient extends Context.Tag("graphql-codegen/GraphQLClient")< | |
GraphQLClient, | |
Http.client.Client< | |
never, | |
Http.error.HttpClientError | "missing", | |
{ | |
readonly headers: Http.headers.Headers | |
readonly body: any | |
} | |
> | |
>() { | |
static fromDefaultClient( | |
client: Http.client.Client.Default, | |
): Layer.Layer<GraphQLClient> { | |
return Layer.succeed( | |
GraphQLClient, | |
pipe( | |
client, | |
Http.client.mapRequest(Http.request.setHeaders(headers)), | |
Http.client.filterStatusOk, | |
Http.client.mapEffectScoped((res) => | |
Effect.flatMap(res.json, (_) => { | |
const body = _ as any | |
return body.data | |
? Effect.succeed(body.data) | |
: Effect.fail("missing" as const) | |
}), | |
), | |
), | |
) | |
} | |
static Live: Layer.Layer<GraphQLClient, never, Http.client.Client.Default> = | |
Layer.unwrapEffect( | |
Effect.map(Http.client.Client, GraphQLClient.fromDefaultClient), | |
) | |
static fromEndpoint( | |
endpoint: string, | |
): Layer.Layer<GraphQLClient, never, Http.client.Client.Default> { | |
return Layer.unwrapEffect( | |
Effect.map(Http.client.Client, (client) => | |
GraphQLClient.fromDefaultClient( | |
Http.client.mapRequest(client, Http.request.prependUrl(endpoint)), | |
), | |
), | |
) | |
} | |
} | |
const endpoint = ({ query, operationName, variables }: any) => | |
Effect.flatMap(GraphQLClient, (client) => | |
pipe( | |
Http.request.post(""), | |
Http.request.jsonBody({ | |
query, | |
operationName, | |
variables, | |
}), | |
Effect.flatMap(client), | |
), | |
) | |
endpoint({}).pipe( | |
Effect.provide( | |
GraphQLClient.fromEndpoint("https://api.github.com/graphql").pipe( | |
Layer.provide(Http.client.layer), | |
), | |
), | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment