Skip to content

Support integration with Koa #33

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 4 commits into from
Jan 4, 2023
Merged
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
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,21 @@ export default {
};
```

##### With [`Koa`](https://koajs.com/)

```js
import Koa from 'koa'; // yarn add koa
import mount from 'koa-mount'; // yarn add koa-mount
import { createHandler } from 'graphql-http/lib/use/koa';
import { schema } from './previous-step';

const app = new Koa();
app.use(mount('/graphql', createHandler({ schema })));

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

#### Use the client

```js
Expand Down
9 changes: 9 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,11 @@
"require": "./lib/use/fastify.js",
"import": "./lib/use/fastify.mjs"
},
"./lib/use/koa": {
"types": "./lib/use/koa.d.ts",
"require": "./lib/use/koa.js",
"import": "./lib/use/koa.mjs"
},
"./package.json": "./package.json"
},
"types": "lib/index.d.ts",
Expand Down Expand Up @@ -105,6 +110,8 @@
"@types/express": "^4.17.15",
"@types/glob": "^8.0.0",
"@types/jest": "^29.2.4",
"@types/koa": "^2.13.5",
"@types/koa-mount": "^4.0.2",
"@typescript-eslint/eslint-plugin": "^5.47.0",
"@typescript-eslint/parser": "^5.47.0",
"@whatwg-node/fetch": "^0.5.3",
Expand All @@ -116,6 +123,8 @@
"graphql": "^16.6.0",
"jest": "^29.3.1",
"jest-jasmine2": "^29.3.1",
"koa": "^2.14.1",
"koa-mount": "^4.0.0",
"node-fetch": "^3.3.0",
"prettier": "^2.8.1",
"rollup": "^3.8.1",
Expand Down
20 changes: 20 additions & 0 deletions src/__tests__/use.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { fetch } from '@whatwg-node/fetch';
import http from 'http';
import express from 'express';
import fastify from 'fastify';
import Koa from 'koa';
import mount from 'koa-mount';
import { createServerAdapter } from '@whatwg-node/server';
import { startDisposableServer } from './utils/tserver';
import { serverAudits } from '../audits';
Expand All @@ -11,6 +13,7 @@ import { createHandler as createNodeHandler } from '../use/node';
import { createHandler as createExpressHandler } from '../use/express';
import { createHandler as createFastifyHandler } from '../use/fastify';
import { createHandler as createFetchHandler } from '../use/fetch';
import { createHandler as createKoaHandler } from '../use/koa';

describe('node', () => {
const [url, dispose] = startDisposableServer(
Expand Down Expand Up @@ -90,3 +93,20 @@ describe('fetch', () => {
});
}
});

describe('koa', () => {
const app = new Koa();
app.use(mount('/', createKoaHandler({ schema })));

const [url, dispose] = startDisposableServer(app.listen(0));
afterAll(dispose);

for (const audit of serverAudits({ url, fetchFn: fetch })) {
it(audit.name, async () => {
const result = await audit.fn();
if (result.status !== 'ok') {
throw result.reason;
}
});
}
});
85 changes: 85 additions & 0 deletions src/use/koa.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import type { Middleware } from 'koa';
import type { IncomingMessage } from 'http';
import {
createHandler as createRawHandler,
HandlerOptions,
OperationContext,
} from '../handler';

/**
* Create a GraphQL over HTTP Protocol compliant request handler for
* the Koa framework.
*
* ```js
* import Koa from 'koa'; // yarn add koa
* import mount from 'koa-mount'; // yarn add koa-mount
* import { createHandler } from 'graphql-http/lib/use/koa';
* import { schema } from './my-graphql-schema';
*
* const app = new Koa();
* app.use(mount('/', createHandler({ schema })));
*
* app.listen({ port: 4000 });
* console.log('Listening to port 4000');
* ```
*
* @category Server/koa
*/
export function createHandler<Context extends OperationContext = undefined>(
options: HandlerOptions<IncomingMessage, undefined, Context>,
): Middleware {
const isProd = process.env.NODE_ENV === 'production';
const handle = createRawHandler(options);
return async function requestListener(ctx) {
try {
const [body, init] = await handle({
url: ctx.url,
method: ctx.method,
headers: ctx.headers,
body: () => {
if (ctx.body) {
// in case koa has a body parser
return ctx.body;
}
return new Promise<string>((resolve) => {
let body = '';
ctx.req.on('data', (chunk) => (body += chunk));
ctx.req.on('end', () => resolve(body));
});
},
raw: ctx.req,
context: undefined,
});
ctx.body = body;
ctx.response.status = init.status;
ctx.response.message = init.statusText;
if (init.headers) {
for (const [name, value] of Object.entries(init.headers)) {
ctx.response.set(name, value);
}
}
} catch (err) {
// The handler shouldnt throw errors.
// If you wish to handle them differently, consider implementing your own request handler.
console.error(
'Internal error occurred during request handling. ' +
'Please check your implementation.',
err,
);
ctx.response.status = 500;
if (!isProd) {
ctx.response.set('content-type', 'application/json; charset=utf-8');
ctx.body = {
errors: [
err instanceof Error
? {
message: err.message,
stack: err.stack,
}
: err,
],
};
}
}
};
}
Loading