如何在 NextJS 应用程序中使用 SWR 从 GraphQL 的 Apollo Server 实例呈现数据?

问题描述 投票:0回答:1

I can successfully view my

GraphQL query
via
apollo-graphql-studio
:
resolver
已正确配置,但我不确定如何呈现数据。

我知道

next-js
swr
react-hook
是高性能的,所以我想通过
swr
方法获取数据:

import useSWR from "swr";

const Query = `
  books {
    title
  }
`;

export default function Home() {
  const fetcher = async () => {
    const response = await fetch("/api/graphql", {
      body: JSON.stringify({ query: Query }),
      headers: { "Content-type": "application/json" },
      method: "POST"
    });
    const { data } = await response.json();
    return data;
  };

  const { data, error } = useSWR([Query], fetcher);

  if (error) return <div>failed to load</div>;
  if (!data) return <div>loading...</div>;
  return (
    <div>
      <div>hello {data?.books?.title}</div>
    </div>
  );
}

这只是返回

loading...
所以数据显然没有正确获取。虽然,正如我所说,我可以通过
Apollo-graphql-studio
IDE
检索它。

控制台错误是API路由上的

400 Bad Request
/api/graphql
,所以这就是问题所在。

如何呈现数据?

这是 GraphQL API:

import Cors from 'micro-cors'
import { gql, ApolloServer } from 'apollo-server-micro'
import { Client, Map, Paginate, Documents, Collection, Lambda, Get } from 'faunadb'

const client = new Client({
    secret: process.env.FAUNA_SECRET,
    domain: "db.fauna.com",
})

export const config = {
    api: {
        bodyParser: false
    }
}

const typeDefs = gql`
    type Book {
        title: String
        author: String
    }

    type Query {
        books: [Book]
    }
`

const resolvers = {
    Query: {
        books: async () => {
            const response = await client.query(
                Map(
                    Paginate(Documents(Collection('Book'))),
                    Lambda((x) => Get(x))
                )
            )
            const books = response.data.map(item => item.data)
            return [...books]
        },
    },
}
const cors = Cors()

const apolloServer = new ApolloServer({
    typeDefs,
    resolvers,
    context: ({ req }) => {

    },
    introspection: true,
    playground: true,
})

const serversStart = apolloServer.start()

export default cors(async (req, res) => {
    if (req.method === "OPTIONS") {
        res.end();
        return false;
    }

    await serversStart;
    await apolloServer.createHandler({ path: '/api/graphql' })(req, res)
})
javascript graphql next.js apollo-server
1个回答
0
投票

这就是我使用 Apollo Client 的方式:

import { ApolloClient, InMemoryCache, createHttpLink } from "@apollo/client";

const defaultOptions: any = {
  watchQuery: {
    fetchPolicy: "no-cache",
    errorPolicy: "ignore",
  },
  query: {
    fetchPolicy: "no-cache",
    errorPolicy: "all",
  },
};

const cache = new InMemoryCache({
  resultCaching: false,
});


const link = createHttpLink({
  uri: process.env.NEXT_PUBLIC_GRAPQL_URI,
  
});

export const client: any = new ApolloClient({
 
  connectToDevTools: true,
  link,
  cache,
  defaultOptions,
});

然后在前端:

const { data, error } = useSWR(MY_QUERY, query => client.query({ query }));

Apollo Server 应该也类似

© www.soinside.com 2019 - 2024. All rights reserved.