Giter VIP home page Giter VIP logo

apollo-server-integration-h3's Introduction

Apollo Server integration for h3 and nuxt

npm version npm downloads Github Actions Codecov

This package allows you to easily integrate Apollo Server with your h3 or Nuxt 3 application.

For defining a GraphQL server in Nuxt 3, you may want to have a look at the GraphQL server toolkit Nuxt module.

Installation

# npm
npm install @apollo/server graphql @as-integrations/h3

# yarn
yarn add @apollo/server graphql @as-integrations/h3

# pnpm
pnpm add @apollo/server graphql @as-integrations/h3

Usage with Nuxt v3

Create a Server API Route that configures an instance of Apollo Server as described in the documentation and then exports it as the event handler:

import { ApolloServer } from '@apollo/server'
import { startServerAndCreateH3Handler } from '@as-integrations/h3'

const apollo = new ApolloServer({
  // Specify server options like schema and resolvers here
})

export default startServerAndCreateH3Handler(apollo, {
  // Optional: Specify context
  context: (event) => {...}
})

Usage with h3

Create and configure an instance of Apollo Server as described in the documentation and then register it as a route handler in your h3 application.

import { createApp } from 'h3'
import { ApolloServer } from '@apollo/server'
import { startServerAndCreateH3Handler } from '@as-integrations/h3'

const apollo = new ApolloServer({
  // Specify server options like schema and resolvers here
})

export const app = createApp()
app.use(
  '/api',
  startServerAndCreateH3Handler(apollo, {
    // Optional: Specify context
    context: (event) => {...}
  })
)

Then run your h3 server as usual, e.g. with npx --yes listhen -w --open ./app.ts. Visit http://localhost:3000/api in your browser to access the Apollo Sandbox.

๐Ÿ’ป Development

  • Clone this repository
  • Enable Corepack using corepack enable (use npm i -g corepack for Node.js < 16.10).
  • Install dependencies using pnpm install.
  • Run tests using pnpm test and integration tests via pnpm test:integration.

License

Made with ๐Ÿ’›

Published under MIT License.

apollo-server-integration-h3's People

Contributors

github-actions[bot] avatar renovate[bot] avatar tobiasdiez avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

apollo-server-integration-h3's Issues

[Question] How to set the response status code

When using startServerAndCreateH3Handler() to handle GraphQL requests, I am not sure how to set the response status code within the resolver.
I have tried several patterns and the result is either a 200 OK returned or a server error.

// 1. 200 OK is returned
setResponseStatus(context.event, 400);
throw new Error('Error message');


// 2. 200 OK is returned
throw createError({
  statusCode: 400,
  statusMessage: 'Error message',
});


// 3. 400 is returned but a server error occurs
// [nuxt] [request error] [unhandled] [500] Cannot set headers after they are sent to the client
context.event.res.statusCode = 400;
context.event.res.end('Error message');


// 4. 400 is returned but a server error occurs
return sendError(context.event, createError({
  statusCode: 400,
  statusMessage: 'Error message',
}));
@as-integrations/h3 v1.1.6

% npx nuxt info
------------------------------
- Operating System: Darwin
- Node Version:     v18.14.2
- Nuxt Version:     3.7.1
- CLI Version:      3.8.0
- Nitro Version:    2.6.3
- Package Manager:  [email protected]
- Builder:          -
- User Config:      devtools, rootDir
- Runtime Modules:  -
- Build Modules:    -
------------------------------

Failing integration test: throws an error if invalid content-type

These are the headers send to executeHTTPGraphQLRequest

{
      'host' => 'localhost:33787',
      'accept-encoding' => 'gzip, deflate',
      'content-type' => 'text/plain',
      'apollo-require-preflight' => 't',
      'content-length' => '36',
      'connection' => 'close'
}

This seems to be correct to me, so maybe this is an issue in apollo/server? Or are integrations supposed to filter out non-json requests?

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

This repository currently has no open or pending branches.

Detected dependencies

github-actions
.github/workflows/ci.yml
  • actions/checkout v3
  • actions/setup-node v3
  • codecov/codecov-action v3
.github/workflows/release.yml
  • google-github-actions/release-please-action v3
  • actions/checkout v3
  • actions/setup-node v3
