标签: apollo

GraphQL 突变后的 updateQueries 不适用于 Apollo 客户端

在我的应用程序中发送createMessage突变后,我想ApolloStore使用updateQueries.

我的设置如下:

const ChatWithAllMessages = graphql(allMessages, {name: 'allMessagesQuery'})(Chat)
export default graphql(createMessage, {
   props({ownProps, mutate}) {
    return {
      createMessageMutation(text, conversationId) {
        return mutate({
          variables: { text, conversationId },
          updateQueries: {
            allConversations: (previousState, {mutationResult}) => {
              console.log('Chat - did send mutation for allConversationsQuery: ', previousState, mutationResult)
              return ...
            }
          }
        })
      }
    }
  }
})(ChatWithAllMessages)
Run Code Online (Sandbox Code Playgroud)

createMessageMutation在代码中这样调用:

_onSend = () => {
  this.props.createMessageMutation(this.state.message, this.props.conversationId)
}
Run Code Online (Sandbox Code Playgroud)

通过此设置,我希望updateQueries执行我在值中指定的函数,但是,这似乎不会发生(日志记录语句永远不会被打印)。

作为参考,查询如下allConversation所示ApolloStore

在此输入图像描述

另外,我的 JS …

javascript apollo graphql apollostack react-apollo

5
推荐指数
1
解决办法
2572
查看次数

应如何通过 GraphQL 突变对列表中的项目进行重新排序并更新多个对象?

我正在使用的堆栈


我正在尝试做什么

我正在构建一个向用户呈现多个列表的应用程序,每个列表都包含多张卡片。在列表中,用户可以对卡片重新排序。卡片也可以从一个列表移动到另一个列表,这会更改卡片的父列表以及卡片在源列表和目标列表中的顺序。

这是一个 GIF,显示了我的应用程序中的卡片/列表和重新排序的 UI。您在这里看到的都是在客户端发生的,并且更改不会持久保存到数据库中:

从我的应用程序拖放的示例

这是我用来构建 UI 的查询:

const foo = gql`
  query foo {
    getAccount(id: "xxxxx") {
      cardLists {        
        edges {
          node {
            id
            name
            cards(orderBy: {field: order, direction: ASC}) {
              edges {
                node {
                  id
                  name
                  order
                }
              }
            }
          }
        }
      }
    }
  }
`
Run Code Online (Sandbox Code Playgroud)

这是来自 Vue Draggable 项目的 GIF,它进一步说明了我正在做的事情(注意数据中的“order”值):

Vue Draggable 项目中的拖放示例


问题

我不知道如何构建突变来处理重新排序,以便正确保留移动的卡以及源列表和目标列表的排序更改。

在 Scaphold 中构建模式意味着我需要(我认为)使用它提供的突变。我没有找到将多个卡片和列表传递给单个突变的方法,以便我可以立即更新所有内容。

以下是 Scaphold.io 中示例项目的端点:https://us-west-2.api.scaphold.io/graphql/soreorderingexample

这是 Scaphold.io 生成的架构:https://d3uepj124s5rcx.cloudfront.net/items/1e1m2q3F170C2G3M0v2p/schema.json


我的问题

  • 在 GraphQL …

apollo graphql scaphold

5
推荐指数
1
解决办法
1978
查看次数

GraphQL Apollo iOS 客户端响应标头

我正在使用 Apollo iOS 客户端进行 GraphQL 查询。我需要在标头中传递身份验证令牌,我可以使用下面的代码来实现 -

let apolloAuth: ApolloClient = {
            let configuration = URLSessionConfiguration.default
            let token = "Bearer \(UserDefaults.standard.string(forKey: "UserToken") ?? "")"
            // Add additional headers as needed
            configuration.httpAdditionalHeaders = ["Authorization": token]

            let url = URL(string: "...URL.../graphql")!

            return ApolloClient(networkTransport: HTTPNetworkTransport(url: url, configuration: configuration))
        }()
Run Code Online (Sandbox Code Playgroud)

我的获取查询如下 -

apolloAuth.fetch(query: referralQuery){ (result, error) in

        if let error = error {
            print(error.localizedDescription)
            return
        }else{
            self.referralId = result?.data?.referrals?.id
        }

    }
