Coder Social home page Coder Social logo

graphql-type-json's Introduction

graphql-type-json Travis npm

JSON scalar types for GraphQL.js.

Codecov

Usage

This package exports a JSON value scalar GraphQL.js type:

import GraphQLJSON from 'graphql-type-json';

It also exports a JSON object scalar type:

import { GraphQLJSONObject } from 'graphql-type-json';

These types can also be imported as follows using CommonJS:

const { GraphQLJSON, GraphQLJSONObject } = require('graphql-type-json');

GraphQLJSON can represent any JSON-serializable value, including scalars, arrays, and objects. GraphQLJSONObject represents specifically JSON objects, which covers many practical use cases for JSON scalars.

Programmatically-constructed schemas

You can use this in a programmatically-constructed schema as with any other scalar type:

import GraphQLJSON, { GraphQLJSONObject } from 'graphql-type-json';

export default new GraphQLObjectType({
  name: 'MyType',

  fields: {
    myValue: { type: GraphQLJSON },
    myObject: { type: GraphQLJSONObject },
  },
});

SDL with GraphQL-tools

When using the SDL with GraphQL-tools, define GraphQLJSON as the resolver for the appropriate scalar type in your schema:

import { makeExecutableSchema } from 'graphql-tools';
import GraphQLJSON, { GraphQLJSONObject } from 'graphql-type-json';

const typeDefs = `
scalar JSON
scalar JSONObject

type MyType {
  myValue: JSON
  myObject: JSONObject
}

# ...
`;

const resolvers = {
  JSON: GraphQLJSON,
  JSONObject: GraphQLJSONObject,
};

export default makeExecutableSchema({ typeDefs, resolvers });

graphql-type-json's People

Contributors

benjie avatar cooperka avatar dependabot-preview[bot] avatar dependabot-support avatar dependabot[bot] avatar itajaja avatar jbblanchet avatar renovate-bot avatar renovate[bot] avatar taion avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

graphql-type-json's Issues

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: undefined. Note: this is a nested preset so please contact the preset author if you are unable to fix it yourself.

unable to query JSON in graphql..is this a known limitation?

Hi,

First - thanks to whoever works on this package! Not sure why it's not part of a core graphql library but it should be. I've read far and wide on the lack of support for native JSON object support within graphql, and so am guessing the best way currently available is a 3rd party package such as this.

I needed a way to work with schemaless / customer-driven data with varying structures, and so I'm using MongoDB as the schema-less store and was hoping Graphql would "play well" too.
When I attempt to run a graphql query against a JSON type (i.e. an embedded document in my collection), i get a message like so:

"message":"Field "myQuery" must not have a selection since type "JSON" has no subfields.","locations":[{"line":2,"column":37}],"details":null}]}

Is this inability to query the JSON object type natively by GraphQL just a known limitation?

For now, i'm asking my client app to pull the entire JSON object via a graphql query, and doing further drilling on the client-side, but this introduces additional overhead in many ways, including code bloat on the client app to handle what graphql is ideally suited for.

Please advise if i'm hitting a known limitation of this package with GraphQL, and if so, any better workarounds other than what i'm already doing?

Thank you,

S. Arora

Variable "$features" of type "JSON" used in position expecting type "JSON".

Hi,

I am getting this weird error when using JSON as input on a mutation:

"GraphQL error: Variable "$features" of type "JSON" used in position expecting type "JSON"."

I have followed the Apollo docs and am able to retrieve JSON. But somehow I seem unable to use it as an input.

Any clue what I'm doing wrong?

Server side schema:

    scalar JSON

    createOffer(
      token: String!
      title: String!
      description: String!
      offer_category_id: ID!
      min_price: Float!
      features: JSON
      active: Boolean
    ): Offer

Client side mutation:

const createOfferMutation = gql`
 mutation createOffer(
   $token: String!,
   $offer_category_id:ID!,
   $title: String!,
   $description:String!,
   $min_price:Float!,
   $features: JSON,
   $active:Boolean!
 ){
   createOffer(
     token: $token,
     offer_category_id:$offer_category_id,
     title: $title,
     description: $description,
     min_price: $min_price,
     features: $features,
     active: $active
   ){
       # ...
   }
 }
`;

Impossible to catch and format errors

Library throws errors of generic TypeError without any additional information attached to them. It makes it almost impossible to distinguish them from TypeErrors thrown by any other piece of code. The only option is to try to parse error messages, which is not convenient and unreliable, cuz they seem like not something that is part of the library API contract. Could you please add custom error class like this?

