Graphql-yoga: custom scalar

Created on 27 Mar 2018  路  2Comments  路  Source: dotansimha/graphql-yoga

Hi All

This is more of a question than an issue. How do I create a custom scalar with graphql-yoga? I have attempted to use GraphQLScalarType from 'graphql' along the following lines:

import { GraphQLScalarType } from 'graphql'
//...
const MyScalar = new GraphQLScalarType({
 //...
})
//...

const resolvers = {
  Query: {
    //...
  },
  MyScalar: MyScalar
}

But the scalar value returns as null in all queries.

kinquestion

Most helpful comment

I made it work with something along the lines of this:

const NLString = new GraphQLScalarType({
  name: 'NLString',
  description:
    'New line terminated string',
  //invoked to parse client input that was passed through variables.
  //takes a plain JS object.
  parseValue(varaible){
    return varaible.replace(/\n$/, "")
  },
  //invoked to parse client input that was passed inline in the query.
  //takes a value AST.
  parseLiteral(literal) {
    return literal.value.replace(/\n$/, "")
  },
  //invoked when serializing the result to send it back to a client.
  serialize: function(value){
    return value + "\n"
  }
})

//...

const resolvers = {
  Query: {
    //...
  },
  NLString
}

All 2 comments

I made it work with something along the lines of this:

const NLString = new GraphQLScalarType({
  name: 'NLString',
  description:
    'New line terminated string',
  //invoked to parse client input that was passed through variables.
  //takes a plain JS object.
  parseValue(varaible){
    return varaible.replace(/\n$/, "")
  },
  //invoked to parse client input that was passed inline in the query.
  //takes a value AST.
  parseLiteral(literal) {
    return literal.value.replace(/\n$/, "")
  },
  //invoked when serializing the result to send it back to a client.
  serialize: function(value){
    return value + "\n"
  }
})

//...

const resolvers = {
  Query: {
    //...
  },
  NLString
}

Also, for completeness, here's are some example graphql queries:
Literals
Query:

query {
  post(title:"example\n"){
    title
    body
  }
}

triggers:
parseLiteral(literal) with literal.value="example\n"

Variables
Query:

query Posts($title: NLString) {
  post(title:$title){
    title
    body
  }
}

with variable:

{
  "title": "example\n"
}

triggers: parseValue(varaible) with varaible="example\n"

Was this page helpful?
0 / 5 - 0 ratings

Related issues

yesprasad picture yesprasad  路  3Comments

playerx picture playerx  路  5Comments

kv-pawar picture kv-pawar  路  3Comments

2wce picture 2wce  路  4Comments

checkmatez picture checkmatez  路  5Comments