All Projects → graphql-editor → Graphql Zeus

graphql-editor / Graphql Zeus

Licence: mit
GraphQL client and GraphQL code generator with GraphQL autocomplete library generation ⚡⚡⚡ for browser,nodejs and react native

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to Graphql Zeus

Create Graphql
Command-line utility to build production-ready servers with GraphQL.
Stars: ✭ 441 (-57.72%)
Mutual labels:  graphql, cli
Aliyun Cli
Alibaba Cloud CLI
Stars: ✭ 561 (-46.21%)
Mutual labels:  cli, client
Graphql
Package graphql provides a GraphQL client implementation.
Stars: ✭ 467 (-55.23%)
Mutual labels:  graphql, client
Isogram
Generate Google Analytics tracking code with any isogrammic parameters you like
Stars: ✭ 396 (-62.03%)
Mutual labels:  cli, code-generator
Githubv4
Package githubv4 is a client library for accessing GitHub GraphQL API v4 (https://docs.github.com/en/graphql).
Stars: ✭ 760 (-27.13%)
Mutual labels:  graphql, client
Graphql Ws
Coherent, zero-dependency, lazy, simple, GraphQL over WebSocket Protocol compliant server and client.
Stars: ✭ 398 (-61.84%)
Mutual labels:  graphql, client
Discline
🐍 A terminal Discord client that you can actually use.
Stars: ✭ 553 (-46.98%)
Mutual labels:  cli, client
Circleci Cli
Use CircleCI from the command line
Stars: ✭ 297 (-71.52%)
Mutual labels:  graphql, cli
Graphql
Simple low-level GraphQL HTTP client for Go
Stars: ✭ 682 (-34.61%)
Mutual labels:  graphql, client
Graphql Client
Typed, correct GraphQL requests and responses in Rust
Stars: ✭ 620 (-40.56%)
Mutual labels:  graphql, client
Re Graph
A graphql client for clojurescript and clojure
Stars: ✭ 366 (-64.91%)
Mutual labels:  graphql, client
Graphql Code Generator
A tool for generating code based on a GraphQL schema and GraphQL operations (query/mutation/subscription), with flexible support for custom plugins.
Stars: ✭ 7,993 (+666.35%)
Mutual labels:  graphql, code-generator
Graphback
Graphback - Out of the box GraphQL server and client
Stars: ✭ 323 (-69.03%)
Mutual labels:  graphql, cli
Graphql Client
A GraphQL Client for .NET Standard
Stars: ✭ 418 (-59.92%)
Mutual labels:  graphql, client
Haxor News
Browse Hacker News like a haxor: A Hacker News command line interface (CLI).
Stars: ✭ 3,342 (+220.42%)
Mutual labels:  cli, client
Saws
A supercharged AWS command line interface (CLI).
Stars: ✭ 4,886 (+368.46%)
Mutual labels:  cli, client
Graphqurl
curl for GraphQL with autocomplete, subscriptions and GraphiQL. Also a dead-simple universal javascript GraphQL client.
Stars: ✭ 3,012 (+188.78%)
Mutual labels:  graphql, cli
Eiskaltdcpp
File sharing program using DC and ADC protocols
Stars: ✭ 277 (-73.44%)
Mutual labels:  cli, client
Graphqlviz
GraphQL Server schema visualizer
Stars: ✭ 591 (-43.34%)
Mutual labels:  graphql, cli
Schemathesis
A modern API testing tool for web applications built with Open API and GraphQL specifications.
Stars: ✭ 768 (-26.37%)
Mutual labels:  graphql, cli

npm Commitizen friendly npm downloads

GraphQL Zeus creates autocomplete client library for JavaScript or TypeScript which provides autocompletion for strongly typed queries.

⚡⚡ From version 2.0 Zeus support mapped types

⚡⚡⚡ From version 3.0 Zeus supports

  • JSON schema generation
  • Subscriptions
  • ZeusHook Type for extracting the response type

Supported Languages:

  • Javascript
    • Browser
    • NodeJS
    • React Native
  • TypeScript
    • Browser
    • NodeJS
    • React Native

How it works

Given the following schema Olympus Cards

Table of contents

License

MIT

How to use

Main usage of graphql zeus should be as a CLI.

As a CLI

Installation

Install globally

$ npm i -g graphql-zeus

Of course you can install locally to a project and then use as a npm command or with npx

Usage with JavaScript

$ zeus schema.graphql ./

It will also generate corresponding out.d.ts file so you can have autocompletion,

Usage with TypeScript

$ zeus schema.graphql ./  --ts

Usage with NodeJS

$ zeus schema.graphql ./  --node

Usage with React Native

Same as browser

$ zeus schema.graphql ./

Load from URL

$ zeus https://faker.graphqleditor.com/a-team/olympus/graphql ./generated

With Authorization header

$ zeus https://faker.graphqleditor.com/a-team/olympus/graphql ./generated --header=Authorization:dsadasdASsad

Use generated client example

$ zeus https://faker.graphqleditor.com/a-team/olympus/graphql ./generated

Perform query with Chain

import { Chain } from './zeus';
const createCards = async () => {
  const chain = Chain('https://faker.graphqleditor.com/a-team/olympus/graphql');
  const listCardsAndDraw = await chain.query({
    cardById: [
      {
        cardId: 'sdsd'
      },
      {
        description: true
      }
    ],
    listCards: {
      name: true,
      skills: true,
      attack: [
        { cardID: ['s', 'sd'] },
        {
          name: true
        }
      ]
    },
    drawCard: {
      name: true,
      skills: true,
      Attack: true
    }
  });
};
createCards();
// Result of a query
// {
//     "drawCard": {
//         "Attack": 83920,
//         "name": "Raphaelle",
//         "skills": [
//             "RAIN",
//             "
",
//         ]
//     },
//     "cardById": {
//         "description": "Customer"
//     },
//     "listCards": [
//         {
//             "name": "Lon",
//             "skills": [
//                 "THUNDER"
//             ],
//             "attack": [
//                 {
//                     "name": "Christop"
//                 },
//                 {
//                     "name": "Theodore"
//                 },
//                 {
//                     "name": "Marcelle"
//                 }
//             ]
//         },
//         {
//             "name": "Etha",
//             "skills": null,
//             "attack": [

//                 {
//                     "name": "Naomie"
//                 }
//             ]
//         },
//         {
//             "attack": [
//                 {
//                     "name": "Kyle"
//                 },
//             ],
//             "name": "Arlene",
//             "skills": [
//                 "FIRE",
//             ]
//         }
//     ]
// }

Listen on a websocket - GraphQL Subscription

This creates websocket connection between your backend GraphQL socket and web browser one.

const chain = Chain('https://faker.graphqleditor.com/a-team/olympus/graphql');
chain
  .subscription({
    cardPile: {
      id: true,
    },
  })
  .on((response) => {
    console.log(response.cardPile);
  });

Perform query with Thunder - Abstracted Fetch function

With thunder you have total control of fetch function not losing the result format the same time.

import { Thunder } from './zeus';
const createCards = async () => {
  const thunder = Thunder(async (query) => {
    const response = await fetch('https://faker.graphqleditor.com/a-team/olympus/graphql', {
      body: JSON.stringify({ query }),
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
    });
    if (!response.ok) {
      return new Promise((resolve, reject) => {
        response
          .text()
          .then((text) => {
            try {
              reject(JSON.parse(text));
            } catch (err) {
              reject(text);
            }
          })
          .catch(reject);
      });
    }
    const json = await response.json();
    return json.data;
  });
  const listCardsAndDraw = await thunder.query({
    cardById: [
      {
        cardId: 'sdsd',
      },
      {
        description: true,
      },
    ],
    listCards: {
      name: true,
      skills: true,
      attack: [
        { cardID: ['s', 'sd'] },
        {
          name: true,
        },
      ],
    },
    drawCard: {
      name: true,
      skills: true,
      Attack: true,
    },
  });
};
createCards();
// Result of a query
// {
//     "drawCard": {
//         "Attack": 83920,
//         "name": "Raphaelle",
//         "skills": [
//             "RAIN",
//             "THUNDER",
//         ]
//     },
//     "cardById": {
//         "description": "Customer"
//     },
//     "listCards": [
//         {
//             "name": "Lon",
//             "skills": [
//                 "THUNDER"
//             ],
//             "attack": [
//                 {
//                     "name": "Christop"
//                 },
//                 {
//                     "name": "Theodore"
//                 },
//                 {
//                     "name": "Marcelle"
//                 }
//             ]
//         },
//         {
//             "name": "Etha",
//             "skills": null,
//             "attack": [

//                 {
//                     "name": "Naomie"
//                 }
//             ]
//         },
//         {
//             "attack": [
//                 {
//                     "name": "Kyle"
//                 },
//             ],
//             "name": "Arlene",
//             "skills": [
//                 "FIRE",
//             ]
//         }
//     ]
// }

Unions

You can use Zeus with unions:

const { drawChangeCard } = await chain.query({
  drawChangeCard: {
    __typename: true,
    '...on EffectCard': {
      effectSize: true,
      name: true,
    },
    '...on SpecialCard': {
      effect: true,
      name: true,
    },
  },
});
// drawChangeCard result:
// {
//     "effectSize": 195.99532210956377,
//     "name": "Destinee",
//     "__typename": "EffectCard"
// }

Interfaces

And interfaces.

const { nameables } = await Gql.query({
  nameables: {
    __typename: true,
    name: true,
    '...on CardStack': {
      cards: {
        Defense: true,
      },
    },
    '...on Card': {
      Attack: true,
    },
  },
});
// result
// {
//     "nameables": [
//         {
//             "__typename": "EffectCard",
//             "name": "Hector"
//         },
//         {
//             "__typename": "CardStack",
//             "name": "Scotty",
//             "cards": [
//                 {
//                     "Defense": 1950
//                 },
//                 {
//                     "Defense": 76566
//                 },
//                 {
//                     "Defense": 64261
//                 }
//             ]
//         },
//         {
//             "__typename": "SpecialCard",
//             "name": "Itzel"
//         },
//     ]
// }

Perform query with aliases

const aliasedQueryExecute = await chain.query({
  listCards: {
    __alias: {
      atak: {
        attack: [
          { cardID: ['1'] },
          {
            name: true,
            description: true,
          },
        ],
      },
    },
  },
});
// RESULT
// {
//     "listCards": [
//         {
//             "atak": {
//                 "attack": [
//                     {
//                         "name": "Zelma",
//                         "description": "Central"
//                     }
//                 ]
//             }
//         }
//     ]
// }

So you can access properties type-safe like this

aliasedQueryExecute.listCards.map((c) => c.atak.attack);

Variables

To perform query with variables please import $ function and pass the variables to query

const test = await Gql.mutation(
  {
    addCard: [
      {
        card: $`card`,
      },
      {
        id: true,
        description: true,
        name: true,
        Attack: true,
        skills: true,
        Children: true,
        Defense: true,
        cardImage: {
          bucket: true,
          region: true,
          key: true,
        },
      },
    ],
  },
  {
    card: {
      Attack: 2,
      Defense: 3,
      description: 'Lord of the mountains',
      name: 'Golrog',
    },
  },
);

Gql string

Use Zeus to generate gql string

import { Zeus } from './zeus';
const createCards = async () => {
  const stringGql = Zeus.query({
    listCards: {
      name: true,
      skills: true,
      Attack: true,
    },
  });
  // query{listCards{name skills Attack}}
};
createCards();

To run the example navigate to: ./examples and run

$ npm i

then run

$ npm run start

Use Api for single queries mutations and Chain for query chaining

JavaScript Type Casting

You can cast your response from fetch/apollo/other-lib to correct type even if you are using JavaScript:

import { Cast } from './zeus';
const myQuery = Cast.query(myLib('somegraphqlendpoint'));

Typescript SelectionSet

In TypeScript you can make type-safe selection sets to reuse them across queries You can use Selectors on operations or ZeusSelect on concrete type. Only Selectors make sense in JS as usage of ZeusSelect on type is impossible without type support :)

