DEV Community

Birol AYDIN
Birol AYDIN

Posted on

GraphQL-JIT Basic Example

npm i -D typescript tsx
Enter fullscreen mode Exit fullscreen mode
npm i --save-dev graphql @graphql-tools/schema graphql-jit
Enter fullscreen mode Exit fullscreen mode
import { makeExecutableSchema } from "@graphql-tools/schema";
import { parse } from "graphql";
import { compileQuery, isCompiledQuery } from "graphql-jit";

const typeDefs = `
  type Query {
    hello: String
    goodbye: String
    users: [User!]!
  }

  type User {
    name: String!
    age: Int!
  }
`;

const users = [
  {
    name: "John",
    age: 30
  },
  {
    name: "Jane",
    age: 25
  }
];

const resolvers = {
  Query: {
    hello: () => "World!",
    goodbye: () => "Goodbye!",
    users: () => users
  },
};

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

const query = `
  query GetHello {
    hello
  }

  query GetGoodbye {
    goodbye
  }

  query GetUsers
  {
    users
    {
      name
      age
    }
  }
`;

const document = parse(query);

const compilerOptions = {
  customJSONSerializer: true,
};

const operationName = "GetUsers";

const compiledQuery = compileQuery(schema, document, operationName, compilerOptions);

if (!isCompiledQuery(compiledQuery)) {
  console.error(compiledQuery);
  throw new Error("Error compiling query");
}

const executionResult = await compiledQuery.query(null, null, null);
//console.log(executionResult);
console.log(JSON.stringify(executionResult, null, 2));
Enter fullscreen mode Exit fullscreen mode

Top comments (0)