首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >阿波罗服务器+ Next.js - GraphQL模式不更新

阿波罗服务器+ Next.js - GraphQL模式不更新
EN

Stack Overflow用户
提问于 2020-11-19 20:17:43
回答 2查看 3.2K关注 0票数 2

我有一个阿波罗GraphQL / Next.js应用程序。在更改了graphql模式并导航到"http://localhost:3000/api/graphql"“的graphql操场后,在操场和我的应用程序中仍然引用了旧模式。

我尝试过清除节点模块并运行npm安装、清除缓存、重新启动所有内容,但我无法理解为什么我的模式没有更新。我是不是遗漏了一些关键的模式更新步骤?

这里是我对Series和Publisher的模式(注意,SeriesInput需要发布者,而不是PublisherInput):

代码语言:javascript
复制
type Series {
    _id: ID!
    name: String
    altID: String
    publisher: Publisher!
    comics: [Comic]
}

input SeriesInput {
    _id: ID
    name: String!
    altID: String
    publisher: Publisher!
    comics: [Comic]
}

type Mutation {
    addSeries(series: SeriesInput): Series
}

type Query {
    series: [Series]
}

-------------------------

type Publisher {
    _id: ID!
    name: String
    altID: String
    series: [Series]
}

input PublisherInput {
    _id: ID!
    name: String!
    altID: String
    series: [Series]
}

type Mutation {
    addPublisher(publisher: PublisherInput): Publisher
}

type Query {
    publishers: [Publisher]
}

这里 是我在GraphQL游乐场中收到的错误消息,这是因为旧的系列模式需要一个PublisherInput类型,该类型的强制字段为"Name“,而我没有传递。

这里是我的graphql阿波罗服务器代码,在这里我使用mergeResolvers和mergeTypeDefs将所有的graphql文件合并成一个单一的模式:

代码语言:javascript
复制
import { ApolloServer } from "apollo-server-micro";
import { mergeResolvers, mergeTypeDefs } from "graphql-tools";
import connectDb from "../../lib/mongoose";

// Mutations and resolvers
import { comicsResolvers } from "../../api/comics/resolvers";
import { comicsMutations } from "../../api/comics/mutations";
import { seriesResolvers } from "../../api/series/resolvers";
import { seriesMutations } from "../../api/series/mutations";
import { publishersResolvers } from "../../api/publishers/resolvers";
import { publishersMutations } from "../../api/publishers/mutations";

// GraphQL Schema
import Publishers from "../../api/publishers/Publishers.graphql";
import Series from "../../api/series/Series.graphql";
import Comics from "../../api/comics/Comics.graphql";

// Merge type resolvers, mutations, and type definitions
const resolvers = mergeResolvers([
    publishersMutations,
    publishersResolvers,
    seriesMutations,
    seriesResolvers,
    comicsMutations,
    comicsResolvers,
]);
const typeDefs = mergeTypeDefs([Publishers, Series, Comics]);

// Create apollo server and connect db
const apolloServer = new ApolloServer({ typeDefs, resolvers });
export const config = {
    api: {
        bodyParser: false,
    },
};
const server = apolloServer.createHandler({ path: "/api/graphql" });
export default connectDb(server);

这里是我的阿波罗/next.js代码,我使用了Vercel的文档:

代码语言:javascript
复制
 * Code copied from Official Next.js documentation to work with Apollo.js
 * https://github.com/vercel/next.js/blob/6e77c071c7285ebe9998b56dbc1c76aaf67b6d2f/examples/with-apollo/lib/apollo.js
 */

import React, { useMemo } from "react";
import Head from "next/head";
import { ApolloProvider } from "@apollo/react-hooks";
import { ApolloClient } from "apollo-client";
import { InMemoryCache } from "apollo-cache-inmemory";
import { HttpLink } from "apollo-link-http";
import fetch from "isomorphic-unfetch";

let apolloClient = null;

/**
 * Creates and provides the apolloContext
 * to a next.js PageTree. Use it by wrapping
 * your PageComponent via HOC pattern.
 * @param {Function|Class} PageComponent
 * @param {Object} [config]
 * @param {Boolean} [config.ssr=true]
 */
