Skip to content

Instantly share code, notes, and snippets.

@niwinz
Last active November 26, 2019 03:37
Show Gist options
  • Save niwinz/dfdc9ba04002f3e3678a9e1f44e31caf to your computer and use it in GitHub Desktop.
Save niwinz/dfdc9ba04002f3e3678a9e1f44e31caf to your computer and use it in GitHub Desktop.
GraphQL Dynamic Object.
const {GraphQLError} = require("graphql/error");
const {Kind} = require("graphql/language");
const g = require("graphql");
function parseLiteral(ast) {
switch (ast.kind) {
case Kind.STRING:
case Kind.BOOLEAN:
return ast.value;
case Kind.INT:
case Kind.FLOAT:
return parseFloat(ast.value);
case Kind.OBJECT: {
const value = Object.create(null);
ast.fields.forEach((field) => {
value[field.name.value] = parseLiteral(field.value);
});
return value;
}
case Kind.LIST:
return ast.values.map(parseLiteral);
default:
return null;
}
}
module.exports = new g.GraphQLScalarType({
name: "DynamicObject",
description: "A dynamic object.",
serialize(v) {
return v;
},
parseValue(v) {
return v;
},
parseLiteral(ast) {
return parseLiteral(ast);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment