This project is a Work in Progress and currently in development. The API is subject to change without warning.
Programatically create your GraphQL Query.
Pass an Object following our format, get your GraphQL Query. Simple as that.
npm install gql-query-creator
gqlQueryCreator(queryName, queryVariables, queryTree);
This package allows you to programmatically construct an object that is formatted into a query string and variables. We call this the Query Tree. It follows the format shown below*:
const queryTree = {
singleProperty: '', /* OUTPUT - singleProperty */
propertyWithOptionsAndVariables: [{
optionA: 'variableA',
}], /* OUTPUT - propertyWithOptionsAndVariables(optionsA: $variableA) */
propertyWithOptionsAndValues: [{
propOverride: true,
optionA: 150,
}], /* OUTPUT - propertyWithOptionsAndValues(optionsA: 150) */
propertyWithAlias: [{}, 'alias'], /* OUTPUT - alias: propertyWithAlias */
propertyWithProperties: {
args: [{
optionA: 'variableA',
}], // Note: this functions the same as the arrays above
items: {
singleProperty: '',
singlePropertyTwo: '',
},
}, /* OUTPUT -
propertyWithProperties(optionA: $variableA) {
singleProperty
singlePropertyTwo
}
*/
};
* If this seems confusing to you, check out the example it might make more sense.
// using CommonJS
const { gqlQueryCreator } = require('gql-query-creator');
// using ESM
import { gqlQueryCreator } from 'gql-query-creator';
function myQueryString() {
/* --- RandomProject's Useful Items --- */
const postProperties = {
title: '',
date: '',
body: '',
};
const userProperties = {
username: '',
firstName: '',
url: [{ propOverride: true, dotty: true }, 'dottyUrl'],
posts: {
args: [{
propOverride: true,
latest: true,
count: 10,
}],
items: {
...postProperties,
},
},
};
/* --- Query Creation --- */
const queryName = 'UserInfo';
const queryTree = {
userByUsername: {
args: [{ username: 'username' }],
items: {
...userProperties,
},
},
};
const username = 'RayhanADev';
const queryVariables = {
username: ['String!', username],
};
// Modify the tree if a criteria is met
if(username === 'RayhanADev') {
queryTree.userByUsername.items.roles = '';
};
// Pass Everything Through the Creator
const myQuery = gqlQueryCreator(queryName, queryVariables, queryTree);
return myQuery;
}
const myQuery = myQueryString();
console.log(myQuery.query);
console.log('-----');
console.log(myQuery.variables);
Output:
query UserInfo($username: String!) {
userByUsername(username: $username) {
username
firstName
dottyUrl: url(dotty: true)
posts(latest: true, count: 10) {
title
date
body
}
roles
}
}
-----
{"username":"RayhanADev"}