Skip to content
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

Added whatwg-node-server adapter for grafserv #2288

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 21 additions & 5 deletions grafast/grafserv/__tests__/exampleServer.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { createServer } from "node:http";
import { createServer, Server } from "node:http";
import type { AddressInfo } from "node:net";

import { constant, error, makeGrafastSchema } from "grafast";
import { resolvePreset } from "graphile-config";

import { grafserv } from "../src/servers/node/index.js";
import { grafserv as grafservNode } from "../src/servers/node/index.js";
import { grafserv as grafservWhatwg } from "../src/servers/whatwg-node-server";
import { GrafservBase } from "../src/index.js";

export async function makeExampleServer(
preset: GraphileConfig.Preset = {
Expand All @@ -14,6 +16,7 @@ export async function makeExampleServer(
dangerouslyAllowAllCORSRequests: true,
},
},
type?: 'node' | 'whatwg'
) {
const resolvedPreset = resolvePreset(preset);
const schema = makeGrafastSchema({
Expand All @@ -35,9 +38,22 @@ export async function makeExampleServer(
},
});

const serv = grafserv({ schema, preset });
const server = createServer();
serv.addTo(server);
let serv: GrafservBase
let server: ReturnType<typeof createServer>
switch (type) {
case 'whatwg':
const servWhatwg = grafservWhatwg({schema, preset})
server = createServer(servWhatwg.createHandler());
serv = servWhatwg
break;
case 'node':
default:
const servNode = grafservNode({ schema, preset });
server = createServer();
servNode.addTo(server);
serv = servNode
break;
}
const promise = new Promise<void>((resolve, reject) => {
server.on("listening", () => {
server.off("error", reject);
Expand Down
5 changes: 5 additions & 0 deletions grafast/grafserv/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@
},
"peerDependencies": {
"@envelop/core": "^5.0.0",
"@whatwg-node/server": "^0.9.64",
"grafast": "workspace:^",
"graphile-config": "workspace:^",
"graphql": "^16.1.0-experimental-stream-defer.6",
Expand All @@ -100,6 +101,9 @@
"@envelop/core": {
"optional": true
},
"@whatwg-node/server": {
"optional": true
},
"h3": {
"optional": true
},
Expand All @@ -115,6 +119,7 @@
"@types/koa": "^2.13.8",
"@types/koa-bodyparser": "^4.3.10",
"@whatwg-node/fetch": "^0.9.10",
"@whatwg-node/server": "^0.9.64",
benjie marked this conversation as resolved.
Show resolved Hide resolved
"express": "^4.20.0",
"fastify": "^4.22.1",
"grafast": "workspace:^",
Expand Down
154 changes: 154 additions & 0 deletions grafast/grafserv/src/servers/whatwg-node-server/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
import { createServerAdapter } from '@whatwg-node/server'

import { GrafservBase } from "../../core/base.js";
import type {
GrafservBody,
GrafservConfig,
RequestDigest,
Result,
} from "../../interfaces.js";

import { OptionsFromConfig } from '../../options.js';
import { httpError } from '../../utils.js';

export function getBodyFromRequest(
req: Request /* IncomingMessage */,
maxLength: number,
): Promise<GrafservBody> {
return new Promise(async (resolve, reject) => {
const chunks: Buffer[] = [];
let len = 0;
const handleDataCb = (chunk: Uint8Array<ArrayBufferLike>) => {
chunks.push(Buffer.from(chunk));
len += chunk.length;
if (len > maxLength) {
reject(httpError(413, "Too much data"));
}
};
const doneCb = () => {
resolve({ type: "buffer", buffer: Buffer.concat(chunks) });
};
const reader = req.body?.getReader()
if (!reader) {
return doneCb()
}
while (true) {
const {done, value} = await reader?.read()
if (value) {
handleDataCb(value)
}
if (done) {
return doneCb()
}
}
});
}

declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace Grafast {
interface RequestContext {
whatwg: {
version:string
Comment on lines +51 to +52
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry; I meant that the version should be part of the scope key like with the other servers; then when a new version is supported we can add support for that without breaking existing users. See the Koa, Express, Fastify, Lambda and H3 adaptors for example.

Suggested change
whatwg: {
version:string
whatwgv0_9: {

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should also be factored into the file name; e.g. src/servers/whatwg-node-server/v0_9/... - see the same list of other adaptors for examples.

request: Request
}
}
}
}

/** @experimental */
export class WhatwgGrafserv extends GrafservBase {
protected whatwgRequestToGrafserv(
dynamicOptions: OptionsFromConfig,
request: Request
): RequestDigest {
const url = new URL(request.url);
return {
httpVersionMajor: 1,
httpVersionMinor: 1,
isSecure: url.protocol === 'https:',
method: request.method,
path: url.pathname,
headers: this.processHeaders(request.headers),
getQueryParams() {
return Object.fromEntries(url.searchParams.entries()) as Record<string, string>;
},
async getBody() {
return getBodyFromRequest(request, dynamicOptions.maxRequestLength)
},
requestContext: {
whatwg: {
version:'whatwgv1',
Comment on lines +80 to +81
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
whatwg: {
version:'whatwgv1',
whatwgv0_9: {

request
}
},
preferJSON: true,
};
}

protected processHeaders(headers: Headers): Record<string, string> {
const headerDigest: Record<string, string> = Object.create(null);
headers.forEach((v,k)=> {
headerDigest[k]= v
})
return headerDigest
}

protected grafservResponseToWhatwg(response: Result | null): Response {
if (response === null) {
return new Response("¯\\_(ツ)_/¯", {status: 404, headers: new Headers({"Content-Type": "text/plain"})})
}

switch (response.type) {
case "error": {
const { statusCode, headers, error } = response;
const respHeaders = new Headers(headers)
respHeaders.append("Content-Type", "text/plain")
return new Response(error.message, {status: statusCode, headers:respHeaders})
}

case "buffer": {
const { statusCode, headers, buffer } = response;
const respHeaders = new Headers(headers)
return new Response(buffer, {status: statusCode, headers:respHeaders})
}

case "json": {
const { statusCode, headers, json } = response;
const respHeaders = new Headers(headers)
return new Response(JSON.stringify(json), {status: statusCode, headers:respHeaders})
}

default: {
console.log("Unhandled:");
console.dir(response);
return new Response("Server hasn't implemented this yet", {status: 501, headers: new Headers({"Content-Type": "text/plain"})})
}
}
}

createHandler() {
// eslint-disable-next-line @typescript-eslint/no-this-alias
return createServerAdapter(async (request: Request): Promise<Response> => {
const dynamicOptions = this.dynamicOptions;
return this.grafservResponseToWhatwg(
await this.processWhatwgRequest(
request,
this.whatwgRequestToGrafserv(dynamicOptions, request),
),
);
})
}

protected processWhatwgRequest(
_request: Request,
request: RequestDigest,
) {
return this.processRequest(request);
}
}

/** @experimental */
export function grafserv(config: GrafservConfig) {
return new WhatwgGrafserv(config);
}
Loading