import { ZeusSelect, Selectors, Chain, ValueTypes } from './zeus';
const chain = Chain('https://faker.graphqleditor.com/a-team/olympus/graphql');

const { drawCard: cardSelector } = Selectors.query({
  drawCard: {
    name: true,
    description: true,
    Attack: true,
    skills: true,
    Defense: true,
    cardImage: {
      key: true,
      bucket: true,
    },
  },
});

const cardSelector2 = ZeusSelect<ValueTypes['Card']>()({
  name: true,
  description: true,
  Attack: true,
  skills: true,
  Defense: true,
  cardImage: {
    key: true,
    bucket: true,
  },
});

const queryWithSelectionSet = await chain.query({
  drawCard: cardSelector,
  listCards: cardSelector2,
});

Usage with React Hooks and Apollo Client

GraphQL Zeus can be used in combination with Apollo Client's React hooks to provide typed versions of useQuery(), useMutation(), and useSubscription(). Below is what the implementation looks like (please note the comment about root typenames, like query_root).

import {
  gql,
  MutationHookOptions,
  QueryHookOptions,
  SubscriptionHookOptions,
  useMutation,
  useQuery,
  useSubscription,
} from '@apollo/client';

/**
 * If your query/mutation/subscription root fields are named differently
 * you will need to alter the imports and references in "ValueTypes" below
 */
