Skip to content

Latest commit

 

History

History
267 lines (171 loc) · 7.27 KB

handler.md

File metadata and controls

267 lines (171 loc) · 7.27 KB

graphql-http / handler

Module: handler

Table of contents

Interfaces

Type Aliases

Functions

Server

AcceptableMediaType

Ƭ AcceptableMediaType: "application/graphql-response+json" | "application/json"

Request's Media-Type that the server accepts.


Handler

Ƭ Handler<RequestRaw, RequestContext>: (req: Request<RequestRaw, RequestContext>) => Promise<Response>

Type parameters

Name Type
RequestRaw unknown
RequestContext unknown

Type declaration

▸ (req): Promise<Response>

The ready-to-use handler. Simply plug it in your favourite HTTP framework and enjoy.

Errors thrown from any of the provided options or callbacks (or even due to library misuse or potential bugs) will reject the handler's promise. They are considered internal errors and you should take care of them accordingly.

Parameters
Name Type
req Request<RequestRaw, RequestContext>
Returns

Promise<Response>


OperationArgs

Ƭ OperationArgs<Context>: ExecutionArgs & { contextValue?: Context }

Type parameters

Name Type
Context extends OperationContext = undefined

OperationContext

Ƭ OperationContext: Record<PropertyKey, unknown> | symbol | number | string | boolean | undefined | null

A concrete GraphQL execution context value type.

Mainly used because TypeScript collapes unions with any or unknown to any or unknown. So, we use a custom type to allow definitions such as the context server option.


RequestHeaders

Ƭ RequestHeaders: { [key: string]: string | string[] | undefined; set-cookie?: string | string[] } | { get: (key: string) => string | null }

The incoming request headers the implementing server should provide.


Response

Ƭ Response: readonly [body: ResponseBody | null, init: ResponseInit]

Server agnostic response returned from graphql-http containing the body and init options needing to be coerced to the server implementation in use.


ResponseBody

Ƭ ResponseBody: string

Server agnostic response body returned from graphql-http needing to be coerced to the server implementation in use.


ResponseHeaders

Ƭ ResponseHeaders: { accept?: string ; allow?: string ; content-type?: string } & Record<string, string>

The response headers that get returned from graphql-http.


createHandler

createHandler<RequestRaw, RequestContext, Context>(options): Handler<RequestRaw, RequestContext>

Makes a GraphQL over HTTP Protocol compliant server handler. The handler can be used with your favourite server library.

Beware that the handler resolves only after the whole operation completes.

Errors thrown from any of the provided options or callbacks (or even due to library misuse or potential bugs) will reject the handler's promise. They are considered internal errors and you should take care of them accordingly.

For production environments, its recommended not to transmit the exact internal error details to the client, but instead report to an error logging tool or simply the console.

Simple example usage with Node:

import http from 'http';
import { createHandler } from 'graphql-http';
import { schema } from './my-graphql-schema';

// Create the GraphQL over HTTP handler
const handler = createHandler({ schema });

// Create a HTTP server using the handler on `/graphql`
const server = http.createServer(async (req, res) => {
  if (!req.url.startsWith('/graphql')) {
    return res.writeHead(404).end();
  }

  try {
    const [body, init] = await handler({
      url: req.url,
      method: req.method,
      headers: req.headers,
      body: () => new Promise((resolve) => {
        let body = '';
        req.on('data', (chunk) => (body += chunk));
        req.on('end', () => resolve(body));
      }),
      raw: req,
    });
    res.writeHead(init.status, init.statusText, init.headers).end(body);
  } catch (err) {
    // BEWARE not to transmit the exact internal error message in production environments
    res.writeHead(500).end(err.message);
  }
});

server.listen(4000);
console.log('Listening to port 4000');

Type parameters

Name Type
RequestRaw unknown
RequestContext unknown
Context extends OperationContext = undefined

Parameters

Name Type
options HandlerOptions<RequestRaw, RequestContext, Context>

Returns

Handler<RequestRaw, RequestContext>


getAcceptableMediaType

getAcceptableMediaType(acceptHeader): AcceptableMediaType | null

Inspects the request and detects the appropriate/acceptable Media-Type looking at the Accept header while complying with the GraphQL over HTTP Protocol.

Parameters

Name Type
acceptHeader undefined | null | string

Returns

AcceptableMediaType | null


isResponse

isResponse(val): val is Response

Checks whether the passed value is the graphql-http server agnostic response.

Parameters

Name Type
val unknown

Returns

val is Response


makeResponse

makeResponse(resultOrErrors, acceptedMediaType): Response

Creates an appropriate GraphQL over HTTP response following the provided arguments.

If the first argument is an ExecutionResult, the operation will be treated as "successful".

If the first argument is any object without the data field, it will be treated as an error (as per the spec) and the response will be constructed with the help of acceptedMediaType complying with the GraphQL over HTTP Protocol.

Parameters

Name Type
resultOrErrors readonly GraphQLError[] | Readonly<ExecutionResult<ObjMap<unknown>, ObjMap<unknown>>> | Readonly<GraphQLError>
acceptedMediaType AcceptableMediaType

Returns

Response