graphql-http / use/fetch
Ƭ HandlerOptions<Context
>: HandlerOptions
<Request
, FetchAPI
, Context
>
Handler options when using the fetch adapter.
Name | Type |
---|---|
Context |
extends OperationContext = undefined |
▸ createHandler<Context
>(options
, reqCtx?
): (req
: Request
) => Promise
<Response
>
Create a GraphQL over HTTP spec compliant request handler for a fetch environment like Deno, Bun, CloudFlare Workers, Lambdas, etc.
You can use @whatwg-node/server to create a server adapter and isomorphically use it in any environment. See an example:
import http from 'http';
import { createServerAdapter } from '@whatwg-node/server'; // yarn add @whatwg-node/server
import { createHandler } from 'graphql-http/lib/use/fetch';
import { schema } from './my-graphql-schema';
// Use this adapter in _any_ environment.
const adapter = createServerAdapter({
handleRequest: createHandler({ schema }),
});
const server = http.createServer(adapter);
server.listen(4000);
console.log('Listening to port 4000');
Name | Type |
---|---|
Context |
extends OperationContext = undefined |
Name | Type | Description |
---|---|---|
options |
HandlerOptions <Context > |
- |
reqCtx |
Partial <FetchAPI > |
Custom fetch API engine, will use from global scope if left undefined. |
fn
▸ (req
): Promise
<Response
>
Name | Type |
---|---|
req |
Request |
Promise
<Response
>
▸ parseRequestParams(req
, api?
): Promise
<RequestParams
| Response
>
The GraphQL over HTTP spec compliant request parser for an incoming GraphQL request.
It is important to pass in the abortedRef
so that the parser does not perform any
operations on a disposed request (see example).
If the HTTP request is not a well-formatted GraphQL over HTTP request, the function will return a Response
.
If the HTTP request is a well-formatted GraphQL over HTTP request, but is invalid or malformed, the function will throw an error and it is up to the user to handle and respond as they see fit.
import http from 'http';
import { createServerAdapter } from '@whatwg-node/server'; // yarn add @whatwg-node/server
import { parseRequestParams } from 'graphql-http/lib/use/fetch';
// Use this adapter in _any_ environment.
const adapter = createServerAdapter({
handleRequest: async (req) => {
try {
const paramsOrResponse = await parseRequestParams(req);
if (paramsOrResponse instanceof Response) {
// not a well-formatted GraphQL over HTTP request,
// parser created a response object to use
return paramsOrResponse;
}
// well-formatted GraphQL over HTTP request,
// with valid parameters
return new Response(JSON.stringify(paramsOrResponse, null, ' '), {
status: 200,
});
} catch (err) {
// well-formatted GraphQL over HTTP request,
// but with invalid parameters
return new Response(err.message, { status: 400 });
}
},
});
const server = http.createServer(adapter);
server.listen(4000);
console.log('Listening to port 4000');
Name | Type |
---|---|
req |
Request |
api |
Partial <FetchAPI > |
Promise
<RequestParams
| Response
>