Skip to content

Latest commit

 

History

History
137 lines (91 loc) · 3.48 KB

use_http.md

File metadata and controls

137 lines (91 loc) · 3.48 KB

graphql-http / use/http

Module: use/http

Table of contents

Interfaces

Type Aliases

Functions

Server/http

HandlerOptions

Ƭ HandlerOptions<Context>: HandlerOptions<IncomingMessage, RequestContext, Context>

Handler options when using the http adapter.

Type parameters

Name Type
Context extends OperationContext = undefined

createHandler

createHandler<Context>(options): (req: IncomingMessage, res: ServerResponse) => Promise<void>

Create a GraphQL over HTTP spec compliant request handler for the Node environment http module.

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

const server = http.createServer(createHandler({ schema }));

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

Type parameters

Name Type
Context extends OperationContext = undefined

Parameters

Name Type
options HandlerOptions<Context>

Returns

fn

▸ (req, res): Promise<void>

Parameters
Name Type
req IncomingMessage
res ServerResponse
Returns

Promise<void>


parseRequestParams

parseRequestParams(req, res): Promise<RequestParams | null>

The GraphQL over HTTP spec compliant request parser for an incoming GraphQL request.

If the HTTP request is not a well-formatted GraphQL over HTTP request, the function will respond on the ServerResponse argument and return null.

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 { parseRequestParams } from 'graphql-http/lib/use/http';

const server = http.createServer(async (req, res) => {
  if (req.url.startsWith('/graphql')) {
    try {
      const maybeParams = await parseRequestParams(req, res);
      if (!maybeParams) {
        // not a well-formatted GraphQL over HTTP request,
        // parser responded and there's nothing else to do
        return;
      }

      // well-formatted GraphQL over HTTP request,
      // with valid parameters
      res.writeHead(200).end(JSON.stringify(maybeParams, null, '  '));
    } catch (err) {
      // well-formatted GraphQL over HTTP request,
      // but with invalid parameters
      res.writeHead(400).end(err.message);
    }
  } else {
    res.writeHead(404).end();
  }
});

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

Parameters

Name Type
req IncomingMessage
res ServerResponse<IncomingMessage>

Returns

Promise<RequestParams | null>