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

0.1.7 • Public • Published

graphql-schema-query

npm version bundlephobia license

yarn add graphql-schema-query
# or 
npm install graphql-schema-query

This small library is made to execute a GraphQL query or mutation without the need of any http request, and just using the GraphQL schema generated from TypeGraphQL, Nexus Schema or any other.

Useful for testing, referencing your own resolvers without any hassle or repeating code.

And specially the reason I made this library, for getServerSideProps and getStaticProps usage in Next.js

Usage

import schemaQuery from 'graphql-schema-query';
 
// ...
import { makeSchema } from '@nexus/schema';
 
export const schema = makeSchema({
  // ...
});
 
// or
 
import { buildSchemaSync } from 'type-graphql';
 
export const schema = buildSchemaSync({
  // ...
});
 
// ...
 
export const executeFromSchema = schemaQuery(schema);

Then, anywhere you need to use it:

import { executeFromSchema } from './[anywhere]';
import { gql } from 'graphql-squema-query';
// import gql from "graphql-tag"; also works
 
const helloWorld = async () => {
  // You can use a plain string
  executeFromSchema(`query {
        helloWorld
    }`);
 
  // Or you can use a graphql-tag document,
  // which gives you some nice editor formatting
  executeFromSchema(gql`
    query {
      helloWorld
    }
  `);
};

Protip

This library is using graphql-tag-ts, which can give you some nice type-safety from the gql tag itself, writing less code without any performance penalty.

For example:

import { executeFromSchema } from './[anywhere]';
import { gql, DocumentNode } from 'graphql-schema-query';
// import gql, { DocumentNode } from "graphql-tag-ts"; also works
 
const HelloWorldQuery: DocumentNode<
  {
    helloWorldstring;
  },
  {
    anyVariablestring;
  }
> = gql`
  query($anyVariable: String!) {
    helloWorld(anyVariable: $anyVariable)
  }
`;
 
const helloWorld = async () => {
  const data = await executeFromSchema(HelloWorldQuery, {
    variables: {
      anyVariable: 'asd',
    },
  });
 
  // data === { helloWorld: string } | undefined | null
};

Package Sidebar

Install

npm i graphql-schema-query

Weekly Downloads

0

Version

0.1.7

License

MIT

Unpacked Size

20.6 kB

Total Files

15

Last publish

Collaborators

  • pablosz