question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Convert arbitrary scalar values into ASTs and back

See original GitHub issue

Reporting issues with GraphQL.js

This issue is related to: https://github.com/graphql/graphql-js/issues/1815

Expected:

  • Successfully convert arbitrary scalars (including default values) to ASTs
  • Convert ASTs into dedicated values

Code:

const {
  makeExecutableSchema,
} = require('graphql-tools')

const {
  astFromValue,
  valueFromAST,
  isValidJSValue
} = require('graphql/utilities')

const {
  GraphQLScalarType
} = require('graphql')


const JsonScalarType = new GraphQLScalarType({
  name: 'JSON',
  serialize: (value) => value,
});

const resolveFunctions = {
  JSON: JsonScalarType
};

const typeDefs = `
  scalar JSON
  input Message {
    extra: JSON
    meta: JSON = {}
  }
`

const schema = makeExecutableSchema({
  typeDefs,
  resolvers: resolveFunctions
})

const messageType = schema.getType('Message')

const value = {
  extra: {
    'key': 'andy',
    "kafka.producer.batch": 0
  }
}

// check if there's any error in our value
const errors = isValidJSValue(value, messageType)
// errors will contain detail errors if any
console.log(`Valid: ${errors.length==0}`)

// parse and get value 
const ast = astFromValue(value, messageType)
const conf = valueFromAST(ast, messageType)

Result

$ npm start                                                                                                              master ✱ ◼

> gql@1.0.0 start /Users/andy/Works/gql
> babel-node --presets es2015 run.js

Valid: true
/Users/andy/Works/gql/node_modules/graphql/utilities/astFromValue.js:130
          throw _iteratorError;
          ^

TypeError: Cannot convert value to AST: { key: "andy", kafka.producer.batch: 0 }
    at astFromValue (/Users/andy/Works/gql/node_modules/graphql/utilities/astFromValue.js:193:11)
    at astFromValue (/Users/andy/Works/gql/node_modules/graphql/utilities/astFromValue.js:107:26)

Solution

I have to patch astFromValue: https://github.com/graphql/graphql-js/blob/8aef229cb2/src/utilities/astFromValue.js#L139-L140 by adding following lines before L139


if (typeof serialized === 'object' ){
    return {
      kind: _kinds.Kind.OBJECT,
      value: serialized
    };
}

Question

The solution above may not be adequate. Would you please tell me it’s worth to make a RP against this issue and how to properly resolve it?

Issue Analytics

  • State:open
  • Created 4 years ago
  • Comments:6 (3 by maintainers)

github_iconTop GitHub Comments

2reactions
IvanGoncharovcommented, Apr 15, 2019

@anhldbk It’s designed proposal for a fix. Idea is to have optional serializeAsLiteral that if omitted equals to astFromValueUntypped(this.serialize(value)).

1reaction
vitramircommented, Dec 13, 2019

I think this is a better fix:

    if (typeof serialized === 'object') {
      if (Array.isArray(serialized)) {
        return {
          kind: Kind.LIST,
          values: serialized.map(v => astFromValue(v, type)),
        };
      }

      return {
        kind: Kind.OBJECT,
        fields: Object.entries(serialized).map(([k, v]) => {
          return {
            kind: 'ObjectField',
            name: { kind: 'Name', value: k },
            value: astFromValue(v, type),
          };
        }),
      };
    }

I think we can keep Enum and GraphQLID logic in this function and move all the stuff regarding scalars (boolean, string, number and this fix also) to astFromValueUntyped function.

@IvanGoncharov Do you want me to make PR for these changes?

Read more comments on GitHub >

github_iconTop Results From Across the Web

GraphQL Blackbox / "Any" type? - Stack Overflow
I have a field in my schema that should be able to accept any arbitrary value, which could be a String, Boolean, Object,...
Read more >
pandas dataframe valueerror: if using all scalar values, you must ...
When this is returned, pd.read_json throws an error, because it can't convert this to a dataframe. The simplest workaround is to use a...
Read more >
All-optical synthesis of an arbitrary linear transformation using ...
Here, we report the design of diffractive surfaces to all-optically perform arbitrary complex-valued linear transformations between an input ...
Read more >
18 Expressions - Advanced R - Hadley Wickham
Section 18.6 circles back to three more specialised data structures: pairlists, ... Scalar constants are the simplest component of the AST.
Read more >
Conversion and Promotion · The Julia Language
One example is assigning a value into an array: if A is a Vector{Float64} , the expression A[1] = 2 should work by...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found