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

Initital Hono grafserv adapter #2297

Open
wants to merge 10 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
162 changes: 162 additions & 0 deletions grafast/grafserv/__tests__/hono-adapter.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
import { serve } from "@hono/node-server";
import { createNodeWebSocket } from "@hono/node-ws";
import { error } from "console";
import { constant, makeGrafastSchema } from "grafast";
import { serverAudits } from "graphql-http";
import { createClient } from "graphql-ws";
import { Hono } from "hono";
import { WebSocket } from "ws";

import type { GrafservConfig } from "../src/interfaces.js";
import { grafserv } from "../src/servers/hono/v4/index.js";

const schema = makeGrafastSchema({
typeDefs: /* GraphQL */ `
type Query {
hello: String!
throwAnError: String
}

type Subscription {
subscriptionTest: String!
}
`,
plans: {
Query: {
hello() {
return constant("world");
},
throwAnError() {
return error(new Error("You asked for an error... Here it is."));
},
},
Subscription: {
subscriptionTest: {
// eslint-disable-next-line graphile-export/export-methods
subscribe: async function* () {
yield { subscriptionTest: "test1" };
yield { subscriptionTest: "test2" };
},
},
},
},
});

describe("Hono Adapter", () => {
// setup test server
const app = new Hono();
const config: GrafservConfig = {
schema, // Mock schema for testing
preset: {
grafserv: {
graphqlOverGET: true,
graphqlPath: "/graphql",
dangerouslyAllowAllCORSRequests: true,
},
},
};
const honoGrafserv = grafserv(config);
honoGrafserv.addTo(app);

const server = serve({
fetch: app.fetch,
port: 7777,
});
const url = `http://0.0.0.0:7777/graphql`;

it("SHOULD work for a simple request", async () => {
const res = await fetch(url, {
method: "POST",
headers: {
"content-type": "application/json",
},
body: JSON.stringify({ query: "{ __typename }" }),
});

const responseBody = await res.json();
expect(responseBody.data).toEqual({
__typename: "Query",
});
});

// run standard audits
const audits = serverAudits({
url,
fetchFn: fetch,
});
for (const audit of audits) {
it(audit.name, async () => {
const result = await audit.fn();
if (audit.name.startsWith("MUST") || result.status === "ok") {
expect({
...result,
response: "<omitted for brevity>",
}).toEqual(
expect.objectContaining({
status: "ok",
}),
);
} else {
console.warn(`Allowing failed test: ${audit.name}`);
}
});
}
});

describe("Hono Adapter with websockets", () => {
// setup test server
const app = new Hono();
const config: GrafservConfig = {
schema, // Mock schema for testing
preset: {
grafserv: {
graphqlOverGET: true,
websockets: true,
},
},
};
const { injectWebSocket, upgradeWebSocket } = createNodeWebSocket({ app });

const honoGrafserv = grafserv(config, upgradeWebSocket);
honoGrafserv.addTo(app);

const server = serve({
fetch: app.fetch,
port: 7778,
});
injectWebSocket(server);

const url = `ws://0.0.0.0:7778/graphql`;

it("SHOULD work for a simple subscription", async () => {
// make a graphql subscription
const client = createClient({
url,
webSocketImpl: WebSocket,
});

const query = client.iterate({
query: "subscription { subscriptionTest }",
});

const { value } = await query.next();
expect(value).toEqual({ data: { subscriptionTest: "test1" } });
const { value: value2 } = await query.next();
expect(value2).toEqual({ data: { subscriptionTest: "test2" } });
});

it("SHOULD throw an error is websocket is enabled but no upgradeWebSocket was provided", async () => {
const config: GrafservConfig = {
schema, // Mock schema for testing
preset: {
grafserv: {
websockets: true,
},
},
};
const honoGrafserv = grafserv(config);
expect(async () => {
await honoGrafserv.addTo(app);
}).rejects.toThrow();
});
});
23 changes: 23 additions & 0 deletions grafast/grafserv/examples/example-hono.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { serve } from "@hono/node-server";
import { grafserv } from "grafserv/hono";
import { Hono } from "hono";

import preset from "./graphile.config.mjs";
import schema from "./schema.mjs";

// Create a Node HTTP server
const app = new Hono();

// Create a Grafserv instance
// the second argument is an optional websocket upgrade handler
// see https://hono.dev/docs/helpers/websocket
const serv = grafserv({ schema, preset });

// Mount the request handler into a new HTTP server
serv.addTo(server).catch((e) => {
console.error(e);
process.exit(1);
});

// Start the server with the chosen Hono adapter - here Node.js
serve(app);
13 changes: 12 additions & 1 deletion grafast/grafserv/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@
"types": "./dist/servers/h3/v1/index.d.ts",
"default": "./dist/servers/h3/v1/index.js"
},
"./hono/v4": {
"types": "./dist/servers/hono/v4/index.d.ts",
"default": "./dist/servers/hono/v4/index.js"
},
"./ruru": {
"types": "./fwd/ruru/index.d.ts",
"node": "./fwd/ruru/index.js",
Expand Down Expand Up @@ -94,6 +98,7 @@
"graphile-config": "workspace:^",
"graphql": "^16.1.0-experimental-stream-defer.6",
"h3": "^1.13.0",
"hono": "^4.6.15",
"ws": "^8.12.1"
},
"peerDependenciesMeta": {
Expand All @@ -103,13 +108,17 @@
"h3": {
"optional": true
},
"hono": {
"optional": true
},
"ws": {
"optional": true
}
},
"devDependencies": {
"@envelop/core": "^5.0.0",
"@fastify/websocket": "^8.2.0",
"@hono/node-server": "^1.13.7",
"@types/aws-lambda": "^8.10.123",
"@types/express": "^4.17.17",
"@types/koa": "^2.13.8",
Expand All @@ -120,13 +129,15 @@
"grafast": "workspace:^",
"graphql-http": "^1.22.0",
"h3": "^1.13.0",
"hono": "^4.6.15",
"jest": "^29.6.4",
"jest-serializer-graphql-schema": "workspace:^",
"koa": "^2.14.2",
"koa-bodyparser": "^4.4.1",
"nodemon": "^3.0.1",
"ts-node": "^10.9.1",
"typescript": "^5.2.2"
"typescript": "^5.2.2",
"ws": "^8.12.1"
},
"files": [
"dist",
Expand Down
3 changes: 1 addition & 2 deletions grafast/grafserv/src/servers/h3/v1/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -278,8 +278,7 @@ export class H3Grafserv extends GrafservBase {
{ socket: peer.websocket, request: peer.request },
);
client.closed = async (code, reason) => {
// @ts-expect-error fixed in unreleased https://github.com/enisdenjo/graphql-ws/pull/573
onClose(code, reason);
onClose(code as number, reason as string);
};
},
message(peer, message) {
Expand Down
Loading