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.
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.
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.
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With