export class JSONTypeError extends TypeError { // Custom class makes it possible to differentiate errors thrown by this library
  constructor(message) {
    super(message)
    this.code = 'FAILED_TO_PARSE_JSON' // Optionally, may make sense to attach some sort of error code in order to  differentiate it without using `instanceof` operator
  }
}

GraphQLJSON as a argument type

Have you used this JSON type as a type for an argument ?. Can't get it working, I have this:

entries: {
  type: new GraphQLList(entryType),
  args: {
    query: { type: GraphQLJSON }
  },
  resolve: (obj, args) => client.getEntries(args.query).then(entries => entries.items)
},

When I try to pass it a parameter, let's say:

{
  entries(query: {'content_type': 'sFzTZbSuM8coEwygeUYes'}) {
    id
    fields
  }
}

Got this error:

{
  "errors": [
    {
      "message": "Syntax Error GraphQL request (2:19) Unexpected character \"'\".\n\n1: {\n2:   entries(query: {'content_type': 'sFzTZbSuM8coEwygeUYes'}) {\n                     ^\n3:     id\n",
      "locations": [
        {
          "line": 2,
          "column": 19
        }
      ]
    }
  ]
}

When I try to pass it as a string just got null on entries.

Any suggestions on how I can approach this ?.

Graphql key as number with GraphQLJSON

Good day,

I use GraphQLJSON because I found we have fields in a NoSLQ database named like "90-100", meaning they are numbers and Graphql does not allow numbers as keys.

Question is, GraphQLJSON allows me to retrieve the saved data, but does not allow me to simply do the same in a GraphQLInputObjectType.

Is there a way to get a JSON as a input so I can skip that?

Thanks a lot for the help and the package creation! :)

JSONObject can not parse objects with string keys

Considering that a JSON Object can have keys can have non alpha numerical characters like . or -, those should be wrapped in a string in javascript.

I would assume that passing JSONObject input where: { "dot.path.thing": { name: 123 }} should still pass as valid input JSONObject, but the parser throws this error:

Syntax Error GraphQL request (3:30) Expected Name, found String

I'm assuming it's some kind of limitation though... Must all JSONObject keys be Name ?

parseObject does not work for parseLiteral

When I pass a string to to a json field as a variable, I get a correct error message

Variable \"$a\" got invalid value \"foo\"; Expected type JSONObject. JSONObject cannot represent non-object value: foo

But when I do the same thing inline, without using a variable, I get this error

Expected type JSONObject, found \"foo\"; Cannot read property 'forEach' of undefined

the parseObject function expects a ast node

Errors importing

When I import like so it works:

const GraphQLJSON = require('graphql-type-json');

When I import like so it doesn't:

import GraphQLJSON from 'graphql-type-json';

The error I get is:

Error: "JSON" defined in resolvers, but has invalid value "undefined". A resolver's value must be of type object or function.

I verified that GraphQLJSON is indeed undefined with a console.log.

Any ideas?

Adding assertion or validation to the Scalar

What would it look like if I wanted to ensure that the value is a javascript object and not of any other type?

I have this definition currently under use and if I where to pass, for example, an integer value as the result this would permit it because of the way the type checks occur. My guess is that it will look something like the scalar assertions in the reference implementation (graphql-js) See this.

Can't import from graphql-type-json

Hi,

this is a minimal code snippet from a module I am developing:

import { GraphQLJSONObject } from 'graphql-type-json';

It lives inside a xxx.mjs file, which is imported by other ES6 modules in the application.

When I run this (node version 13.14) I get a fatal error:

import { GraphQLJSONObject } from 'graphql-type-json'; ^^^^^^^^^^^^^^^^^ SyntaxError: The requested module 'graphql-type-json' does not provide an export named 'GraphQLJSONObject'

I looked at the package.json file in your module and I am not sure it does the right thing, according to the node.js documentation:

"module": "es/index.js",

