Last active
February 21, 2020 11:59
-
-
Save bitnbytesio/3621d5fedd6407bc5f8db82e883fda59 to your computer and use it in GitHub Desktop.
Convert Object to GraphQL QueryString
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// usage example | |
import { graphql, GraphqlQuery } from './obj-to-graphql'; | |
const bookingsQuery: GraphqlQuery = { | |
name: 'bookings', | |
args: { | |
page: 1, | |
filter: { from: '2020-02-02' }, | |
}, | |
select: { | |
totalRecords: true, | |
data: { | |
_id: true, | |
event: { | |
title: true, | |
address: true, | |
} | |
} | |
} | |
}; | |
console.log(graphql(bookingsQuery)); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export interface GraphqlQuery { | |
name: string; | |
args?: object; | |
select: object; | |
} | |
export const graphqlQueryStrLN = '\n'; | |
export function processArgs(obj?: object) { | |
let str = ''; | |
if (!obj) { | |
return str; | |
} | |
Object.keys(obj).forEach((k: any) => { | |
let holds = obj[k]; | |
if (typeof holds === 'object') { | |
holds = `{ ${processArgs(holds)} }`; | |
} else if (typeof holds === 'string') { | |
holds = `"${holds}"`; | |
} | |
const comma = str === '' ? '' : ','; | |
str += `${comma}${k}:${holds}` | |
}); | |
return str; | |
} | |
export function processSelect(obj?: object, space = ' ') { | |
let str = ' {'; | |
if (!obj) { return str; } | |
Object.keys(obj).forEach((k: any) => { | |
const holds = obj[k]; | |
if (holds === false) { | |
return; | |
} | |
const v = (typeof holds === 'object') ? processSelect(holds, space + ' ') : ''; | |
str += `${graphqlQueryStrLN}${space} ${k}${v}`; | |
}); | |
str += `${graphqlQueryStrLN}${space}}`; | |
return str; | |
} | |
export function processQuery(q: GraphqlQuery, space = ' ') { | |
let str = graphqlQueryStrLN; | |
str += `${space}${q.name}(${processArgs(q.args)})`; | |
str += processSelect(q.select, space); | |
return str; | |
} | |
export function graphql(...args: Array<GraphqlQuery>) { | |
let query = '{'; | |
args.forEach((q) => { | |
query += `${processQuery(q)}${graphqlQueryStrLN}`; | |
}); | |
query += `}`; | |
return query; | |
} | |
export default graphql; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It Converts this object
to this