Проблемы с установкой Vuex-ORM GraphQL

#graphql #vuex #vuex-orm

#graphql #vuex #vuex-orm

Вопрос:

Я установил плагин Vuex-ORM Graphql в существующий проект Nuxt с помощью Laravel / GraphQL API, чтобы попытаться избежать использования кэша Apollo. Однако в одном из моих компонентов я запускаю:

 <script>
  import Notification from '~/data/models/notification';

  export default {
    computed: {
      notifications: () => Notification.all()
    },
    async mounted () {
      await Notification.fetch();
    }
  }
</script>
 

однако я получаю сообщение об ошибке [vuex] unknown action type: entities/notifications/fetch .

Я просмотрел журнал отладки и нашел несколько доступных способов получения (entities / notifications / query, entities / notifications / all, entities / notifications / find и entities / notifications / findIn). Я попытался запустить await Notification.all() в смонтированном методе, который устранил ошибку, однако при просмотре в Vuex объект данных уведомлений пуст.

Вот остальная часть моей настройки:

nuxt.config.js

 plugins: [
  '~/plugins/vuex-orm',
  '~/plugins/graphql'
],
 

plugins/vuex-orm.js

 import VuexORM from '@vuex-orm/core';
import database from '~/data/database';

export default ({ store }) => {
  VuexORM.install(database)(store);
};
 

plugins/graphql.js

 /* eslint-disable import/no-named-as-default-member */
import VuexORM from '@vuex-orm/core';
import VuexORMGraphQL from '@vuex-orm/plugin-graphql';
import { HttpLink } from 'apollo-link-http';
import fetch from 'node-fetch';
import CustomAdapter from '~/data/adapter';
import database from '~/data/database';

// The url can be anything, in this example we use the value from dotenv
export default function ({ app, env }) {
  const apolloClient = app?.apolloProvider?.defaultClient;
  const options = {
    adapter: new CustomAdapter(),
    database,
    url: env.NUXT_ENV_BACKEND_API_URL,
    debug: process.env.NODE_ENV !== 'production'
  };

  if (apolloClient) {
    options.apolloClient = apolloClient;
  } else {
    options.link = new HttpLink({ uri: options.url, fetch });
  }

  VuexORM.use(VuexORMGraphQL, options);
};
 

/data/adapter.js

 import { DefaultAdapter, ConnectionMode, ArgumentMode } from '@vuex-orm/plugin-graphql';

export default class CustomAdapter extends DefaultAdapter {
  getConnectionMode () {
    return ConnectionMode.PLAIN;
  }

  getArgumentMode () {
    return ArgumentMode.LIST;
  }
};
 

/data/database.js

 import { Database } from '@vuex-orm/core';

// import models
import Notification from '~/data/models/notification';
import User from '~/data/models/user';

const database = new Database();
database.register(User);
database.register(Notification);

export default database;
 

/data/models/user.js

 import { Model } from '@vuex-orm/core';
import Notification from './notification';

export default class User extends Model {
  static entity = 'users';

  static eagerLoad = ['notifications'];

  static fields () {
    return {
      id: this.attr(null),
      email: this.string(''),
      first_name: this.string(''),
      last_name: this.string(''),

      // relationships
      notifications: this.hasMany(Notification, 'user_id')
    };
  }
};
 

/data/models/notification.js

 import { Model } from '@vuex-orm/core';
import User from './user';

export default class Notification extends Model {
  static entity = 'notifications';

  static fields () {
    return {
      id: this.attr(null),
      message: this.string(''),
      viewed: this.boolean(false),

      // relationships
      user: this.belongsTo(User, 'user_id')
    };
  }
};
 

package.json

 "@vuex-orm/plugin-graphql": "^1.0.0-rc.41"
 

Ответ №1:

Итак, чтобы заставить это работать, я в итоге внес пару изменений, которые действительно сработали!

Если другие люди сталкиваются с подобными проблемами, вот что я сделал… В моем nuxt.config.js , поменял порядок двух плагинов на этот:

 plugins: [
    '~/plugins/graphql',
    '~/plugins/vuex-orm',
],
 

В моем graphql.js плагин, я изменил порядок параметров на этот (сначала база данных, затем адаптер):

 const options = {
  database,
  adapter: new CustomAdapter(),
  url: env.NUXT_ENV_BACKEND_API_URL,
  debug: process.env.NODE_ENV !== 'production'
};