如何使用 ember-apollo-client 在 ember 中保持数据同步?

How to keep data synchronized in ember using ember-apollo-client?

我有一个使用 Emberember-apollo-client 构建的应用程序。

// templates/collaborators.hbs

// opens an ember-bootstrap modal
{{#bs-button type="success" onClick=(action (mut createCollaborator) true)}}Create collaborator{{/bs-button}}
// submit button in modal triggers "createCollaborator" in controller    

{{#each model.collaborators as |collaborator|}}
    {{collaborator.firstName}} {{collaborator.lastName}}
{{/each}}
// routes/collaborators.js
import Route from '@ember/routing/route';
import { RouteQueryManager } from 'ember-apollo-client';
import query from '../gql/collaborators/queries/listing';

export default Route.extend(RouteQueryManager, {
    model() {
        return this.get('apollo').watchQuery({ query }); 
    }
});

// controllers/collaborator.js
export default Controller.extend({
  apollo: service(),

  actions: {
    createCollaborator() {
      let variables = { 
        firstName: this.firstName, 
        lastName: this.lastName, 
        hireDate: this.hireDate 
      }

      return this.get('apollo').mutate({ mutation, variables }, 'createCollaborator')
        .then(() => {
          this.set('firstName', '');
          this.set('lastName', '');
          this.set('hireDate', '');
      });
    }
  }
});

目前,创建协作者后数据已过时,需要刷新浏览器才能更新。我希望更改立即显示在协作者列表中。

根据我的理解,为了将 GraphQL 与 Ember 一起使用,我应该将 Ember Dataember-graphql-adapter 一起使用,或者只使用 ember-apollo-client。我继续使用 apollo 因为它有更好的文档。

我想我不太明白该怎么做。我应该以某种方式将 storeapollo 中的 watchQuery 结合使用吗?还是其他原因?

稍后编辑

Adi 几乎成功了。

将此留在此处,因为它可能会对其他人有所帮助。

return this.get('apollo').mutate({
    mutation: createCollaborator,
    variables,
    update: (store, { data: { createCollaborator } }) => {
      const data = store.readQuery({ query })

      data.collaborators.push(createCollaborator);

      store.writeQuery({ query, data });
    }
  }, createCollaborator');

您可以使用类似于此的 apollo 命令式存储 API:

return this.get('apollo').mutate(
    { 
        mutation, 
        variables, 
        update: (store, { data: {mutationResult} }) => {
            const cachedData = store.readyQuery({query: allCollaborators})

            const newCollaborator = mutationResult; //this is the result of your mutation

            store.writeQuery({query: allCollaborators, cachedData.push(newCollaborator)})
        }
    }, 'createCollaborator')