Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

javascript - GraphQL field with space

I'm trying to use a new GraphQL server on a very old legacy code, where the column names have spaces, e.g: "Poke ball"

I've been trying to run this query:

query{{userItems{Poke ball}}}

and got this:

extensions: {code: "GRAPHQL_VALIDATION_FAILED",…}
locations: [{line: 1, column: 12}]
message: "Cannot query field "Poke" on type "UserItems"."

I've tried to use quotes with no luck, any idea if this is supported / workaround?

Thanks.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The GraphQL specification requires that names of things (fields, types, arguments, etc.) only contain letters, numbers and underscores. A field name cannot contain a space because spaces and other whitespace are used to separate individual tokens. In other words, one or more spaces or line returns are used to indicate that, for example, one field's name has terminated and another has begun.

If your underlying data layer is returning data with keys that contain spaces, you need to define a field with an allowed name (like pokeball) and then write a resolver for that field. For example:

const UserItems = new GraphQLObjectType({
  name: "UserItems",
  fields: () => ({
    pokeball: {
      type: Pokeball,
      resolve: (parent) => {
        // The parent value will be whatever the parent field resolved to.
        // We look for a property named "Poke ball" on that value and return it.
        return parent["Poke ball"];
      },
    },
    ...
  }),
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...