Run Code Online (Sandbox Code Playgroud)

现在,我的服务器在每个请求后返回刷新的身份验证令牌,这是响应标头的一部分。我需要从响应标头获取令牌,但我无法找到方法来做到这一点。有人可以指导我吗?

ios apollo graphql swift3

5
推荐指数
1
解决办法
2304
查看次数

GraphQL 突变中的条件参数?

假设我有一个mutationtypearg 的对象。根据typeI 的值,可以接受mutation另一个arg输入类型,也可以mutation不使用它进行调用。

如何实施graphql?我知道对于查询有@skip指令@include(对于字段,而不是参数)。有类似的东西吗mutations?或者我应该将附加参数指定为可选,然后在服务器上进行验证?

apollo graphql

5
推荐指数
1
解决办法
3093
查看次数

使用 Apollo 客户端和 graphql-go 时 Graphql 查询出现“未知类型 Int”错误

我有一个使用graphql-go实现的 graphql 服务器,并且我在前端使用 Apollo。不带参数的简单查询和使用输入对象类型的突变工作正常,但由于某种原因在查询中传递标量类型参数会返回错误:

[{"message":"Unknown type \"Int\".","locations":[{"line":1,"column":19}]}]
Run Code Online (Sandbox Code Playgroud)

我的使用再简单不过了;在客户端,我的查询是:

export const GET_CLIENT = gql`
  query client($id: Int) {
  client(id: $id) {
    id
    name
  }
}`
Run Code Online (Sandbox Code Playgroud)

它在像这样的组件中使用:

<Query
  query={GET_CLIENT}
  variables={{
    id: 1
  }} />
Run Code Online (Sandbox Code Playgroud)

它在后端解析为该字段:

// ClientQuery takes an ID and returns one client or nil
var ClientQuery = &graphql.Field{
Type: ClientType,
Args: graphql.FieldConfigArgument{
    "id": &graphql.ArgumentConfig{
        Type: graphql.Int,
    },
},
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
    return p.Context.Value("service").(*model.Service).FindClientByID(id)
},
}
Run Code Online (Sandbox Code Playgroud)

我尝试过传递输入对象、字符串等,但后端似乎没有满足任何查询参数、标量或其他参数。我尝试过 graphql-go 的 master 和 v0.7.5。我错过了什么吗?非常感谢帮助,这种基本的东西成为如此巨大的阻碍者感觉很奇怪。

go apollo graphql

5
推荐指数
1
解决办法
2万
查看次数

测试运行完成后,Jest 一秒钟都没有退出。--检测打开句柄

我将测试使用 Jest 运行的后端服务器。有时会成功,但有时会显示这样的错误。 在此输入图像描述

因此,如果我按照建议使用 --detectOpenHandles 标志,它总是成功而不显示任何错误。这是测试代码。

  it("should be able to initialize a server (development)",async (done) => {
      // Before main() is called there is no active connection:

    expect(connection.readyState).toBe(0);
    return main({
      env: "dev",
      port: PORT,
    })
    .then(async (server: ApolloServer) => {
        // After main() got called, there is an active connection:
      expect(connection.readyState).toBe(1);
      await server.stop();
      done();
    })
  });
  afterAll(async () => {
    await connection.close(); //connection is mongoose.connection
  });
Run Code Online (Sandbox Code Playgroud)

我不知道为什么它在标记时失败。奇怪的是,有时成功,有时失败。

谢谢

apollo jestjs graphql apollo-server

5
推荐指数
1
解决办法
1051
查看次数

AWS AppSync:如何通过 DynamoDB 返回有效的 JSON

我有一个 AppSync GraphQL API,可以对 DynamoDB 进行查询并返回 JSON 字符串,但是在我的响应映射模板中,我使用此处$util.parseJson()列出的内置函数- 但我仍然在查询窗口中返回 JSON 字符串,并且在我的 React 应用程序中请求数据时。

架构文件,我有一个 AWSJSON 类型的普通 ID 和地址字段。

type Venue {
  id: ID!
  address: AWSJSON
}
Run Code Online (Sandbox Code Playgroud)

