Skip to content

Validating a JSON Object against GraphQL Type #2343

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
rawkode opened this issue Jan 10, 2020 · 2 comments
Closed

Validating a JSON Object against GraphQL Type #2343

rawkode opened this issue Jan 10, 2020 · 2 comments
Labels

Comments

@rawkode
Copy link

rawkode commented Jan 10, 2020

Is it possible to validate a JSON document against a GraphQL Output Type?

I found these docs: https://graphql.org/graphql-js/utilities/

I am able to load the schema and get the types. I can't work out how to validate a JSON doc against one of those types though.

I've tried astFromValue and isValidJSValue; both without success.

Please help :)

This is where I am thus far:

jest.disableAutomock();

const fs = require("fs");
const graphql = require("graphql");
const yaml = require("js-yaml");

test("adds 1 + 2 to equal 3", () => {
  const teamMemberSchema = fs.readFileSync(
    "../../schemas/graphql/team/member.graphql",
    "utf8"
  );

  const schema = graphql.buildSchema(teamMemberSchema);

  const members = yaml.safeLoadAll(
    fs.readFileSync("../../examples/team/member.yaml", "utf8")
  );

  members.map(member => {
    const result = ???;
    console.log(result);
  });

  expect(1 + 2).toBe(3);
});
@IvanGoncharov
Copy link
Member

@rawkode There is no specialized function for astFromValue and isValidJSValue are intended to work with Input types only.
The resolution of output types heavily depends on resolvers so output data is validated only during query execution.

What you can do is to use graphql:

const testSchema = new GraphQLSchema({
  query: new GraphQLObjectType({
    name: 'Query',
    fields: {
      testField: {
        type: new GraphQLList(schema.getType('SomeType')),
      }
    }
  });
})

const source = `
  {
     testField {
       someField
       # All other subfields
     }
  }
`;

const result = graphqlSync({ schema: testSchema, source, rootValue: members });
expect(result.errors).to.equal(undefined);
expect(result.data.testField).to.deep.equal(members);

Disclaimer: I didn't run this code just wrote it from the top of my head.

@IvanGoncharov
Copy link
Member

Also, it's partly overlaps with #563

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants