如何在GraphQL的REST API中获取具有空格,连字符的字段值

时间:2019-12-23 06:49:01

标签: graphql apollo apollo-server

REST API端点-https://api.jikan.moe/v3/manga/13

“替代版本”,“旁白”和“分拆”字段具有空格和连字符。

enter image description here

common_schema.js

const { gql } = require('apollo-server');

const typeDefs = gql`

    type RelatedType {
        Adaptation: [RelatedSubType]
        SideStory: [RelatedSubType]
        Character: [RelatedSubType]
        Summary: [RelatedSubType]
        Other: [RelatedSubType]
        AlternativeVersion: [RelatedSubType]
        SpinOff: [RelatedSubType]
    }

    type RelatedSubType {
        mal_id: ID
        type: String
        name: String
        url: String
    }
`;

module.exports = typeDefs;

如果我将字段值写为Spin-offAlternative version,则会在终端中显示错误。 "Spin-off"也不起作用。我知道这些无效,但随后也尝试过。

manga_resolver.js

module.exports = {
    Query: {
        manga: (_, { id }, { dataSources }) =>
            dataSources.mangaAPI.getMangaDetail(id)
    }
};

manga.js

const { RESTDataSource } = require('apollo-datasource-rest');

class MangaAPI extends RESTDataSource {
    constructor() {
        super();
        this.baseURL = 'https://api.jikan.moe/v3/manga/';
    }

    async getMangaDetail(mal_id) {
        const response = await this.get(`/${mal_id}`);
        return response;
    }
}

module.exports = MangaAPI;

查询-

query getMangaDetail{
manga(id: 13){
    related{
      Adaptation{
        name
      }
      AlternativeVersion{
        name
      }
      SpinOff{
        name
      }
    }
  }
}

在具有空格和连字符的字段中获取null

查询结果-

{
"data": {
    "manga": {
      "related": {
        "Adaptation": [
          {
            "name": "One Piece"
          }
        ],
        "AlternativeVersion": null,
        "SpinOff": null
      }
    }
  }
}

Repository - jikan-graphql

1 个答案:

答案 0 :(得分:1)

根据the spec,GraphQL中的名称必须遵循以下格式:

/[_A-Za-z][_0-9A-Za-z]*/

换句话说,不允许使用空格或破折号。如果您的数据源返回的属性名称格式错误,则可以为有问题的字段提供解析器:

const resolvers = {
  RelatedType: {
    sideStory: (parent) => {
      return parent['Side story']
    },
    ...
  }
}