运行突变时,我通常通过快速运行地址对象JSON.stringify(addressObj),并将对象格式化为带有“\”转义的字符串,这意味着它可以插入到 DynamoDB 中。

请求映射模板

{
  "version": "2017-02-28",
  "operation": "GetItem",
  "key": {
    "id": $util.dynamodb.toDynamoDBJson($ctx.args.id),
  }
}
Run Code Online (Sandbox Code Playgroud)

响应映射模板

#set($result = $ctx.result)

## address - parse back to JSON
#set($result.address = $util.parseJson($ctx.result.address))

## Return the result
$util.toJson($result)
Run Code Online (Sandbox Code Playgroud)

创建新变量然后将值分配给该值的想法parseJSON取自如何使用 appsync 从 DynamoDB 返回 JSON 对象?。因此,如下所示,我正在通过似乎正确的方法来解析该值,将其从字符串化 JSON 转换为对象 - 但它似乎不起作用。 …

json amazon-web-services amazon-dynamodb apollo aws-appsync

5
推荐指数
1
解决办法
7076
查看次数

API.swift 文件未更新:Apollo GraphQL iOS

我正在将 GraphQL API 与 iOS 项目一起使用。我的 .graphql 文件是,

mutation SigninQuery($email: String! , $password: String!) {
    signin(email: $email, password: $password) {
        result {
            token
            firstName
            lastName
            profileImage
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我的文件按以下顺序放置,

项目

  • ->应用程序委托
  • ->信息.plist
  • ->schema.json
  • -->Graphql[文件夹]

  • ->API.swift

  • ->ApiFile.graphql

我的 API.swift 文件仍然仅存在标头

进口阿波罗

。任何人都可以帮我找到解决方案

ios apollo swift graphql

5
推荐指数
1
解决办法
2897
查看次数

如果 Apollo GraphQL 令牌无效或已过期,则 NextAuth.js 注销

在尝试访问后端(Apollo GraphQL)时清除 NextAuth.js 会话的最佳方法是什么,并且由于令牌已过期或无效而返回 401?

我想到了errorLinkand signout,但据我所知signout不能在服务器端使用getServerSideProps,而只能在客户端使用。

推荐的方法是什么?有没有其他方法可以实现中间件来处理这种情况?

这将是errorLink我正在尝试实现的概念的证明,代码被困在其中,if但我无法使用,signOut()因为它仅在客户端可用

const errorLink = onError(({ graphQLErrors }) => {
   if (graphQLErrors?.[0]?.message === 'Unauthenticated.') {
    // signOut();
  }
});

function createApolloClient(session) {
  return new ApolloClient({
    cache: new InMemoryCache(),
    ssrMode: typeof window === 'undefined',
    link: from([
      errorLink,
      createUploadLink({
        uri: GRAPHQL_URI,
        credentials: 'same-origin',
        headers: { Authorization: session?.accessToken ? `Bearer ${session.accessToken}` : '' },
      }),
    ]),
  });
}
Run Code Online (Sandbox Code Playgroud)

谢谢

apollo reactjs graphql next.js next-auth

5
推荐指数
1
解决办法
1121
查看次数

阿波罗角中的令牌刷新错误

我正在使用 apollo-angular 构建一个前端应用程序。在我的应用程序中,我使用带有短期访问令牌和长期刷新令牌的 JWT 身份验证系统(它们在仅 HTTP cookie 中传输,而不是开始存储在 HTTP 标头中)。

当我运行我的应用程序时,我可以成功登录,但是当访问令牌过期时,我收到以下错误并且我在浏览器上看不到任何内容。
Error: Network error: Cannot read property 'refresh' of undefined at new ApolloError

我的代码如下:

GraphQLModule(它是在 AppModule 中导入的)(部分基于此问题

import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

import { ApolloModule, APOLLO_OPTIONS } from 'apollo-angular';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { HttpLinkModule, HttpLink } from 'apollo-angular-link-http';
import { ApolloLink, Observable } from 'apollo-link';
import { onError } from 'apollo-link-error';

import { AuthService } from …
Run Code Online (Sandbox Code Playgroud)

apollo graphql angular apollo-angular

5
推荐指数
1
解决办法
145
查看次数