• Stars
    star
    374
  • Rank 114,346 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 6 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Generate queries from graphql schema, used for writing api test.

gql-generator

Generate queries from graphql schema, used for writing api test.

Example

# Sample schema
type Query {
  user(id: Int!): User!
}

type User {
  id: Int!
  username: String!
  email: String!
  createdAt: String!
}
# Sample query generated
query user($id: Int!) {
  user(id: $id){
    id
    username
    email
    createdAt
  }
}

Usage

# Install
npm install gql-generator -g

# see the usage
gqlg --help

# Generate sample queries from schema file
gqlg --schemaFilePath ./example/sampleTypeDef.graphql --destDirPath ./example/output --depthLimit 5

Now the queries generated from the sampleTypeDef.graphql can be found in the destDir: ./example/output.

This tool generate 3 folders holding the queries: mutations, queries and subscriptions. And also index.js files to export the queries in each folder.

You can require the queries like this:

// require all the queries
const queries = require('./example/output');
// require mutations only
const mutations = require('./example/output/mutations');

// sample content
console.log(queries.mutations.signup);
console.log(mutations.signup);
/*
mutation signup($username: String!, email: String!, password: String!){
  signup(username: $username, email: $email, password: $password){
    token
    user {
      id
      username
      email
      createdAt
    }
  }
}
*/

The tool will automatically exclude any @deprecated schema fields (see more on schema directives here). To change this behavior to include deprecated fields you can use the includeDeprecatedFields flag when running the tool, e.g. gqlg --includeDeprecatedFields.

Programmatic Access

Alternatively, you can run gql-generator directly from your scripts:

const gqlg = require('gql-generator')

gqlg({ schemaFilePath: './example/sampleTypeDef.graphql', destDirPath: './example/output', depthLimit: 5 })

Usage example

Say you have a graphql schema like this:

type Mutation {
  signup(
    email: String!
    username: String!
    password: String!
  ): UserToken!
}

type UserToken {
  token: String!
  user: User!
}

type User {
  id: Int!
  username: String!
  email: String!
  createdAt: String!
}

Before this tool, you write graphql api test like this:

const { GraphQLClient } = require('graphql-request');
require('should');

const host = 'http://localhost:8080/graphql';

