Как реализовать интерфейс с использованием GraphQL и узла - PullRequest
0 голосов
/ 15 марта 2019

Я хочу получить поля одного типа объекта в другом типе объекта

Вот мой файл схемы.

const Films = new GraphQLInterfaceType({
  name: 'films',
  fields: () => ({
    id:{
        type: GraphQLID
      },
      name: {
        type: GraphQLString,
      },
    })
})

const MovieStream = new GraphQLObjectType({
    name: 'MovieStream',
    interfaces: () => [Films], 
    fields: () => ({
        id: {
            type: GraphQLID,    
          },    
          movie_id: {
              type: GraphQLString,   
            },    
    })
})

Здесь я пытаюсь использовать интерфейс.Но он показывает ошибку:

{
  "errors": [
    {
      "message": "Query root type must be Object type, it cannot be { __validationErrors: undefined, __allowedLegacyNames: [], _queryType: undefined, _mutationType: undefined, _subscriptionType: undefined, _directives: [@include, @skip, @deprecated], astNode: undefined, extensionASTNodes: undefined, _typeMap: { __Schema: __Schema, __Type: __Type, __TypeKind: __TypeKind, String: String, Boolean: Boolean, __Field: __Field, __InputValue: __InputValue, __EnumValue: __EnumValue, __Directive: __Directive, __DirectiveLocation: __DirectiveLocation, films: films, ID: ID, Date: Date, JSON: JSON, MovieStream: MovieStream }, _possibleTypeMap: {}, _implementations: { films: [] } }."
    },
    {
      "message": "Expected GraphQL named type but got: { __validationErrors: undefined, __allowedLegacyNames: [], _queryType: undefined, _mutationType: undefined, _subscriptionType: undefined, _directives: [@include, @skip, @deprecated], astNode: undefined, extensionASTNodes: undefined, _typeMap: { __Schema: __Schema, __Type: __Type, __TypeKind: __TypeKind, String: String, Boolean: Boolean, __Field: __Field, __InputValue: __InputValue, __EnumValue: __EnumValue, __Directive: __Directive, __DirectiveLocation: __DirectiveLocation, films: films, ID: ID, Date: Date, JSON: JSON, MovieStream: MovieStream }, _possibleTypeMap: {}, _implementations: { films: [] } }."
    }
  ]
}

Вот тип запроса:

const QueryRoot = new GraphQLObjectType({

  name: 'Query',
  fields: () => ({
        getContentList:{
        type: new GraphQLList(contentCategory),
        args: {
          id: {
            type: GraphQLInt
          },
          permalink: {
              type: GraphQLString
          },
          language: {
              type: GraphQLString
          },
          content_types_id: {
              type: GraphQLString
          },
          oauth_token:{
              type: GraphQLString
          }

        },

        resolve: (parent, args, context, resolveInfo) => {
           var category_flag = 0;
           var menuItemInfo = '';
           user_id = args.user_id ? args.user_id : 0;
          // console.log("context"+context['oauth_token']);
           return AuthDb.models.oauth_registration.findAll({attributes: ['oauth_token', 'studio_id'],where:{
              //  oauth_token:context['oauth_token'],
               $or: [
                  {
                      oauth_token: 
                      {
                          $eq: context['oauth_token']
                      }
                  },

                  {
                      oauth_token: 
                      {
                          $eq: args.oauth_token
                      }
                  },
              ]

              },limit:1}).then(oauth_registration => { 
              var oauthRegistration = oauth_registration[0]
              // for(var i = 0;i<=oauth_registration.ength;i++){
                      if(oauth_registration && oauthRegistration && oauthRegistration.oauth_token == context['oauth_token'] || oauthRegistration.oauth_token == args.oauth_token){
                         studio_id = oauthRegistration.studio_id;
                         return joinMonster.default(resolveInfo,{}, sql => {
                            return contentCategoryDb.query(sql).then(function(result) { 

                                return result[0];
                            });   
                        } ,{dialect: 'mysql'});

                      }else{
                          throw new Error('Invalid OAuth Token');
                      }

                  })

        },

        where: (filmTable, args, context) => {
            return getLanguage_id(args.language).then(language_id=>{
                return ` ${filmTable}.permalink = "${args.permalink}" and ${filmTable}.studio_id = "${studio_id}" and (${filmTable}.language_id = "${language_id}"  OR  ${filmTable}.parent_id = 0 AND ${filmTable}.id NOT IN (SELECT ${filmTable}.parent_id FROM content_category WHERE ${filmTable}.permalink = "${args.permalink}" and ${filmTable}.language_id = "${language_id}" and ${filmTable}.studio_id = "${studio_id}"))`
            })

              },

    }

  })
})

module.exports = new GraphQLSchema({
    query: QueryRoot
})

Пожалуйста, помогите мне.я сделал что-то не так в использовании интерфейса?

Я нашел ответ в этом посте Можно ли получить данные из нескольких таблиц, используя GraphQLList

Кто-нибудь, пожалуйста,скажите мне точный способ использования интерфейса в моем коде.

1 Ответ

0 голосов
/ 15 марта 2019

Хотя ошибка, которую вы напечатали, на самом деле не относится к реализациям interfaces, чтобы использовать интерфейсы, вы должны реализовать методы / типы ссылок на интерфейсы. Таким образом, в вашей ситуации в вашем объекте MovieStream отсутствует тип name, на который вы ссылаетесь в объекте Films.

Ваш код должен выглядеть примерно так:

const Films = new GraphQLInterfaceType({
    name: 'films',
    fields: () => ({
        id:{
            type: GraphQLID
        },
        name: {
            type: GraphQLString,

        },
    })
})

const MovieStream = new GraphQLObjectType({
    name: 'MovieStream',
    interfaces: () => [Films],
    fields: () => ({
        id: {
            type: GraphQLID,
        },
        name: {
            type: GraphQLString // You're missing this!
        },
        movie_id: {
            type: GraphQLString,
        },
    })
})

Теперь вернемся к напечатанной ошибке "message": "Query root type must be Object type, it cannot be...

Похоже, это связано с вашим QueryRoot объектом, кажется, что GraphQLSchema не распознает корневой объект. Если проблема не устранена после того, как вы исправите интерфейс, взгляните на этот ответ здесь

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...