Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to represent an object of key-value pairs in GraphQL

I am using GraphQL in my Node.js application. And I want to store an object that uses keys as a locale short code and values for the string in the corresponding language. (like { en: "Hello", ru: "Привет" } etc.)

I want to represent this using GraphQL, both in input (like that):

mutation {
  addExercise(name: { en: "Hello", ru: "Привет" })
}

and in output (like that)

{
  exercises {
    _id, name
  }
}

(name should return an object of key-value pairs:)

[
  {_id: 1, name: { en: "Hello", ru: "Привет" }}
]

How can I do something like that?

I know I can store my data this way

{ name: "en", value: "Hello }`

but the previous one seems to be easier.

like image 889
serge1peshcoff Avatar asked Sep 26 '16 08:09

serge1peshcoff


People also ask

How do you store key-value pairs in objects?

How to Add a Key-Value Pair Using Bracket Notation in JavaScript. Just like dot notation, you can use bracket notation to add a key-value pair to an object. Bracket notation offers more flexibility than dot notation. That's because key names can include spaces and hyphens, and they can start with numbers.

What is object type in GraphQL?

Object types are used in GraphQL to define the custom data structures of your application as well as the relationships between objects. This is the equivalent of modeling your database schema and models in traditional applications.

What is key-value pair format?

A key-value pair consists of two related data elements: A key, which is a constant that defines the data set (e.g., gender, color, price), and a value, which is a variable that belongs to the set (e.g., male/female, green, 100). Fully formed, a key-value pair could look like these: gender = male. color = green.

What other types can be used in a GraphQL schema?

A GraphQL schema can contain more than just the scalar types. The two most used types are query and mutation types. Every GraphQL service will have a query type. This is the entry point to a GraphQL schema.


1 Answers

you can define scalar type for JSON, and then return the data as is. here is an example library that does just that (use it or copy & modify): https://github.com/taion/graphql-type-json/blob/master/src/index.js

enjoy!

like image 50
HagaiCo Avatar answered Sep 22 '22 08:09

HagaiCo