export function withApollo(PageComponent, { ssr = true } = {}) {
    const WithApollo = ({ apolloClient, apolloState, ...pageProps }) => {
        const client = useMemo(() => apolloClient || initApolloClient(apolloState), []);
        return (
            <ApolloProvider client={client}>
                <PageComponent {...pageProps} />
            </ApolloProvider>
        );
    };

    // Set the correct displayName in development
    if (process.env.NODE_ENV !== "production") {
        const displayName = PageComponent.displayName || PageComponent.name || "Component";

        if (displayName === "App") {
            console.warn("This withApollo HOC only works with PageComponents.");
        }

        WithApollo.displayName = `withApollo(${displayName})`;
    }

    if (ssr || PageComponent.getInitialProps) {
        WithApollo.getInitialProps = async (ctx) => {
            const { AppTree } = ctx;

            // Initialize ApolloClient, add it to the ctx object so
            // we can use it in `PageComponent.getInitialProp`.
            const apolloClient = (ctx.apolloClient = initApolloClient());

            // Run wrapped getInitialProps methods
            let pageProps = {};
            if (PageComponent.getInitialProps) {
                pageProps = await PageComponent.getInitialProps(ctx);
            }

            // Only on the server:
            if (typeof window === "undefined") {
                // When redirecting, the response is finished.
                // No point in continuing to render
                if (ctx.res && ctx.res.finished) {
                    return pageProps;
                }

                // Only if ssr is enabled
                if (ssr) {
                    try {
                        // Run all GraphQL queries
                        const { getDataFromTree } = await import("@apollo/react-ssr");
                        await getDataFromTree(
                            <AppTree
                                pageProps={{
                                    ...pageProps,
                                    apolloClient,
                                }}
                            />
                        );
                    } catch (error) {
                        // Prevent Apollo Client GraphQL errors from crashing SSR.
                        // Handle them in components via the data.error prop:
                        // https://www.apollographql.com/docs/react/api/react-apollo.html#graphql-query-data-error
                        console.error("Error while running `getDataFromTree`", error);
                    }

                    // getDataFromTree does not call componentWillUnmount
                    // head side effect therefore need to be cleared manually
                    Head.rewind();
                }
            }

            // Extract query data from the Apollo store
            const apolloState = apolloClient.cache.extract();

            return {
                ...pageProps,
                apolloState,
            };
        };
    }

    return WithApollo;
}

/**
 * Always creates a new apollo client on the server
 * Creates or reuses apollo client in the browser.
 * @param  {Object} initialState
 */
function initApolloClient(initialState) {
    // Make sure to create a new client for every server-side request so that data
    // isn't shared between connections (which would be bad)
    if (typeof window === "undefined") {
        return createApolloClient(initialState);
    }

    // Reuse client on the client-side
    if (!apolloClient) {
        apolloClient = createApolloClient(initialState);
    }

    return apolloClient;
}

/**
 * Creates and configures the ApolloClient
 * @param  {Object} [initialState={}]
 */
function createApolloClient(initialState = {}) {
    // Check out https://github.com/zeit/next.js/pull/4611 if you want to use the AWSAppSyncClient
    return new ApolloClient({
        ssrMode: typeof window === "undefined", // Disables forceFetch on the server (so queries are only run once)
        link: new HttpLink({
            uri: "http://localhost:3000/api/graphql", // Server URL (must be absolute)
            credentials: "same-origin", // Additional fetch() options like `credentials` or `headers`
            fetch,
        }),
        cache: new InMemoryCache().restore(initialState),
    });
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-06-04 18:40:14

我遇到了同样的问题,原因是下一个js处理缓存的方式。删除.next文件夹,然后重新启动服务器,这将解决问题。

票数 2
EN

Stack Overflow用户

发布于 2020-12-01 02:41:27

好吧,我花了将近5天的时间试图找出我做错了什么,或者如果阿波罗服务器在生产时缓存模式,任何找到阿波罗客户端来源的服务器都指向错误的服务器。

也许你也应该好好检查一下。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64919332

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档