npm
package.json
  • @apollo/server ^4.0.0
  • @apollo/server-integration-testsuite ^4.0.0
  • @apollo/utils.withrequired ^1.0.0
  • @jest/globals ^29.2.0
  • @nuxtjs/eslint-config-typescript ^11.0.0
  • @typescript-eslint/eslint-plugin ^5.40.0
  • @typescript-eslint/parser ^5.40.0
  • @vitest/coverage-c8 ^0.24.3
  • eslint ^8.25.0
  • eslint-config-prettier ^8.5.0
  • eslint-plugin-unused-imports ^2.0.0
  • graphql ^16.6.0
  • h3 ^0.8.1
  • jest ^29.2.0
  • prettier ^2.7.1
  • standard-version ^9.5.0
  • ts-jest ^29.0.3
  • typescript ^4.8.4
  • unbuild ^0.9.4
  • vitest ^0.24.3
  • @apollo/server ^4.0.0
  • h3 ^0.8.1
  • pnpm 7.13.5

  • Check this box to trigger a request for Renovate to run again on this repository

Query will throw an error

Environment

  • Operating System: Windows_NT
  • Node Version: v18.17.1
  • Nuxt Version: 3.7.2
  • CLI Version: 3.8.3
  • Nitro Version: 2.6.3
  • Package Manager: [email protected]
  • Builder: -
  • User Config: devtools, typescript, imports, modules
  • Runtime Modules: @pinia/[email protected], [email protected]
  • Build Modules: -

Reproduction

https://github.com/awdr74100/nuxt-graphql-integration

Describe the bug

Thanks @tobiasdiez for developing such a great package!

I used nuxt-graphql-client combined with this package to achieve the purpose of graphql full end, but encountered a strange problem:

export default defineNuxtConfig({
  modules: [
    [
      "nuxt-graphql-client",
      {
        clients: {
          default: {
            host: "http://localhost:3000/api/graphql",
            schema: "./server/schema.graphql",
          },
        },
      },
    ],
  ],
});
import { ApolloServer } from "@apollo/server";
import { startServerAndCreateH3Handler } from "@as-integrations/h3";
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { resolve } from "node:path";

interface User {
  id: number;
  name: string;
  email: string;
  website: string;
}

interface Photo {
  id: number;
  title: String;
  url: String;
}

const resolvers = {
  Query: {
    user: async (parent: any, args: { id: number }, context: any) => {
      const url = `https://jsonplaceholder.typicode.com/users/${args.id}`;

      return $fetch<User>(url, { method: "GET" });
    },
    users: async (parent: any, args: {}, context: any) => {
      const url = `https://jsonplaceholder.typicode.com/users`;

      return $fetch<User[]>(url, { method: "GET" });
    },
    photo: async (parent: any, args: { id: number }, context: any) => {
      const url = `https://jsonplaceholder.typicode.com/photos/${args.id}`;

      return $fetch<Photo>(url, { method: "GET" });
    },
  },
};

const apollo = new ApolloServer({
  typeDefs: readFileSync(
    resolve(fileURLToPath(import.meta.url), "../../../server/schema.graphql"),
    "utf-8"
  ),
  resolvers,
});

export default startServerAndCreateH3Handler(apollo);
<template>
  <h1>Use useFetch()</h1>
  <pre v-if="data">{{ data }}</pre>
</template>

<script setup lang="ts">
const { data } = await useFetch("/api/users"); // success
</script>

<template>
  <h1>Use useAsyncGql() (https://jsonplaceholder.ir/graphql)</h1>
  <pre v-if="data">{{ data }}</pre>
</template>

<script setup lang="ts">
useGqlHost("https://jsonplaceholder.ir/graphql");

const { data } = await useAsyncGql("getUsers"); // success
</script>

<template>
  <h1>Use useAsyncGql() (http://localhost:3000/api/graphql)</h1>
  <pre v-if="data">{{ data }}</pre>
</template>

<script setup lang="ts">
const { data } = await useAsyncGql("getUsers"); // fail
</script>

I thought it was nuxt-graphql-client problem, but the second query worked normally. The key seemed to be that the server returned null data, causing a problem with SSR.

Also, I would like to ask which client module currently works best with this module?

Activate rennovate bot

@trevor-scheer could you please activate rennovate for this repo. Since this since to be configured on the org level, I don't have the necessary rights to do so. Thanks!

Configure release-please

https://github.com/google-github-actions/release-please-action

Todo:

  • Create PAT to run checks on created PRs

@trevor-scheer I cannot create a fine-grained PAT for this repo. Under https://github.com/settings/personal-access-tokens/new, I cannot select the "apollo-server-integrations" as the resource owner. I'm not sure if one has to be admin of the org or if the org policies prevent PATs. For the latter, could you please check https://docs.github.com/en/enterprise-cloud@latest/organizations/managing-programmatic-access-to-your-organization/setting-a-personal-access-token-policy-for-your-organization ? Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.