import { MapType, ValueTypes, Zeus, mutation_root, query_root, subscription_root } from './generated/graphql-zeus';

export function useTypedQuery<Q extends ValueTypes['query_root']>(
  query: Q,
  options?: QueryHookOptions<MapType<query_root, Q>, Record<string, any>>,
) {
  return useQuery<MapType<query_root, Q>>(gql(Zeus.query(query)), options);
}

export function useTypedMutation<Q extends ValueTypes['mutation_root']>(
  mutation: Q,
  options?: MutationHookOptions<MapType<mutation_root, Q>, Record<string, any>>,
) {
  return useMutation<MapType<mutation_root, Q>>(gql(Zeus.mutation(mutation)), options);
}

export function useTypedSubscription<Q extends ValueTypes['subscription_root']>(
  subscription: Q,
  options?: SubscriptionHookOptions<MapType<subscription_root, Q>, Record<string, any>>,
) {
  return useSubscription<MapType<subscription_root, Q>>(gql(Zeus.subscription(subscription)), options);
}

ZeusHook

Assuming that you created hook like function

import { Gql, ZeusHook } from './zeus';

export const useZeus = () => {
  const drawACard = () => {
    return Gql.query({
      drawCard: {
        name: true,
        Attack: true,
        Defense: true,
        Children: true,
        description: true,
      },
    });
  };
  return { drawACard };
};