test('signup', async () => {
  const gql = new GraphQLClient(host);
  const query = `mutation signup($username: String!, email: String!, password: String!){
    signup(username: $username, email: $email, password: $password){
      token
      user {
        id
        username
        email
        createdAt
      }
    }
  }`;

  const data = await gql.request(query, {
    username: 'tim',
    email: '[email protected]',
    password: 'samplepass',
  });

  (typeof data.signup.token).should.equal('string');
);

As gqlg generated the queries for you, you don't need to write the query yourself, so your test will becomes:

const { GraphQLClient } = require('graphql-request');
require('should');
const mutations = require('./example/output/mutations');

const host = 'http://localhost:8080/graphql';

test('signup', async () => {
  const gql = new GraphQLClient(host);

  const data = await gql.request(mutations.signup, {
    username: 'tim',
    email: '[email protected]',
    password: 'samplepass',
  });

  (typeof data.signup.token).should.equal('string');
);

Notes

  • As this tool is used for tests, it expands all of the fields in a query. There might be recursive fields in the query, so gqlg ignores the types which have been added in the parent queries already by default. This can be disabled using the --includeCrossReferences argument.
  • Variable names are derived from argument names, so variables generated from multiple occurrences of the same argument name must be deduped. An index is appended to any duplicates e.g. region(language: $language1).

More Repositories

1

chinese-independent-blogs

中文独立博客列表
JavaScript
20,246
star
2

chart.xkcd

xkcd styled chart lib
JavaScript
7,622
star
3

openprompt.co

Create. Use. Share. ChatGPT prompts
JavaScript
1,168
star
4

hacker-job-trends

Play with hackernews' "who is hiring"
JavaScript
749
star
5

sideproject.guide

Notes on how to build side projects
JavaScript
480
star
6

resumd

Write resume with markdown
JavaScript
423
star
7

star-history-plugin

[Deprecated] project moved to https://github.com/timqian/star-history as a mono repo
CSS
266
star
8

js-code-structure

Analyse the structure of your js project (relations between js files)
HTML
166
star
9

my-headline

Deprecated, visit https://github.com/headllines
JavaScript
98
star
10

one-goal

A macOS menu bar APP helps you stay focused
Swift
91
star
11

auth-api

Auth part of your RESTful API
JavaScript
51
star
12

weekly-report

weekly report from git commits
JavaScript
50
star
13

scientific-computation-libs-in-javascript

Feel free to PR
42
star
14

my-headline-crawler

Crawler for my-headline
HTML
36
star
15

mathlab

Aimed to be the best matrix lab in javascript
JavaScript
34
star
16

modsoul

🔨🔨莫得灵魂乐团
C++
27
star
17

letcode.ai

JavaScript
21
star
18

v2ex-online-number

V2EX 的心电图(在线人数随时间的变化)
HTML
17
star
19

dapp-possiblities

Explore possible usage of dapp
Solidity
16
star
20

music-lab

JavaScript
13
star
21

sponsor.cat

🔨 A decentralized funding platform. Powered by NFTs.
JavaScript
12
star
22

follows-you

Adds a tag indicating whether a user follows you on GitHub
JavaScript
12
star
23

Online_Snake_Battle

一个HTML5 实时对战小游戏,使用了socket.io
HTML
10
star
24

hackernotes

Record news/ideas/thoughts interests me, update daily(hopefully)
7
star
25

my-notes

7
star
26

viti

A 100 line shadowsocks like tunneling proxy in nodejs.
JavaScript
7
star
27

anahub

open-source / serverless / self-hostable google-analytics alternative 🔨🔨comming soon...
JavaScript
7
star
28

invoice-automation

JavaScript
7
star
29

GiG

Content Management System using github as its backend
JavaScript
6
star
30

express-rate-limit-redis

An express rate-limiting middleware using redis as its storage
TypeScript
6
star
31

0daydown_get_baidu_pan

get baidu pan link and password from feeds of www.0daydown.com
HTML
6
star
32

acl-matrix

Use matrix to describe your application's access control list (ACL)
JavaScript
5
star
33

timqian.github.io

HTML
4
star
34

v2.run

3
star
35

murmur

🔨WIP🔨 A serverless, customizable comment system
JavaScript
3
star
36

json2landing

Generate landing page from json
JavaScript
3
star
37

things-to-build

3
star
38

SSNN

Simple Spiking Neural Networks
JavaScript
2
star
39

issue-blog-view

Writing blog using github issue? Then this chrome extension is for you
JavaScript
2
star
40

comment-chain

comment on every webpage
2
star
41

tplayer

JavaScript
2
star
42

serverless-component-http

WIP 🔨 Deploy any Node.js http server serverlessly. Use any framework you like - Vanilla HTTP server, express, koa, apollo-server...
JavaScript
2
star
43

zip-performance-comparsion

JavaScript
2
star
44

OpenPrice

TypeScript
2
star
45

HackEngine-offline-7-openprompt-copilot-for-prompts

TypeScript
2
star
46

2019nCoV-map

2019 nCoV 数据市级可视化
2
star
47

timqian

1
star
48

es6-backend-starter

backend starter for myself
1
star
49

make-a-cpu

数电学习笔记
1
star
50

reg-match-arr

JavaScript
1
star
51

sls-action

JavaScript
1
star
52

cos-global-acceleration-speed-tests

JavaScript
1
star
53

blog

My personal blog (in English)
CSS
1
star
54

get-unique-name

Generate a unique name used for creating tmp folder/file/simpleId; with no dependency, using Date and Math.random
JavaScript
1
star
55

stocks

试图对股票市场做一点分析
HTML
1
star
56

buildAComputer

My implementation of the project: [From NAND to Tetris](http://nand2tetris.org/)
Assembly
1
star
57

images

hosting my images, using picGo
1
star
58

folder-ponder

Get details of a folder(info of each file) quickly
JavaScript
1
star
59

test-permission

JavaScript
1
star
60

.vim

1
star
61

npm-package-template

A dead-simple template to write and publish npm packages
JavaScript
1
star
62

adm-zip-test

JavaScript
1
star
63

rgba-to-img-to-rgba

Transform img to rgba data && transform rgba data array to img
JavaScript
1
star