首页 > 解决方案 > 具有动态键的对象的 GraphQL 模式类型

问题描述

我使用外部 API 作为数据源,因此我无法控制返回记录中的键。我有一个这样的对象的记录:

images: {
  '50': 'https://mir-s3-cdncf.behance.net.jpg',
  '100': 'https://mir-s3-cdn-cf.behance.net/user/100/579c455d13419.jpg',
  '115': 'https://mir-s3-cdn-cf.behance.net/user/115/.jpg',
  '138': 'https://mir-s3-cdn-cf.behance.net/user/138/.jpg'
}

我无法预先知道这个对象中的键是什么。有没有办法在 GraphQL 模式中处理这个问题?

标签: graphql

解决方案


我得到这个使用包“graphql-type-json”。这是使用该包的代码:


// Define new JSON types.
const AppTypes = `
  scalar JSON
  scalar JSONObject
`;

// Define resolvers for the new types which point to the types from the library.
const { GraphQLJSON, GraphQLJSONObject } = require('graphql-type-json');

const AppResolvers = {
  JSON: GraphQLJSON,
  JSONObject: GraphQLJSONObject
};

// Use the types.
entityTree: [JSONObject]!

推荐阅读