0.1.7 • Published 4 years ago

graphql-schema-query v0.1.7

Weekly downloads
5
License
MIT
Repository
github
Last release
4 years ago

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<
  {
    helloWorld: string;
  },
  {
    anyVariable: string;
  }
> = gql`
  query($anyVariable: String!) {
    helloWorld(anyVariable: $anyVariable)
  }
`;

const helloWorld = async () => {
  const data = await executeFromSchema(HelloWorldQuery, {
    variables: {
      anyVariable: 'asd',
    },
  });

  // data === { helloWorld: string } | undefined | null
};
0.1.7

4 years ago

0.1.6

4 years ago

0.1.5

4 years ago

0.1.4

4 years ago

0.1.3

4 years ago

0.1.2

4 years ago

0.1.1

4 years ago

0.1.0

4 years ago