Last active
November 26, 2019 03:37
-
-
Save niwinz/dfdc9ba04002f3e3678a9e1f44e31caf to your computer and use it in GitHub Desktop.
GraphQL Dynamic Object.
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
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