Skip to content

feat(use): Built-in handlers for some environments and frameworks #13

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 19 commits into from
Nov 7, 2022

Conversation

enisdenjo
Copy link
Member

Speed up and improve DX by shipping with built-in support for some environments inside the lib/use folder.

Node

graphql-http/lib/use/node

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

const handler = createHandler({ schema });

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) {
-    res.writeHead(500).end(err.message);
-  }
+  if (req.url.startsWith('/graphql')) {
+    handler(req, res);
+  } else {
+    res.writeHead(404).end();
+  }
});

Express

graphql-http/lib/use/express

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

const handler = createHandler({ schema });

const app = express();
-app.all('/graphql', async (req, res) => {
-  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) {
-    res.writeHead(500).end(err.message);
-  }
-});
+app.all('/graphql', handler);

app.listen({ port: 4000 });
console.log('Listening to port 4000');

Fastify

graphql-http/lib/use/fastify

import Fastify from 'fastify'; // yarn add fastify
-import { createHandler } from 'graphql-http';
+import { createHandler } from 'graphql-http/lib/use/fastify';
import { schema } from './my-graphql-schema';

const handler = createHandler({ schema });

const fastify = Fastify();
-fastify.all('/graphql', async (req, res) => {
-  try {
-    const [body, init] = await handler({
-      url: req.url,
-      method: req.method,
-      headers: req.headers,
-      body: req.body, // fastify reads the body for you
-      raw: req,
-    });
-    res.writeHead(init.status, init.statusText, init.headers).end(body);
-  } catch (err) {
-    res.writeHead(500).end(err.message);
-  }
-});
+fastify.all('/graphql', handler);

fastify.listen({ port: 4000 });
console.log('Listening to port 4000');

Deno (and other fetch native environments)

graphql-http/lib/use/fetch

import { serve } from 'https://deno.land/[email protected]/http/server.ts';
-import { createHandler } from 'https://esm.sh/graphql-http';
+import { createHandler } from 'https://esm.sh/graphql-http/lib/use/fetch';
import { schema } from './my-graphql-schema';

const handler = createHandler({ schema });

await serve(
  async (req: Request) => {
    const [path, _search] = req.url.split('?');
-   if (!path.endsWith('/graphql')) {
-     return new Response(null, { status: 404, statusText: 'Not Found' });
-   }
-
-   const [body, init] = await handler({
-     url: req.url,
-     method: req.method,
-     headers: req.headers,
-     body: () => req.text(),
-     raw: req,
-   });
-   return new Response(body, init);
+   if (path.endsWith('/graphql')) {
+     return handler(req);
+   } else {
+     return new Response(null, { status: 404 });
+   }
  },
  {
    port: 4000,
  },
);

@enisdenjo enisdenjo merged commit 750e600 into master Nov 7, 2022
@enisdenjo enisdenjo deleted the use branch November 7, 2022 12:15
enisdenjo pushed a commit that referenced this pull request Nov 7, 2022
# [1.7.0](v1.6.1...v1.7.0) (2022-11-07)

### Bug Fixes

* **audits/server:** Server may accept other content-type encodings ([42c26f7](42c26f7))

### Features

* **handler:** Headers can be native to fetch ([d459991](d459991))
* **handler:** Supply context to schema option and improve typings ([01c45d8](01c45d8))
* **use:** Built-in handlers for some environments and frameworks ([#13](#13)) ([750e600](750e600))
@enisdenjo
Copy link
Member Author

🎉 This PR is included in version 1.7.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

@enisdenjo enisdenjo added the released Has been released and published label Nov 7, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
released Has been released and published
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant