tiny-graphql-query-compiler
TypeScript icon, indicating that this package has built-in type declarations

0.2.3 • Public • Published

tiny-graphql-query-compiler

tiny-graphql-query-compiler provides a JavaScript-land DSL for constructing GraphQL queries.

Example:

import { compile } from "tiny-graphql-query-compiler";

const query = compile({
  type: "query",
  fields: {
    id: true,
    name: true,
    age: true,
  },
});

// query =>
`
query {
  id
  name
  age
}
`;

To pass arguments, you can use the Call helper:

import { compile, Call } from "tiny-graphql-query-compiler";

const query = compile({
  type: "query",
  fields: {
    user: Call(
      { id: 1 },
      {
        id: true,
        name: true,
        age: true,
      }
    ),
  },
});

// query =>
`
query {
  user(id: 1) {
    id
    name
    age
  }
}
`;

To pass arguments using GraphQL variables, you can use the Call helper with the Var helper:

import { compile, Call, Var } from "tiny-graphql-query-compiler";

const query = compile({
  type: "query",
  fields: {
    user: Call(
      { id: Var({ type: "ID!" }) },
      {
        id: true,
        name: true,
        age: true,
      }
    ),
  },
});

// query =>
`
query ($id: ID!) {
  user(id: $id) {
    id
    name
    age
  }
}
`;

To get back a query and a set of variables to pass to that query, use the compileWithVariableValues function, and pass a value to each one of your variables:

import { compile, Call, Var } from "tiny-graphql-query-compiler";

const { query, variables } = compileWithVariableValues({
  type: "query",
  fields: {
    user: Call(
      { id: Var({ type: "ID!", value: 1 }) },
      {
        id: true,
        name: true,
        age: true,
      }
    ),
  },
});

// query =>
`
query ($id: ID!) {
  user(id: $id) {
    id
    name
    age
  }
}
`;

// variables =>
{
  id: 1;
}

await someClient.execute({ query, variables });

Readme

Keywords

none

Package Sidebar

Install

npm i tiny-graphql-query-compiler

Weekly Downloads

12,307

Version

0.2.3

License

MIT

Unpacked Size

35.5 kB

Total Files

10

Last publish

Collaborators

  • airhorns
  • scott-rc