在Next.js应用程序中使用GraphQL的推荐方法

时间:2020-03-25 15:32:31

标签: reactjs graphql next.js react-apollo strapi

在我的应用中,我正在使用以下 NPM模块StrapiGraphQLNext.js一起玩:

下一步,我将创建Apollo配置文件,如下例所示:

import { HttpLink } from "apollo-link-http";
import { withData } from "next-apollo";

const config = {
  link: new HttpLink({
    uri: "http://localhost:1337/graphql",
  })
};
export default withData(config);

然后在类组件中,我正在使用静态方法getInitialProps()通过GraphQL查询从Strapi中获取数据。

一切都很好,但是也许还有另外一种更好的方法可以通过React钩子或其他方法来实现?

2 个答案:

答案 0 :(得分:1)

我发现使用apollo-server-microlodash

还有一个有趣的解决方案

快速指南:

  1. 创建Next.js应用程序(示例名称: next-app )并安装所需的软件包

    npm i apollo-server-micro lodash
    
  2. 在您的Next.js应用程序( next-app

    中创建所需文件
    • / next-app / pages / api / graphql / index.js
    • / next-app / pages / api / graphql / resolvers.js
    • / next-app / pages / api / graphql / typeDefs.js
  3. 将代码添加到 index.js

    import { ApolloServer } from 'apollo-server-micro';
    import resolvers from './resolvers';
    import typeDefs from './TypeDef';
    
    const apolloServer = new ApolloServer({
        typeDefs,
        resolvers,
    });
    
    export const config = {
        api: {
            bodyParser: false
        }
    };
    
    export default apolloServer.createHandler({ path: '/api/graphql' });
    
  4. 将代码添加到 typeDefs.js

    import { gql } from 'apollo-server-micro';
    
    const typeDefs = gql`
        type User {
            id: Int!
            name: String!
            age: Int
            active: Boolean!
        }
        type Query {
            getUser(id: Int): User
        }
    `;
    
    export default typeDefs;
    
  5. 将代码添加到 resolvers.js

    import lodash from 'lodash/collection';
    
    const users = [
        { id: 1, name: 'Mario', age: 38, active: true },
        { id: 2, name: 'Luigi', age: 40, active: true},
        { id: 3, name: 'Wario', age: 36, active: false }
    ];
    
    const resolvers = {
        Query: {
            getUser: (_, { id }) => {
                return lodash.find(users, { id });
            }
        }
    };
    
    export default resolvers;
    
  6. 通过运行以下命令并检查graphql URL http://localhost:3000/api/graphql

    测试您的Next.js应用程序( next-app )。
    npm run dev
    

答案 1 :(得分:1)

我发现了一个更好的Next.js和GraphQL挂钩解决方案。

我想与您分享。我们开始吧。

注意:我假设您已经安装了Next.js应用程序。如果没有,请遵循此guide

要构建此解决方案,我们需要:

1。。运行npm命令:

npm install --save @apollo/react-hooks apollo-cache-inmemory apollo-client apollo-link-http graphql graphql-tag isomorphic-unfetch next-with-apollo

2。。创建Appolo配置文件,例如在文件夹./config中,并将其命名为appollo.js。文件代码如下:

import { ApolloClient } from "apollo-client";
import { InMemoryCache } from "apollo-cache-inmemory";
import withApollo from "next-with-apollo";
import { createHttpLink } from "apollo-link-http";
import fetch from "isomorphic-unfetch";

const GRAPHQL_URL = process.env.BACKEND_URL || "https://api.graphql.url";

const link = createHttpLink({
  fetch,
  uri: GRAPHQL_URL
});

export default withApollo(
  ({ initialState }) =>
    new ApolloClient({
      link: link,
      cache: new InMemoryCache()
        .restore(initialState || {})
    })
);

3。。使用以下代码在_app.js文件夹中创建./pages文件(包装类型):

import React from "react";
import Head from "next/head";
import { ApolloProvider } from "@apollo/react-hooks";
import withData from "../config/apollo";

const App = ({ Component, pageProps, apollo }) => {
  return (
    <ApolloProvider client={apollo}>
      <Head>
        <title>App Title</title>
      </Head>
      <Component {...pageProps} />
    </ApolloProvider>
  )
};

export default withData(App);

4。。创建可重复使用的查询组件,例如./components/query.js

import React from "react";  
import { useQuery } from "@apollo/react-hooks";

const Query = ({ children, query, id }) => {  
  const { data, loading, error } = useQuery(query, {
    variables: { id: id }
  });

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {JSON.stringify(error)}</p>;
  return children({ data });
};

export default Query;

5。。为通过GraphQL提取的数据创建一个组件

import React from "react";
import Query from "../components/query";
import GRAPHQL_TEST_QUERY from "../queries/test-query";

const Example = () => {  
  return (
    <div>
      <Query query={GRAPHQL_TEST_QUERY} id={null}>
        {({ data: { graphqlData } }) => {
          return (
            <div>
              {graphqlData.map((fetchedItem, i) => {
                return (
                  <div key={fetchedItem.id}>
                    {fetchedItem.name}
                  </div>
                );
              })}
            </div>
          );
        }}
      </Query>
    </div>
  );
};

export default Example;

6。。在./queries/test-query内创建我们的GraphQL查询。 注意:我假设我们可以通过GraphQL访问示例数据和属性idname

import gql from "graphql-tag";

const GRAPHQL_TEST_QUERY = gql`
  query graphQLData {
    exampleTypeOfData {
      id
      name
    }
  }
`;

export default GRAPHQL_TEST_QUERY;

7。以显示我们的结果,在index.js文件夹中创建./pages文件(主页),并显示以下代码:

import Example from './components/example';

const Index = () => <div><Example /></div>

export default Index;

仅此而已。.根据需要享受并扩展此解决方案。.