vkolgi / json-to-graphql-query Goto Github PK
View Code? Open in Web Editor NEWSimple module that converts JavaScript objects to GraphQL query syntax
License: MIT License
Simple module that converts JavaScript objects to GraphQL query syntax
License: MIT License
TL;DR I would like the option to be able to pass in an object for a query and have all properties on the query whether the value of a property is truthy or not.
I am using yup on a project where I am already defining my schema and I am using the default of the schema for the form state in react and then ultimately for the mutation query.
I don't like having to define the schema in so many different places and in this case the query is the same shape as the mutation. It would be nice to be able to use the default object from yup like I am to define the default form state in react to define the query.
I am willing to do the work and submit a PR for this if it something you can see value in.
Thanks!
Hi,
I used this project to generated graphql query based on the json I passed.
I initialise a variable args
to {}
and then and properties depending on conditions.
However if none are match then the properties __args = {}
and it's translated to ()
which leads to a fail.
Can you add a control on args to ensure that it's an objects with properties and in case of empty object it handles as there is no args.
Thx.
Mutations that use Enum values for inputs do not work as it creates the query string with double quotes around the Enum types
GraphQL schema
type ProviderHours {
day: DayOfWeek!
isOpen: Boolean!
}
enum DayOfWeek {
MONDAY
TUESDAY
...
}
Node
let mutation = {
mutation: {
updateProviderHours: {
__args: {
id: 1,
input: [{
day: 'MONDAY',
isOpen: false
}]
},
hours: {
day: true,
isOpen: true
}
}
}
}
mutation = jsonToGraphQLQuery(mutation)
the above gives me
mutation { updateProviderHours (providerId: 1, input: [{day: "MONDAY", isOpen: false}]) { hours { day isOpen } } }
using "MONDAY" in the string.
Is there anyway to not quote these values when they're enumerators?
Nested objects with falsy values are not omitted in the result query.
// input
const input = {
query: {
a: {
b: {
c: {
d: {
e: false,
},
},
f: {
g: true,
},
},
},
},
}
// output
query {
a {
b {
c {
}
f {
g
}
}
}
}
Hey @dupski,
thank you for this lib. It's exactly what i was looking for. But now i'm stuck by passing EnumTypes in Objects as Parameter.
const query = {
mutation: {
create: {
__aliasFor: 'createPost',
__args: {
initial: {title: "XYZ" , status: new EnumType("OPEN")},
},
id: true,
},
},
};
results in:
mutation { create: createPost (initial: {title: "XYZ", status: {value: "OPEN"}}) { id }}
expected:
mutation { create: createPost (initial: {title: "XYZ", status: OPEN}) { id }}
Can you help here? Thanks :)
I need to update a field whose type is Date in Graphql,
I noticed in the documentation/example you have an orderBy field, but how do you go about setting the direction?
I see that ConfigurablePost turns into a fragment, but where and how it should be declared? as a object? as a graphql string? where it should be? inside query property? The docs is not clear.
import { jsonToGraphQLQuery } from 'json-to-graphql-query';
const query = {
query: {
Posts: {
title: true,
__all_on: [
"ConfigurablePost",
"PageInfo"
]
}
}
};
const graphql_query = jsonToGraphQLQuery(query, { pretty: true });
Hello!
I'm using your lib to generate qraphql queries from the object and I've run into the #19 issue. I've found that it was solved via #27 but it was still reproducing.
While investigating I've run into the needed line of code in src/jsonToGraphQLQuery.ts
and it version in node_modules differs from master branch although the version in package.json of the lib is 2.1.0
Can you please check if the right version of the package was published? Thanks.
Note: I use yarn 1.22.17 to manage dependencies
File1:
import { EnumType } from 'json-to-graphql-query';
let email = "[email protected]";
let location = { city: "Paris", country: "France", number: "4", postCode: "75008", street: "avenue des Champs Elysee" };
let identity = { type: new EnumType("PERSON"), optPerson: { firstname: "Pierre", lastname: "Fabre" } };
let payout_settings = { type: new EnumType("ETHEREUM_ADDRESS"), optEthAddress: "0x123" };
file2:
import { jsonToGraphQLQuery } from 'json-to-graphql-query';
let mutation = jsonToGraphQLQuery({
mutation: {
updateProfileInfo: { __args: { email: email, location: location, identity: identity, paytoutSettings: payoutSettings } }
}
});
console.log(mutation)
Output:
mutation { updateProfileInfo (email: "[email protected]", location: {city: "Paris", country: "France", number: "4", postCode: "75008", street: "avenue des Champs Elysee"}, identity: {type: {value: "PERSON"}, optPerson: {firstname: "Pierre", lastname: "Fabre"}}, paytoutSettings: {type: {value: "ETHEREUM_ADDRESS"}, optEthAddress: "0x123"}) }
You see:
type: {value: "PERSON"}
and type: {value: "ETHEREUM_ADDRESS"}
what is expected is type: PERSON
and type: ETHEREUM_ADDRESS
. This is straight up what the feature is supposed to do.
I'm using "json-to-graphql-query": "2.2.4"
We're evaluating using your package and graphql at my work, and it looks like either the package is incorrect or the documentation is incorrect, but I'm not sure which.
If I look at the alias documentation:
import { jsonToGraphQLQuery } from 'json-to-graphql-query';
const query = {
query: {
Posts: {
__alias: 'allPosts',
id: true,
comments: {
id: true,
comment: true
}
}
}
};
const graphql_query = jsonToGraphQLQuery(query, { pretty: true });
In that case, I'm assuming that the Schema object is called Posts
, and we're aliasing it to the key of allPosts
. The intent of the alias
mechanic in graphQL is to allow the same endpoint to be queried more than once in the same query.
In example, using the graphIQL sandbox I can run:
{
film1: film(id: "ZmlsbXM6MQ==") {
id
title
}
film2: film(id: "ZmlsbXM6Mg==") {
id
title
}
}
In that case I'm able to query film
twice. The issue is with the syntax in your package, JSON does not support the same key twice in an object. IE the following is invalid JSON.
{
Posts: {
__alias: "Test"
...
}
Posts: {
__alias : "test2"
}
}
I believe to be compatible with graphQL the keys actually needs to be flipped.
{
test: {
__alias: "Posts"
...
}
test2: {
__alias : "Posts"
}
}
See what I'm getting at?
This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.
Warning
These dependencies are deprecated:
Datasource | Name | Replacement PR? |
---|---|---|
npm | tslint |
These updates have all been created already. Click a checkbox below to force a retry/rebase of any.
@types/chai
, @types/mocha
, @types/node
, ansi-regex
, chai
, sinon
, ts-node
, typescript
)@types/mocha
, @types/node
, chai
, mocha
, sinon
, typescript
).github/workflows/npm-publish.yml
actions/checkout v4
actions/setup-node v4
.github/workflows/on-pull-request.yml
actions/checkout v4
package.json
@types/chai 4.3.0
@types/mocha 9.1.0
@types/node 16.11.22
chai 4.3.6
mocha 9.2.2
sinon 13.0.1
ts-node 10.4.0
tslint 6.1.3
typescript 4.5.5
ansi-regex 6.0.1
It would be awesome if we could have a web app to generate JSON objects from GraphQL queries as it is pretty tedious to create the json object manually.
As the title states, we have no example on how to create a mutation, which could be super beneficial for everyone. ๐
Enums are defined though the EnumType
class, in line with the conclusion on issue #2. Here's the example from the README:
const query = {
query: {
Posts: {
__args: {
orderBy: 'post_date',
status: new EnumType('PUBLISHED')
},
title: true,
body: true
}
}
};
However, this is problematic when I need to actually store this in a JSON file, where the EnumType
won't be available. Here's a suggestion for an alternative way to define an enum:
{
"query": {
"Posts": {
"__args": {
"orderBy": "post_date",
"status": { "__enum": "PUBLISHED" }
},
"title": true,
"body": true
}
}
}
Would you be interested in a PR that implements this as an alternative to the EnumType
, @vkolgi?
Could buildArgs be exported? I just want to use it in that one case. Thanks!
I've got a query with a nested argument but the object keys are getting parsed as strings.
{
query: {
allAccounts: {
__args: {
or: [
{accountid: {equalTo: "somestring1"}},
{accountid: {equalTo: "somestring2"}},
{accountid: {equalTo: "somestring3"}}
]
},
nodes: {
accountid: true,
balance: true
}
}
}
}
query {
allAccounts (or: [{"accountid":{"equalTo":"somestring1"}},{"accountid":{"equalTo":"somestring2"}},{"accountid":{"equalTo":"somestring3"}}]) {
nodes {
accountid
balance
}
}
}
For this to be a valid query accountid
and equalTo
would need to not be returned as strings
Support for aliased fields would be great. The natural format would of course be to set the alias as the property value instead of true
.
const query = {
query: {
fruits: {
name: true,
colour: 'color',
flavour: 'flavor'
}
}
}
should result in:
{
query: {
fruits {
name
colour: 'color'
flavour: 'flavor'
}
}
}
I do realize however that that would introduce breaking changes for people using truthy values.
Are there any plans to include support for Swagger/OpenAPI 3.0?
When an array is passed in the current functionality is to add the index of the array as a field on the query. I know that arrays aren't supported currently but with the includeFalsyKeys PR (see #15) this becomes more of an issue.
My first thought (and the easiest to implement) would be to just grab the keys off the first object in the array. Alternatively we could get all of the keys from all of the objects in the array.
Again, I am happy to submit a PR if you are interested in this functionality.
Thanks!
WARNING in ./node_modules/json-to-graphql-query/lib/types/EnumType.js
Module Warning (from ./node_modules/source-map-loader/index.js):
(Emitted value instead of an instance of Error) Cannot find source file '../../src/types/EnumType.ts': Error: Can't resolve '../../src/types/EnumType.ts' in '/Projects/activeql.d/activeql/angular/node_modules/json-to-graphql-query/lib/types'
Everything seems to work, I still like to figure out what's causes the warning, though. Any idea?
There is a need to support Directives, currently just the @client
directive for apollo, however I would like us to implement this in a generic way to allow for possible use of @skip(if: ...)
, etc. if needed.
Relavant GraphQL Spec:
http://facebook.github.io/graphql/October2016/#sec-Directives-Are-In-Valid-Locations
Medium article:
https://medium.com/front-end-developers/graphql-directives-3dec6106c384
Initial Requirements:
Future Requirements
If you add this project to Angular, you get
Warning: C:\web projects\drill-to\node_modules\easy-dgraph\build\module\lib\easy-dgraph.js depends
on 'json-to-graphql-query'. CommonJS or AMD dependencies can cause optimization bailouts.
For more info see: https://angular.io/guide/build#configuring-commonjs-dependencies
Could we update this package to an ECMAScript modules?
Thanks,
J
the __name doesn't work, report error [GraphQL error]: Message: Cannot query field "__name" on type "Query"
{ query: { __name: 'NewName', __variables, [queryName]: { __args: toArgs(__variables), ...schemas, }, }, } }
Same as #19 but for __variables
where if we initialize it with {}
it will generate the query with ()
I'm thinking there should be a Graphql to Json function in this library.
Use case would be to alter existing graphql queries dynamically.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.