@as-integrations/h3 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 - UnJS
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,88 @@
1
+ # Apollo Server integration for h3 and nuxt
2
+
3
+ [![npm version][npm-version-src]][npm-version-href]
4
+ [![npm downloads][npm-downloads-src]][npm-downloads-href]
5
+ [![Github Actions][github-actions-src]][github-actions-href]
6
+ [![Codecov][codecov-src]][codecov-href]
7
+
8
+ This package allows you to easily integrate [Apollo Server](https://www.apollographql.com/docs/apollo-server/) with your [h3](https://github.com/unjs/h3) or [nuxt](v3.nuxtjs.org) application.
9
+
10
+ ## Installation
11
+
12
+ ```sh
13
+ # npm
14
+ npm install @apollo/server graphql @as-integrations/h3
15
+
16
+ # yarn
17
+ yarn install @apollo/server graphql @as-integrations/h3
18
+
19
+ # pnpm
20
+ pnpm install @apollo/server graphql @as-integrations/h3
21
+ ```
22
+
23
+ ## Usage with Nuxt v3
24
+
25
+ Create a [Server API Route](https://v3.nuxtjs.org/guide/directory-structure/server#api-routes) that configures an instance of Apollo Server as described in the [documentation](https://www.apollographql.com/docs/apollo-server/getting-started#step-6-create-an-instance-of-apolloserver) and then exports it as the event handler:
26
+
27
+ ```js
28
+ import { ApolloServer } from '@apollo/server'
29
+ import { startServerAndCreateH3Handler } from '@as-integrations/h3'
30
+
31
+ const apollo = new ApolloServer({
32
+ // Specify server options here
33
+ })
34
+
35
+ export default startServerAndCreateH3Handler(apollo, {
36
+ // Optional: Specify context
37
+ context: (event) => {...}
38
+ })
39
+ ```
40
+
41
+ ## Usage with h3
42
+
43
+ Create and configure an instance of Apollo Server as described in the [documentation](https://www.apollographql.com/docs/apollo-server/getting-started#step-6-create-an-instance-of-apolloserver) and then register it as a route handler in your `h3` application.
44
+
45
+ ```js
46
+ import { createApp } from 'h3'
47
+ import { ApolloServer } from '@apollo/server'
48
+ import { startServerAndCreateH3Handler } from '@as-integrations/h3'
49
+
50
+ const apollo = new ApolloServer({
51
+ // Specify server options here
52
+ })
53
+
54
+ const app = createApp()
55
+ app.use(
56
+ '/api',
57
+ startServerAndCreateH3Handler(apollo, {
58
+ // Optional: Specify context
59
+ context: (event) => {...}
60
+ })
61
+ )
62
+
63
+ createServer(toNodeListener(app)).listen(process.env.PORT || 3000)
64
+ ```
65
+
66
+ ## 💻 Development
67
+
68
+ - Clone this repository
69
+ - Enable [Corepack](https://github.com/nodejs/corepack) using `corepack enable` (use `npm i -g corepack` for Node.js < 16.10).
70
+ - Install dependencies using `pnpm install`.
71
+ - Run tests using `pnpm test` and integration tests via `pnpm test:integration`.
72
+
73
+ ## License
74
+
75
+ Made with 💛
76
+
77
+ Published under [MIT License](./LICENSE).
78
+
79
+ <!-- Badges -->
80
+
81
+ [npm-version-src]: https://img.shields.io/npm/v/@as-integrations/h3?style=flat-square
82
+ [npm-version-href]: https://npmjs.com/package/@as-integrations/h3
83
+ [npm-downloads-src]: https://img.shields.io/npm/dm/@as-integrations/h3?style=flat-square
84
+ [npm-downloads-href]: https://npmjs.com/package/@as-integrations/h3
85
+ [github-actions-src]: https://img.shields.io/github/workflow/status/apollo-server-integrations/apollo-server-integration-h3/ci/main?style=flat-square
86
+ [github-actions-href]: https://github.com/apollo-server-integrations/apollo-server-integration-h3/actions?query=workflow%3Aci
87
+ [codecov-src]: https://img.shields.io/codecov/c/gh/apollo-server-integrations/apollo-server-integration-h3/main?style=flat-square
88
+ [codecov-href]: https://codecov.io/gh/apollo-server-integrations/apollo-server-integration-h3
package/dist/index.cjs ADDED
@@ -0,0 +1,75 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ const h3 = require('h3');
6
+
7
+ function startServerAndCreateH3Handler(server, options) {
8
+ server.startInBackgroundHandlingStartupErrorsByLoggingAndFailingAllRequests();
9
+ const defaultContext = () => Promise.resolve({});
10
+ const contextFunction = options?.context ?? defaultContext;
11
+ return h3.eventHandler(async (event) => {
12
+ if (h3.isMethod(event, "OPTIONS")) {
13
+ return null;
14
+ }
15
+ try {
16
+ const graphqlRequest = await toGraphqlRequest(event);
17
+ const { body, headers, status } = await server.executeHTTPGraphQLRequest({
18
+ httpGraphQLRequest: graphqlRequest,
19
+ context: () => contextFunction({ event })
20
+ });
21
+ if (body.kind === "chunked") {
22
+ throw new Error("Incremental delivery not implemented");
23
+ }
24
+ h3.setHeaders(event, Object.fromEntries(headers));
25
+ event.res.statusCode = status || 200;
26
+ return body.string;
27
+ } catch (error) {
28
+ if (error instanceof SyntaxError) {
29
+ event.res.statusCode = 400;
30
+ return error.message;
31
+ } else {
32
+ throw error;
33
+ }
34
+ }
35
+ });
36
+ }
37
+ async function toGraphqlRequest(event) {
38
+ return {
39
+ method: event.req.method || "POST",
40
+ headers: normalizeHeaders(h3.getHeaders(event)),
41
+ search: normalizeQueryString(event.req.url),
42
+ body: await normalizeBody(event)
43
+ };
44
+ }
45
+ function normalizeHeaders(headers) {
46
+ const headerMap = /* @__PURE__ */ new Map();
47
+ for (const [key, value] of Object.entries(headers)) {
48
+ if (Array.isArray(value)) {
49
+ headerMap.set(key, value.join(","));
50
+ } else if (value) {
51
+ headerMap.set(key, value);
52
+ }
53
+ }
54
+ return headerMap;
55
+ }
56
+ function normalizeQueryString(url) {
57
+ if (!url) {
58
+ return "";
59
+ }
60
+ return url.split("?")[1] || "";
61
+ }
62
+ async function normalizeBody(event) {
63
+ const PayloadMethods = ["PATCH", "POST", "PUT", "DELETE"];
64
+ if (h3.isMethod(event, PayloadMethods)) {
65
+ const body = await h3.readRawBody(event);
66
+ const content = typeof body === "string" ? body : body.toString();
67
+ if (h3.getRequestHeader(event, "content-type") === "application/json") {
68
+ return JSON.parse(content);
69
+ } else {
70
+ return content;
71
+ }
72
+ }
73
+ }
74
+
75
+ exports.startServerAndCreateH3Handler = startServerAndCreateH3Handler;
@@ -0,0 +1,14 @@
1
+ import { BaseContext, ContextFunction, ApolloServer } from '@apollo/server';
2
+ import { H3Event, EventHandler } from 'h3';
3
+
4
+ declare type WithRequired<T, K extends keyof T> = T & Required<Pick<T, K>>;
5
+ interface H3ContextFunctionArgument {
6
+ event: H3Event;
7
+ }
8
+ interface H3HandlerOptions<TContext extends BaseContext> {
9
+ context?: ContextFunction<[H3ContextFunctionArgument], TContext>;
10
+ }
11
+ declare function startServerAndCreateH3Handler(server: ApolloServer<BaseContext>, options?: H3HandlerOptions<BaseContext>): EventHandler;
12
+ declare function startServerAndCreateH3Handler<TContext extends BaseContext>(server: ApolloServer<TContext>, options: WithRequired<H3HandlerOptions<TContext>, 'context'>): EventHandler;
13
+
14
+ export { H3ContextFunctionArgument, H3HandlerOptions, startServerAndCreateH3Handler };
package/dist/index.mjs ADDED
@@ -0,0 +1,71 @@
1
+ import { eventHandler, isMethod, setHeaders, getHeaders, readRawBody, getRequestHeader } from 'h3';
2
+
3
+ function startServerAndCreateH3Handler(server, options) {
4
+ server.startInBackgroundHandlingStartupErrorsByLoggingAndFailingAllRequests();
5
+ const defaultContext = () => Promise.resolve({});
6
+ const contextFunction = options?.context ?? defaultContext;
7
+ return eventHandler(async (event) => {
8
+ if (isMethod(event, "OPTIONS")) {
9
+ return null;
10
+ }
11
+ try {
12
+ const graphqlRequest = await toGraphqlRequest(event);
13
+ const { body, headers, status } = await server.executeHTTPGraphQLRequest({
14
+ httpGraphQLRequest: graphqlRequest,
15
+ context: () => contextFunction({ event })
16
+ });
17
+ if (body.kind === "chunked") {
18
+ throw new Error("Incremental delivery not implemented");
19
+ }
20
+ setHeaders(event, Object.fromEntries(headers));
21
+ event.res.statusCode = status || 200;
22
+ return body.string;
23
+ } catch (error) {
24
+ if (error instanceof SyntaxError) {
25
+ event.res.statusCode = 400;
26
+ return error.message;
27
+ } else {
28
+ throw error;
29
+ }
30
+ }
31
+ });
32
+ }
33
+ async function toGraphqlRequest(event) {
34
+ return {
35
+ method: event.req.method || "POST",
36
+ headers: normalizeHeaders(getHeaders(event)),
37
+ search: normalizeQueryString(event.req.url),
38
+ body: await normalizeBody(event)
39
+ };
40
+ }
41
+ function normalizeHeaders(headers) {
42
+ const headerMap = /* @__PURE__ */ new Map();
43
+ for (const [key, value] of Object.entries(headers)) {
44
+ if (Array.isArray(value)) {
45
+ headerMap.set(key, value.join(","));
46
+ } else if (value) {
47
+ headerMap.set(key, value);
48
+ }
49
+ }
50
+ return headerMap;
51
+ }
52
+ function normalizeQueryString(url) {
53
+ if (!url) {
54
+ return "";
55
+ }
56
+ return url.split("?")[1] || "";
57
+ }
58
+ async function normalizeBody(event) {
59
+ const PayloadMethods = ["PATCH", "POST", "PUT", "DELETE"];
60
+ if (isMethod(event, PayloadMethods)) {
61
+ const body = await readRawBody(event);
62
+ const content = typeof body === "string" ? body : body.toString();
63
+ if (getRequestHeader(event, "content-type") === "application/json") {
64
+ return JSON.parse(content);
65
+ } else {
66
+ return content;
67
+ }
68
+ }
69
+ }
70
+
71
+ export { startServerAndCreateH3Handler };
package/package.json ADDED
@@ -0,0 +1,58 @@
1
+ {
2
+ "name": "@as-integrations/h3",
3
+ "version": "1.0.0",
4
+ "description": "An Apollo Server integration for use with h3 or Nuxt",
5
+ "repository": "apollo-server-integrations/apollo-server-integration-h3",
6
+ "license": "MIT",
7
+ "sideEffects": false,
8
+ "type": "module",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.mjs",
13
+ "require": "./dist/index.cjs"
14
+ }
15
+ },
16
+ "main": "./dist/index.cjs",
17
+ "module": "./dist/index.mjs",
18
+ "types": "./dist/index.d.ts",
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "peerDependencies": {
23
+ "@apollo/server": "^4.0.0",
24
+ "h3": "^0.7.21"
25
+ },
26
+ "devDependencies": {
27
+ "@apollo/server": "^4.0.0",
28
+ "@apollo/server-integration-testsuite": "^4.0.0",
29
+ "@apollo/utils.withrequired": "^1.0.0",
30
+ "@jest/globals": "^29.2.0",
31
+ "@nuxtjs/eslint-config-typescript": "^11.0.0",
32
+ "@typescript-eslint/eslint-plugin": "^5.40.0",
33
+ "@typescript-eslint/parser": "^5.40.0",
34
+ "@vitest/coverage-c8": "^0.24.1",
35
+ "eslint": "^8.25.0",
36
+ "eslint-config-prettier": "^8.5.0",
37
+ "eslint-plugin-unused-imports": "^2.0.0",
38
+ "graphql": "^16.6.0",
39
+ "h3": "^0.7.21",
40
+ "jest": "^29.2.0",
41
+ "prettier": "^2.7.1",
42
+ "standard-version": "^9.5.0",
43
+ "ts-jest": "^29.0.3",
44
+ "typescript": "^4.8.4",
45
+ "unbuild": "^0.8.11",
46
+ "vitest": "^0.24.1"
47
+ },
48
+ "packageManager": "pnpm@7.13.4",
49
+ "scripts": {
50
+ "build": "unbuild",
51
+ "test": "vitest dev",
52
+ "test:integration": "jest",
53
+ "lint": "pnpm lint:eslint && pnpm lint:prettier",
54
+ "lint:eslint": "eslint --ext .ts,.js,.vue,.graphql --ignore-path .gitignore --report-unused-disable-directives .",
55
+ "lint:prettier": "prettier --check --ignore-path .gitignore .",
56
+ "release": "pnpm test && standard-version && git push --follow-tags && pnpm publish"
57
+ }
58
+ }