type DrawCardResponse = ZeusHook<typeof useZeus, 'drawACard'>;

Zeus generates an easy to use Type so you can decalare your zeus queries inside function

Spec

Promise of type query data object is returned.

PROMISE_RETURNING_OBJECT = Chain.[OPERATION_NAME]({
    ...FUNCTION_FIELD_PARAMS
})(
    ...QUERY_OBJECT
).then ( RESPONSE_OBJECT => RESPONSE_OBJECT[OPERATION_FIELD] )

Simple function params object

FUNCTION_FIELD_PARAMS = {
  KEY: VALUE
}

Query object

QUERY_OBJECT = {
    ...RETURN_PARAMS
}

Return params is an object containg RETURN_KEY - true if it is a scalar, RETURN_PARAMS if type otherwise it is a function where you pass Fiel params and type return params.

RETURN_PARAMS = {
    RETURN_KEY: true,
    RETURN_KEY: {
        ...RETURN_PARAMS
    },
    RETURN_FUNCTION_KEY:[
        {
            ...FUNCTION_FIELD_PARAMS
        },
        {
            ...RETURN_PARAMS
        }
    ]
}

Use Alias Spec

RETURN_PARAMS = {
  __alias: RETURN_PARAMS
}

Access aliased operation type-safe

PROMISE_RETURNING_OBJECT[ALIAS_STRING][OPERATION_NAME]

Use In your Project to generate code

This will be rarely used, but here you are!

import { Parser, TreeToTS } from 'graphql-zeus';

const schemaFileContents = `
type Query{
    hello: String!
}
schema{
    query: Query
}
`;

const typeScriptDefinition = TreeToTS.resolveTree(Parser.parse(schemaFileContents));

const jsDefinition = TreeToTS.javascript(Parser.parse(schemaFileContents));

Use in your project to dynamically fetch schema

This is useful when you need some schema fetched from your GraphQL endpoint

import { Utils } from 'graphql-zeus';

Utils.getFromUrl('https://faker.graphqleditor.com/a-team/olympus/graphql').then((schemaContent) => {
  // Use schema content here
});

Support

Join our GraphQL Editor Channel

Leave a star ;)

Contribute

For a complete guide to contributing to GraphQL Editor, see the Contribution Guide.

  1. Fork this repo
  2. Create your feature branch: git checkout -b feature-name
  3. Commit your changes: git commit -am 'Add some feature'
  4. Push to the branch: git push origin my-new-feature
  5. Submit a pull request

Parsing

Simplier approach to GraphQL parsing. Using graphql-js library and parsing AST to simplier types.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].