gqlizer
TypeScript icon, indicating that this package has built-in type declarations

0.0.14 • Public • Published

The power of GQL in its simplest form

GQLizer allows you to use GraphQL anywhere for anything.

WARNING: This package is a work in progress and does not follow semantic versioning.

Usage

There's two ways to use GQLizer:

  1. You can use the resolver directly
import { gql, resolveQuery, ResolverFn } from "gqlizer";

const myAwesomeResolver: ResolverFn = (operations) => {
  // ...
};

const result = await resolveQuery({
  resolver: myAwesomeResolver,
  query: gql`
    {
      User(id: 1) {
        id
        firstName
        lastName
      }
    }
  `,
});

console.log(result);
  1. Or you can create a "client" that you can export and use in your application.
// resolveQuery.ts
import createQueryResolver, { ResolverFn } from "gqlizer";

const myAwesomeResolver: ResolverFn = (operations) => {
  // ...
};

export const resolveQuery = createQueryResolver(myAwesomeResolver);

// somewhere_else.ts
import { gql } from "gqlizer";
import { resolveQuery } from "./resolveQuery";

const result = await resolveQuery(gql`
  {
    User(id: 1) {
      id
      firstName
      lastName
    }
  }
`);

console.log(result);

Resolver

The resolver API was thought so it can be called as little as possible.

The resolver function has a single argument, an array of operations. This is because GQLizer calls the resolver once per depth level, and not for each field. This gives you the chance to make the resolver as fast as possible.

For example: if you are trying to use GQLizer for your own REST API, you could potentially implement an endpoint to resolve the whole array of operations in a single call.

The resolver has to return an array of DocumentLike objects.

type ResolverFn = (operations: Operation[]) => Promise<DocumentLike[]>;

type Operation = {
  handle: string; // The name of the field to resolve
  params?: QueryParams; //  Argument passed to the query of this field
  parent?: DocumentLike; // The result of the parent operation
};

type DocumentLike = Record<string, unknown>;

Notes

  1. This package re-exports gql and GqlDocumentNode from graphql-tag for convenience.

  2. We DO NOT validate the query. You should do that yourself.

  3. We export some utilities that we use under the hood, because why not?

    • assert: a simple assertion function
    • combineArrays: a function that merges two arrays
    • groupBy: a function that groups items by a key
    • isStringArray: a function that checks if an array is made of strings
    • parseGql: a function that transforms a query into a simpler object

Full Example using Star Wars API (SWAPI)

https://stackblitz.com/edit/gqlizer-example-swapi?file=index.ts

Package Sidebar

Install

npm i gqlizer

Weekly Downloads

0

Version

0.0.14

License

MIT

Unpacked Size

61.4 kB

Total Files

107

Last publish

Collaborators

  • maxizipitria