@effect-gql/express 0.1.0 → 1.0.0

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/src/middleware.ts DELETED
@@ -1,65 +0,0 @@
1
- import { Layer } from "effect"
2
- import { HttpApp, HttpRouter } from "@effect/platform"
3
- import type { Request, Response, NextFunction, RequestHandler } from "express"
4
- import { toWebHeaders } from "./http-utils"
5
-
6
- /**
7
- * Convert an HttpRouter to Express middleware.
8
- *
9
- * This creates Express-compatible middleware that can be mounted on any Express app.
10
- * The middleware converts Express requests to web standard Requests, processes them
11
- * through the Effect router, and writes the response back to Express.
12
- *
13
- * @param router - The HttpRouter to convert (typically from makeGraphQLRouter or toRouter)
14
- * @param layer - Layer providing any services required by the router
15
- * @returns Express middleware function
16
- *
17
- * @example
18
- * ```typescript
19
- * import express from "express"
20
- * import { makeGraphQLRouter } from "@effect-gql/core"
21
- * import { toMiddleware } from "@effect-gql/express"
22
- * import { Layer } from "effect"
23
- *
24
- * const router = makeGraphQLRouter(schema, Layer.empty, { graphiql: true })
25
- *
26
- * const app = express()
27
- * app.use(toMiddleware(router, Layer.empty))
28
- * app.listen(4000, () => console.log("Server running on http://localhost:4000"))
29
- * ```
30
- */
31
- export const toMiddleware = <E, R, RE>(
32
- router: HttpRouter.HttpRouter<E, R>,
33
- layer: Layer.Layer<R, RE>
34
- ): RequestHandler => {
35
- const { handler } = HttpApp.toWebHandlerLayer(router, layer)
36
-
37
- return async (req: Request, res: Response, next: NextFunction) => {
38
- try {
39
- // Convert Express request to web standard Request
40
- // Use URL constructor for safe URL parsing (avoids Host header injection)
41
- const baseUrl = `${req.protocol}://${req.hostname}`
42
- const url = new URL(req.originalUrl || "/", baseUrl).href
43
- const headers = toWebHeaders(req.headers)
44
-
45
- const webRequest = new Request(url, {
46
- method: req.method,
47
- headers,
48
- body: ["GET", "HEAD"].includes(req.method) ? undefined : JSON.stringify(req.body),
49
- })
50
-
51
- // Process through Effect handler
52
- const webResponse = await handler(webRequest)
53
-
54
- // Write response back to Express
55
- res.status(webResponse.status)
56
- webResponse.headers.forEach((value, key) => {
57
- res.setHeader(key, value)
58
- })
59
- const body = await webResponse.text()
60
- res.send(body)
61
- } catch (error) {
62
- next(error)
63
- }
64
- }
65
- }
package/src/sse.ts DELETED
@@ -1,285 +0,0 @@
1
- import { Effect, Layer, Stream, Deferred } from "effect"
2
- import type { Request, Response, NextFunction, RequestHandler } from "express"
3
- import { GraphQLSchema } from "graphql"
4
- import {
5
- makeGraphQLSSEHandler,
6
- formatSSEMessage,
7
- SSE_HEADERS,
8
- type GraphQLSSEOptions,
9
- type SSESubscriptionRequest,
10
- SSEError,
11
- } from "@effect-gql/core"
12
- import { toWebHeaders } from "./http-utils"
13
-
14
- /**
15
- * Options for Express SSE middleware
16
- */
17
- export interface ExpressSSEOptions<R> extends GraphQLSSEOptions<R> {
18
- /**
19
- * Path for SSE connections.
20
- * @default "/graphql/stream"
21
- */
22
- readonly path?: string
23
- }
24
-
25
- /**
26
- * Create an Express middleware for SSE subscriptions.
27
- *
28
- * This middleware handles POST requests to the configured path and streams
29
- * GraphQL subscription events as Server-Sent Events.
30
- *
31
- * @param schema - The GraphQL schema with subscription definitions
32
- * @param layer - Effect layer providing services required by resolvers
33
- * @param options - Optional lifecycle hooks and configuration
34
- * @returns An Express middleware function
35
- *
36
- * @example
37
- * ```typescript
38
- * import express from "express"
39
- * import { createServer } from "node:http"
40
- * import { toMiddleware, sseMiddleware, attachWebSocket } from "@effect-gql/express"
41
- * import { makeGraphQLRouter } from "@effect-gql/core"
42
- *
43
- * const app = express()
44
- * app.use(express.json())
45
- *
46
- * // Regular GraphQL endpoint
47
- * const router = makeGraphQLRouter(schema, Layer.empty, { graphiql: true })
48
- * app.use(toMiddleware(router, Layer.empty))
49
- *
50
- * // SSE subscriptions endpoint
51
- * app.use(sseMiddleware(schema, Layer.empty, {
52
- * path: "/graphql/stream",
53
- * onConnect: (request, headers) => Effect.gen(function* () {
54
- * const token = headers.get("authorization")
55
- * const user = yield* AuthService.validateToken(token)
56
- * return { user }
57
- * }),
58
- * }))
59
- *
60
- * const server = createServer(app)
61
- *
62
- * // Optional: Also attach WebSocket subscriptions
63
- * attachWebSocket(server, schema, Layer.empty)
64
- *
65
- * server.listen(4000)
66
- * ```
67
- */
68
- export const sseMiddleware = <R>(
69
- schema: GraphQLSchema,
70
- layer: Layer.Layer<R>,
71
- options?: ExpressSSEOptions<R>
72
- ): RequestHandler => {
73
- const path = options?.path ?? "/graphql/stream"
74
- const sseHandler = makeGraphQLSSEHandler(schema, layer, options)
75
-
76
- return async (req: Request, res: Response, next: NextFunction): Promise<void> => {
77
- // Check if this request is for our path
78
- if (req.path !== path) {
79
- next()
80
- return
81
- }
82
-
83
- // Only handle POST requests
84
- if (req.method !== "POST") {
85
- next()
86
- return
87
- }
88
-
89
- // Check Accept header for SSE support
90
- const accept = req.headers.accept ?? ""
91
- if (!accept.includes("text/event-stream") && !accept.includes("*/*")) {
92
- res.status(406).json({
93
- errors: [{ message: "Client must accept text/event-stream" }],
94
- })
95
- return
96
- }
97
-
98
- // Parse the GraphQL request from the body
99
- let subscriptionRequest: SSESubscriptionRequest
100
- try {
101
- const body = req.body as Record<string, unknown>
102
- if (typeof body.query !== "string") {
103
- throw new Error("Missing query")
104
- }
105
- subscriptionRequest = {
106
- query: body.query,
107
- variables: body.variables as Record<string, unknown> | undefined,
108
- operationName: body.operationName as string | undefined,
109
- extensions: body.extensions as Record<string, unknown> | undefined,
110
- }
111
- } catch {
112
- res.status(400).json({
113
- errors: [{ message: "Invalid GraphQL request body" }],
114
- })
115
- return
116
- }
117
-
118
- // Convert Express headers to web Headers
119
- const headers = toWebHeaders(req.headers)
120
-
121
- // Set SSE headers
122
- res.writeHead(200, SSE_HEADERS)
123
-
124
- // Get the event stream
125
- const eventStream = sseHandler(subscriptionRequest, headers)
126
-
127
- // Create the streaming effect
128
- const streamEffect = Effect.gen(function* () {
129
- // Track client disconnection
130
- const clientDisconnected = yield* Deferred.make<void, SSEError>()
131
-
132
- req.on("close", () => {
133
- Effect.runPromise(Deferred.succeed(clientDisconnected, undefined)).catch(() => {})
134
- })
135
-
136
- req.on("error", (error) => {
137
- Effect.runPromise(Deferred.fail(clientDisconnected, new SSEError({ cause: error }))).catch(
138
- () => {}
139
- )
140
- })
141
-
142
- // Stream events to the client
143
- const runStream = Stream.runForEach(eventStream, (event) =>
144
- Effect.async<void, SSEError>((resume) => {
145
- const message = formatSSEMessage(event)
146
- res.write(message, (error) => {
147
- if (error) {
148
- resume(Effect.fail(new SSEError({ cause: error })))
149
- } else {
150
- resume(Effect.succeed(undefined))
151
- }
152
- })
153
- })
154
- )
155
-
156
- // Race between stream completion and client disconnection
157
- yield* Effect.race(
158
- runStream.pipe(Effect.catchAll((error) => Effect.logWarning("SSE stream error", error))),
159
- Deferred.await(clientDisconnected)
160
- )
161
- })
162
-
163
- await Effect.runPromise(
164
- streamEffect.pipe(
165
- Effect.ensuring(Effect.sync(() => res.end())),
166
- Effect.catchAll(() => Effect.void)
167
- )
168
- )
169
- }
170
- }
171
-
172
- /**
173
- * Create a standalone Express route handler for SSE subscriptions.
174
- *
175
- * Use this if you want more control over routing than the middleware provides.
176
- *
177
- * @param schema - The GraphQL schema with subscription definitions
178
- * @param layer - Effect layer providing services required by resolvers
179
- * @param options - Optional lifecycle hooks and configuration
180
- * @returns An Express request handler
181
- *
182
- * @example
183
- * ```typescript
184
- * import express from "express"
185
- * import { createSSEHandler } from "@effect-gql/express"
186
- *
187
- * const app = express()
188
- * app.use(express.json())
189
- *
190
- * const sseHandler = createSSEHandler(schema, Layer.empty)
191
- * app.post("/graphql/stream", sseHandler)
192
- *
193
- * app.listen(4000)
194
- * ```
195
- */
196
- export const createSSEHandler = <R>(
197
- schema: GraphQLSchema,
198
- layer: Layer.Layer<R>,
199
- options?: Omit<ExpressSSEOptions<R>, "path">
200
- ): RequestHandler => {
201
- const sseHandler = makeGraphQLSSEHandler(schema, layer, options)
202
-
203
- return async (req: Request, res: Response, _next: NextFunction): Promise<void> => {
204
- // Check Accept header for SSE support
205
- const accept = req.headers.accept ?? ""
206
- if (!accept.includes("text/event-stream") && !accept.includes("*/*")) {
207
- res.status(406).json({
208
- errors: [{ message: "Client must accept text/event-stream" }],
209
- })
210
- return
211
- }
212
-
213
- // Parse the GraphQL request from the body
214
- let subscriptionRequest: SSESubscriptionRequest
215
- try {
216
- const body = req.body as Record<string, unknown>
217
- if (typeof body.query !== "string") {
218
- throw new Error("Missing query")
219
- }
220
- subscriptionRequest = {
221
- query: body.query,
222
- variables: body.variables as Record<string, unknown> | undefined,
223
- operationName: body.operationName as string | undefined,
224
- extensions: body.extensions as Record<string, unknown> | undefined,
225
- }
226
- } catch {
227
- res.status(400).json({
228
- errors: [{ message: "Invalid GraphQL request body" }],
229
- })
230
- return
231
- }
232
-
233
- // Convert Express headers to web Headers
234
- const headers = toWebHeaders(req.headers)
235
-
236
- // Set SSE headers
237
- res.writeHead(200, SSE_HEADERS)
238
-
239
- // Get the event stream
240
- const eventStream = sseHandler(subscriptionRequest, headers)
241
-
242
- // Create the streaming effect
243
- const streamEffect = Effect.gen(function* () {
244
- // Track client disconnection
245
- const clientDisconnected = yield* Deferred.make<void, SSEError>()
246
-
247
- req.on("close", () => {
248
- Effect.runPromise(Deferred.succeed(clientDisconnected, undefined)).catch(() => {})
249
- })
250
-
251
- req.on("error", (error) => {
252
- Effect.runPromise(Deferred.fail(clientDisconnected, new SSEError({ cause: error }))).catch(
253
- () => {}
254
- )
255
- })
256
-
257
- // Stream events to the client
258
- const runStream = Stream.runForEach(eventStream, (event) =>
259
- Effect.async<void, SSEError>((resume) => {
260
- const message = formatSSEMessage(event)
261
- res.write(message, (error) => {
262
- if (error) {
263
- resume(Effect.fail(new SSEError({ cause: error })))
264
- } else {
265
- resume(Effect.succeed(undefined))
266
- }
267
- })
268
- })
269
- )
270
-
271
- // Race between stream completion and client disconnection
272
- yield* Effect.race(
273
- runStream.pipe(Effect.catchAll((error) => Effect.logWarning("SSE stream error", error))),
274
- Deferred.await(clientDisconnected)
275
- )
276
- })
277
-
278
- await Effect.runPromise(
279
- streamEffect.pipe(
280
- Effect.ensuring(Effect.sync(() => res.end())),
281
- Effect.catchAll(() => Effect.void)
282
- )
283
- )
284
- }
285
- }
package/src/ws.ts DELETED
@@ -1,152 +0,0 @@
1
- import { Effect, Layer } from "effect"
2
- import type { Server } from "node:http"
3
- import type { IncomingMessage } from "node:http"
4
- import type { Duplex } from "node:stream"
5
- import { WebSocket, WebSocketServer } from "ws"
6
- import { GraphQLSchema } from "graphql"
7
- import {
8
- makeGraphQLWSHandler,
9
- toEffectWebSocketFromWs,
10
- type GraphQLWSOptions,
11
- } from "@effect-gql/core"
12
-
13
- /**
14
- * Options for Express WebSocket server
15
- */
16
- export interface ExpressWSOptions<R> extends GraphQLWSOptions<R> {
17
- /**
18
- * Path for WebSocket connections.
19
- * @default "/graphql"
20
- */
21
- readonly path?: string
22
- }
23
-
24
- /**
25
- * Attach WebSocket subscription support to an Express HTTP server.
26
- *
27
- * Since Express middleware doesn't own the HTTP server, this function
28
- * must be called separately with the HTTP server instance to enable
29
- * WebSocket subscriptions.
30
- *
31
- * @param server - The HTTP server running the Express app
32
- * @param schema - The GraphQL schema with subscription definitions
33
- * @param layer - Effect layer providing services required by resolvers
34
- * @param options - Optional configuration and lifecycle hooks
35
- * @returns Object with cleanup function
36
- *
37
- * @example
38
- * ```typescript
39
- * import express from "express"
40
- * import { createServer } from "node:http"
41
- * import { toMiddleware, attachWebSocket } from "@effect-gql/express"
42
- * import { makeGraphQLRouter, GraphQLSchemaBuilder } from "@effect-gql/core"
43
- * import { Layer, Effect, Stream } from "effect"
44
- * import * as S from "effect/Schema"
45
- *
46
- * // Build schema with subscriptions
47
- * const schema = GraphQLSchemaBuilder.empty
48
- * .query("hello", { type: S.String, resolve: () => Effect.succeed("world") })
49
- * .subscription("counter", {
50
- * type: S.Int,
51
- * subscribe: () => Effect.succeed(Stream.fromIterable([1, 2, 3]))
52
- * })
53
- * .buildSchema()
54
- *
55
- * // Create Express app with middleware
56
- * const app = express()
57
- * app.use(express.json())
58
- * const router = makeGraphQLRouter(schema, Layer.empty, { graphiql: true })
59
- * app.use(toMiddleware(router, Layer.empty))
60
- *
61
- * // Create HTTP server and attach WebSocket support
62
- * const server = createServer(app)
63
- * const ws = attachWebSocket(server, schema, Layer.empty, {
64
- * path: "/graphql"
65
- * })
66
- *
67
- * server.listen(4000, () => {
68
- * console.log("Server running on http://localhost:4000")
69
- * console.log("WebSocket subscriptions available at ws://localhost:4000/graphql")
70
- * })
71
- *
72
- * // Cleanup on shutdown
73
- * process.on("SIGINT", async () => {
74
- * await ws.close()
75
- * server.close()
76
- * })
77
- * ```
78
- */
79
- export const attachWebSocket = <R>(
80
- server: Server,
81
- schema: GraphQLSchema,
82
- layer: Layer.Layer<R>,
83
- options?: ExpressWSOptions<R>
84
- ): { close: () => Promise<void> } => {
85
- const wss = new WebSocketServer({ noServer: true })
86
- const path = options?.path ?? "/graphql"
87
-
88
- // Create the handler from core
89
- const handler = makeGraphQLWSHandler(schema, layer, options)
90
-
91
- // Track active connections for cleanup
92
- const activeConnections = new Set<WebSocket>()
93
-
94
- wss.on("connection", (ws) => {
95
- activeConnections.add(ws)
96
-
97
- const effectSocket = toEffectWebSocketFromWs(ws)
98
-
99
- // Run the handler
100
- Effect.runPromise(
101
- handler(effectSocket).pipe(
102
- Effect.catchAll((error) => Effect.logError("GraphQL WebSocket handler error", error))
103
- )
104
- ).finally(() => {
105
- activeConnections.delete(ws)
106
- })
107
- })
108
-
109
- const handleUpgrade = (request: IncomingMessage, socket: Duplex, head: Buffer) => {
110
- // Check if this is the GraphQL WebSocket path
111
- const url = new URL(request.url ?? "/", `http://${request.headers.host}`)
112
- if (url.pathname !== path) {
113
- socket.destroy()
114
- return
115
- }
116
-
117
- // Check for correct WebSocket subprotocol
118
- const protocol = request.headers["sec-websocket-protocol"]
119
- if (!protocol?.includes("graphql-transport-ws")) {
120
- socket.write("HTTP/1.1 400 Bad Request\r\n\r\n")
121
- socket.destroy()
122
- return
123
- }
124
-
125
- wss.handleUpgrade(request, socket, head, (ws) => {
126
- wss.emit("connection", ws, request)
127
- })
128
- }
129
-
130
- // Attach upgrade handler to server
131
- server.on("upgrade", (request, socket, head) => {
132
- handleUpgrade(request, socket as Duplex, head)
133
- })
134
-
135
- const close = async () => {
136
- // Close all active connections
137
- for (const ws of activeConnections) {
138
- ws.close(1001, "Server shutting down")
139
- }
140
- activeConnections.clear()
141
-
142
- // Close the WebSocket server
143
- return new Promise<void>((resolve, reject) => {
144
- wss.close((error) => {
145
- if (error) reject(error)
146
- else resolve()
147
- })
148
- })
149
- }
150
-
151
- return { close }
152
- }