This is ignored by node, according to their docs (https://nodejs.org/docs/latest-v13.x/api/esm.html). Instead, one is supposed to use a conditional export in package.json , like this:

"exports": { "import": "./main-module.js", "require": "./main-require.cjs" },
main-module.js does the ES6 thing and main-require.cjs the commonJS one. Any thoughts?

Clearing a Field ?

I have a field like this

@Field(() => GraphQLJSONObject || [], { nullable: true })
@Column({ type: 'jsonb', nullable: true })
externalLinks: [{ title: string; url: string }];

it doesn't like it in typescript if I try to clear this field....

ie

foo.externalLinks = []

or

foo.externalLinks = null

"Cannot convert undefined or null to object"

I am using his package and works great - that is until I used it for an optional field. In other words, it is defined without a bang

type foo {
.
myField: JSONObject
.
}

All is well until "myfield" does not exist. Then I get the error in the title. Its is OK when the field is missing as its data coming from a partner who returns information for only a subset of our information.

Couple of notes:

Using the latest of Apollo-*/graphql/this package/etc in a Meteor/React application.
JSONObject is the right scalar for this situation but tried just plain JSON to no avail.
Schema defined and created using SDL/makeExecutableSchema()

One clue:

When I run up my app, and access the GraphQL playground rather than my own client; the playground handles this nicely and merely displays the word "null". No idea if that is helpful but I throw it out there anyway.

Any ideas?

compatibility with graphql 16 ?

The whole graphql ecosystem is moving to graphql16 (Apollo, ...)
Is it possible to update grapqhl dependency to v16 ?

thx by advance

0.1.3 and 0.1.2 contain no code on npm

You've added /lib to .gitignore so npm automatically omits it on publish. You need a .npmignore file to bypass this.

Note however that if you track lib in source control (which seems dirty, I know) people can install directly from git.

Using query variables for JSON values returns null to resolver

Query:

activityGroups: [
     {name: "Set 1", startDate: $startDate},
     {name: "Set 2", startDate: "11/01/16"}
]

Query Variables:

"startDate": "01/01/16",

In graphiql, if I pass in a query variable in, the parseLiteral in graphql-type-json wont resolve the type variable, and simpy returns null.

JSONObject as scalar in input not working

When using JSONObject scalar as an input variable, how does one use this as input in something like Insomnia? I get introspection errors when attempting to use JSON in the input variable on this scalar type:

image

Using JSON as a scalar in buildSchema function of graphql.js

Can you provide a concrete example of how to use JSON as a scalar while passing the schema to buildSchema function of graphql.js? For example, I need content as a json, something like below.

import {
    buildSchema
} from 'graphql';


export default buildSchema(`
  type Query {
    getContent: [Content]
  }
  type Content {
   content: JSON
    type: String
  }
`)

Parsed objects are not linked to Object.prototype

Is there a reason why you're creating a new object with null prototype in this section?

case Kind.OBJECT: { const value = Object.create(null);

It's causing some of my downstream code to blow up due to missing methods like hasOwnProperty.

Could this be changed instead to:

const value = {};

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Warning

These dependencies are deprecated:

Datasource Name Replacement PR?
npm codecov Unavailable
npm dtslint Unavailable

Rate-Limited

These updates are currently rate-limited. Click on a checkbox below to force their creation now.

  • chore(deps): update dependency prettier to v3
  • chore(deps): update dependency typescript to v5
  • chore(deps): update jest monorepo to v29 (major) (babel-jest, jest)
  • ๐Ÿ” Create all rate-limited PRs at once ๐Ÿ”

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

npm
package.json
  • @babel/cli ^7.12.13
  • @babel/core ^7.12.13
  • @babel/preset-env ^7.12.13
  • babel-jest ^26.6.3
  • codecov ^3.8.1
  • cpy-cli ^3.1.1
  • dtslint ^3.7.0
  • eslint ^7.19.0
  • eslint-config-4catalyzer ^1.1.5
  • eslint-config-4catalyzer-jest ^2.0.10
  • eslint-config-prettier ^6.15.0
  • eslint-plugin-import ^2.22.1
  • eslint-plugin-jest ^23.20.0
  • eslint-plugin-prettier ^3.3.1
  • graphql ^15.5.0
  • husky ^4.3.8
  • jest ^26.6.3
  • lint-staged ^10.5.4
  • prettier ^2.2.1
  • typescript ^4.1.3
travis
.travis.yml

  • Check this box to trigger a request for Renovate to run again on this repository

Unknown type "JSON"

Hi, I'm wondering if there is a simple answer as to why consumers of my schema would get this error: Unknown type "JSON". My query looks like this:

query getStuff ($filter: JSON) {
  stuff(filter: $filter){
    ...
  }
}

So, I change the type from JSON to JSONObject and the schema consumers think that's great. But now my api throws the error Unknown type "JSONObject" (before it was working fine with JSON as the type). What am I missing here?

JSONObject cannot represent non-object value

Saving data is correct and is not returning any errors. OK.

But taking the record from the database and returning the response to the request is generating the following error: JSONObject cannot represent non-object value: [object Object],[object Object],[object Object]

My model:

import { Entity, PrimaryGeneratedColumn, Column, BaseEntity } from 'typeorm';
import { ObjectType, Field, ID } from 'type-graphql';
import { GraphQLJSONObject } from 'graphql-type-json';

@ObjectType()
@Entity({ name: 'medical-templates' })
export class Contents extends BaseEntity {
  @Field(() => ID)
  @PrimaryGeneratedColumn()
  id: string;

  @Field(() => String)
  @Column({ type: 'varchar', length: 100 })
  title: string;

  @Field(() => GraphQLJSONObject)
  @Column({ type: 'json', nullable: true })
  content: any[];
}

Is there another type to be used instead of GraphQLJSONObject?

Cannot represent non-object value

I wanted to create a json object field for graphql but when I filled the db with test data to check the new field the following error appeared:
"JSONObject cannot represent non-object value: {\"test\":1,\"something\":\"2\"}"

For type definition I used a graphql scalar:
scalar JSONObject

My resolver:
JSONObject: GraphQLJSONObject

What can be wrong?

Can't get GraphQL to recognize the JSON scalar type.

Hi, I can't get GraphQL to recognize the JSON scalar type.

I followed the [apollo docs] (http://dev.apollodata.com/tools/graphql-tools/scalars.html#Using-a-package) to define a JSON GraphQL scalar type for my schema:

Schema:

    const SchemaDefinition = `
       scalar JSON
       schema {
         query: Query
         mutation: Mutation
      }
    `

    export default [
      SchemaDefinition,
      Query,
      Mutation,
      ...
    ]

Test type:

    const Test = `
      type Test {
        bodyJson: JSON
     }`

Resolver:

    import GraphQLJSON from 'graphql-type-json'

    const QueryResolver = {
      Query: {
        viewer(root, args, ctx) {
          return User.query()
            .where('id', ctx.state.user)
            .first()
         }
      }
    }

    const scalarJSON = {
      JSON: GraphQLJSON
    }

    export default {
      ...QueryResolver,
      ...ViewerResolver,
      ...scalarJSON
      ...
    }

I'm using PostgreSQL and the column I'm querying (body_json) is of data type jsonb.

If I test my schema through GraphiQL, when I return the value straight from the db (I use Knex to query) I get this error message from GraphQL:

Expected a value of type \"JSON\" but received: [object Object]

If I use JSON.stringify first on the returned value, I get this error:

"Expected a value of type \"JSON\" but received: {\"key\":\"test\"}"

Any suggestion as to what I might be doing wrong?

Incompatible with [email protected]

With the new [email protected] release, I get the following error message:

Error: Element.data field type must be Output Type but got: JSON.

the field in question is simply

data: {
  type: GraphQLJSON,
  description: "The element's data.",
},

Thanks for looking into this! :)

Quoted Object Property Name

The JSON spec allows for quoted property names

objectA["prop name"] = "blah"

However when I use with this library I receive an error

Expected Name, found String "prop name"

I've tried to replicate by updating the test cases for this library and found it fails on the parse literal test with a different error.

TypeError: Cannot read property 'value' of undefined

I'm not sure if this is a limitation of GraphQL-JS or this library, any assistance would be appreciated.

What's the purpose of specifiedByUrl ?

It is a breaking change.
I am using apollo + type-graphql setup and it seems the setup is not compatible with specifiedBy directive out of the box, as it's not outputing specifedBy directive definition without touching up here and there.

What are the benefits of having the directive that it requires touching up and it also increases size of schema.graphql file?

No validation is done for strings

Description

Any strings can be returned in a resolver of type JSON, although it's not the case for JSON.parse. eg: {}$, !!!![], a.

The implementation clearly returns the string untouched when it's a string, although JSON.parse throws for pretty much anything except a valid json: {}, [], ...

Is this expected?

Expected behavior

Error for everything that JSON.parse throws for

JSON type allows using lists at the first level

With the actual JSON type, you could do this in a graphql type :

type User {
    things: JSON

}

and the things field could accept an array of json.

[
        { "foo":"bar"},
        { "bar":"baz"}
]

But is that what we want ? The good thingsdefinitiion should be [JSON]
If you agree with this, I can do a PR if you want :)

The GraphQLJSONObject cannot be an array

For a GraphQL query that returns GraphQLJSONObject, I get an error if the return is an array rather than an object.

In my resolver:

return [{x: 1}]

This results in:

GraphQLJSONObject cannot represent non-object value: [object Object]

astFromValue: Cannot convert value to AST

Hi guys,

I'm trying to use this beautiful library in the following code, but it throws an exception:

/Users/xxx/Works/gql/node_modules/graphql/utilities/astFromValue.js:132
          throw _iteratorError;
          ^

TypeError: Cannot convert value to AST: { key: "value" }
    at astFromValue (/Users/xxx/Works/gql/node_modules/graphql/utilities/astFromValue.js:195:11)
    at astFromValue (/Users/xxx/Works/gql/node_modules/graphql/utilities/astFromValue.js:109:26)
    at Object.<anonymous> (/Users/xxx/Works/gql/app.js:73:11)
    at Module._compile (internal/modules/cjs/loader.js:738:30)
    at loader (/Users/xxx/Works/gql/node_modules/babel-register/lib/node.js:144:5)
    at Object.require.extensions.(anonymous function) [as .js] (/Users/xxx/Works/gql/node_modules/babel-register/lib/node.js:154:7)
    at Module.load (internal/modules/cjs/loader.js:630:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:570:12)
    at Function.Module._load (internal/modules/cjs/loader.js:562:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:801:12)

Here's the code

import { makeExecutableSchema } from 'graphql-tools';
import GraphQLJSON from 'graphql-type-json';
import {
  astFromValue,
  valueFromAST,
  isValidJSValue
} from 'graphql/utilities'

const typeDefs = `
scalar JSON

type MyType {
  extra: JSON
}

# ...
`;

const resolvers = {
  JSON: GraphQLJSON,
};

var schema = makeExecutableSchema({ typeDefs, resolvers });

var myType = schema.getType('Message'

var value = {
    extra: {'key': 'value'}
}


// THIS WILL THROW EXCEPTIONS
astFromValue(value, myType)

Would you please tell me how to fix this? Thanks in advance!

Is it possible to use this with graphql-tag?

I'm defining my schema using .graphql files with graphql-tag/loader webpack loader. Is it possible to use graphql-type-json with it?

For example:

type Mutation {
  myMutation(data: GraphQLJSON): GraphQLJSON
}

Graphql v0.8.0

Graphql pushed out a new update for v0.8.0, and should be included in the peerDependencies for graphql.

this isn't quite right โ€“ we should actually use the literal null support and drop < 0.8.0 support entirely

GraphQL as a bug

I am unable to specify a @field decorator that characterizes an instance + collection in a union

Getting the following error

I updated to the latest version of your lib and now when I start the web service using docker I get the following error:

For help, see: https://nodejs.org/en/docs/inspector
venueapiservice | /usr/local/lib/node_modules/graphql/jsutils/invariant.js:19
venueapiservice | throw new Error(message);
venueapiservice | ^
venueapiservice |
venueapiservice | Error: Expected { __esModule: true, GraphQLJSON: JSON, default: JSON, GraphQLJSONObject: JSONObject } to be a GraphQL nullable type.
venueapiservice | at invariant (/usr/local/lib/node_modules/graphql/jsutils/invariant.js:19:11)
venueapiservice | at assertNullableType (/usr/local/lib/node_modules/graphql/type/definition.js:333:50)
venueapiservice | at new GraphQLNonNull (/usr/local/lib/node_modules/graphql/type/definition.js:297:19)
venueapiservice | at Object. (/var/venues/services/gql/mutation/application.js:70:10)
venueapiservice | at Module._compile (internal/modules/cjs/loader.js:774:30)
venueapiservice | at Object.Module._extensions..js (internal/modules/cjs/loader.js:785:10)
venueapiservice | at Module.load (internal/modules/cjs/loader.js:641:32)
venueapiservice | at Function.Module._load (internal/modules/cjs/loader.js:556:12)
venueapiservice | at Module.require (internal/modules/cjs/loader.js:681:19)
venueapiservice | at require (internal/modules/cjs/helpers.js:16:16)

Any ideas on what is causing this error? I commented out my use of any queries and mutations so I could see if the error occurs and it does. I'm using the latest version of node and graphql 14.3.0.

Thanks

Getting GRAPHQL_PARSE_FAILED when object key has a dash

It doesn't seem to support dashes, do you know how to fix this?

For example: { myKey: true, my-key: false } (ERROR on my-key)

I get a 400 Bad Request and GRAPHQL_PARSE_FAILED:

{"errors":[{"message":"Syntax Error: Invalid number, expected digit but got: \"w\".","locations":[{"line":1,"column":260}],"extensions":{"code":"GRAPHQL_PARSE_FAILED"}}]}

I'm using apollo-server-micro.

image

image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.