• Stars
    star
    405
  • Rank 106,656 (Top 3 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 7 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

GraphQL query utility for serverside apps


GotQL


Write GraphQL queries as objects instead of strings

JavaScript Style Guide

This is a better implementation of the GraphQL query API via NodeJS, created as a wrapper of Got. It works like a transpiler, with a built in HTTPRequest Client (Got), allowing you to write your GraphQL queries as Javascript Objects instead of strings.

Built because manipulating strings is a real pain.

Table of Contents

Install

$ npm install gotql

Or

$ yarn install gotql

Basic Usage

const gotQl = require('gotql')

const query = {
  operation: {
    name: 'users',
    fields: ['name', 'age', 'id']
  }
}

const options = {
  headers: {
    "Authorization": "Bearer <token>"
  },
  debug: false,
  useHttp2: false
}

gotQL.query('mygraphqlendpoint.com.br/api', query, options)
  .then(response => console.log(response.data))
  .catch(console.error)

What is it?

GotQL is a better interface for GraphQL queries. It provides a way for developers to run queries using JSON instead of strings. Which is a way more usable data format than the string itself.

See more on: https://hasura.io/blog/fluent-graphql-clients-how-to-write-queries-like-a-boss/

Motivation

Manipulating strings is very smelly, even on dynamically typed languages. So, in order to avoid things such as this:

Which can be translated to something waay more readable in a JSON format like this:

const mutation = {
  operation: {
    name: 'addLog',
    args: {
      logType: literal`status_change`, // Enum Value
      fromState: variables.fromState,
      toState: variables.toState,
      idUser: variables.idUser,
      idCampaign: variables.idCampaign,
      owner: {
        ownerType: variables.ownerType,
        username: variables.username,
        picture: variables.picture,
        name: variables.name,
        id: variables.id
      }
    },
    fields: [ 'uuid' ]
  }
}

This is why GotQL was created.

API

gotQl.query(graphQLEndpoint, query, [options])
  • Description: Performs a graphQL query

GraphQLEndpoint

  • Type: string
  • Description: The GraphQL endpoint to query on

query

options

See option object for more information.


gotQl.mutation(graphQLEndpoint, query, [options])
  • Description: Performs a graphQL mutation

GraphQLEndpoint

  • Type: string
  • Description: The GraphQL endpoint to query on

query

options

See option object for more information.


gotQl.parser(query, type)
  • Description: Parses a JSON-Like query and returns the query's string

query

type

  • Type: string
  • Description: Must be either 'query' or 'mutation'

Option Object

Both gotql.query and gotql.mutation accept an optional user option object with the following API:

  • Type: object
  • Description: The option object with the following properties.
    • errorStatusCode: Default HTTP status code to be returned on error
      • Type: number
    • headers: Additional headers to be sent
      • Type: object, in the form of [headerName: string]: headerValue: string
    • gotInstance: Customized Got instance to be used when calling the endpoint
      • Type: got. Internally this will be called as got.post(prependHttp(endPoint), gotPayload)
    • useHttp2: Boolean defining if the call should be made using HTTP2, defaults to false (see release 11 of got)
      • Type: boolean

Note: GotQL uses debug internally as default debugger, so you can set debug levels by setting the DEBUG environment variable. These are the current levels:

  • gotql:info
  • gotql:info:parser
  • gotql:info:runner
  • gotql:errors

Returns

All methods return a string like this:

const response = 'query { test { name args } }'

The JSON query format

The JSON format gotQL uses is a simple and intuitive description based on the anatomy of a GraphQL query blog post.

This is a generic model of a JSONLike query:

const query = {
  name?: string,
  operation: {
    name: string,
    alias?: string,
    args?: { [argName: string]: any } | {
      [argName: string]: {
        value: string,
        escape: boolean
      }
    },
    fields: (string | {
      [fieldName: string]: [{
        args?: { [argName: string]: any } | {
          [argName: string]: {
            value: string,
            escape: boolean
          }
        },
        fields?: (string | { [fieldName: string]: [any] })[]
      }]
    })[]
  },
  variables?: {
    [varName: string]: {
      type: string,
      value: string
    }
  }
}

Description

  • Query:
    • Type: object
    • Description: The full query object
    • Properties:
      • name: [optional]: Query name
        • Type: string
      • variables: [optional] Query variable declaration
        • Type: object with signature like [varName: string]: { type: string, value: string }
        • Properties:
          • varName: Variable name
            • Type: string
          • type: Variable type. Can be a GraphQL definition of type (i.e: string!)
            • Type: string
          • value: Variable value
            • Type: any
      • operation: The query operation (action that will be executed)
        • Type: object
        • Properties:
          • name: The operation name
            • Type: string
          • alias: [optional] An alias to give the operation
            • Type: string
          • args: [optional] The operation args
            • Type: [argName: string]: any or a detailed arg object
              • Simple args: An object where the key is the argument name and its value. Accepts variables in the format of argName: '$value'
                • Example: args { name: 'myName' }
              • Detailed args: A tagged template. This will give more control over escaping (mostly to use enums). Argument name should be the key
                • Type: tagged template
                • Examples: args: { status: literal`an_enum` } should output operation (status: an_enum)...
          • fields: The field list to get back from the operation
            • Type: An array of object (to use nested fields) or string, or both.
            • Properties (for nested fields):
              • Type: object where the field name is the key
              • fields: Recursive definition, accepts another array just like the fields above.
              • args: [optional] The field args
                • Type: [argName: string]: any or a detailed arg object
                  • Simple args: An object where the key is the argument name and its value. Accepts variables in the format of argName: '$value'
                    • Example: args { name: 'myName' }
                  • Detailed args: A tagged template. This will give more control over escaping (mostly to use enums). Argument name should be the key
                    • Type: tagged template
                    • Examples: args: { status: literal`an_enum` } should output operation (status: an_enum)...

Examples

Simple query

const query = {
  operation: {
    name: 'users',
    fields: ['name', 'age']
  }
}

Outputs:

query { users { name age } }

Named query

const query = {
  name: 'myQuery',
  operation: {
    name: 'users',
    fields: ['name', 'age']
  }
}

Outputs:

query myQuery { users { name age } }

Query with simple args

const query = {
  operation: {
    name: 'users',
    args: {
      name: 'Joe'
    },
    fields: ['name', 'age']
  }
}

Outputs:

query { users(name: "Joe") { name age } }

Query with variables

const query = {
  variables: {
    name: {
      type: 'string!',
      value: 'Joe'
    }
  },
  operation: {
    name: 'users',
    args: {
      name: '$name'
    },
    fields: ['name', 'age']
  }
}

Outputs:

query ($name: string!) { users(name: $name) { name age } }

Variables are sent on a separate object to graphQL.

{
  "variables": { "name": "Joe" }
}

Nested fields

const query = {
  operation: {
    name: 'users',
    fields: [
      'name',
      'age',
      {
        friends: {
          fields: ['name', 'age']
        }
      }
    ]
  }
}

Outputs:

query { users { name age friends { name age } } }

Recursive fields can go forever.

Enum and literal args

Enum or literal values should not be escaped, to do that, GotQL has a helper called literal which can be used to tell the query that value will not be escaped:

const { literal } = require('gotql')

const query = {
  operation: {
    name: 'users',
    args: {
      type: literal`internal`
    },
    fields: ['name', 'age']
  }
}

The code above outputs:

query { users(type: internal) { name age } }

The literal helper is just a shorthand to the old-style {value: string, escape: boolean} object like below:

const query = {
  operation: {
    name: 'users',
    args: {
      type: {
        value: 'internal',
        escape: false
      }
    },
    fields: ['name', 'age']
  }
}

If literal is omitted, or if escape is set to true, the output would be:

query { users(type: "internal") { name age } }

Note: Variables such as described here will not be recognized. If the arg object is not an [argName]: value, variables will not pass through the definition check (GotQL warns if a variable is not declared but used on operation).

Contributing to this project

Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms.

Hey! If you want to contribute, please read the contributing guidelines πŸ˜„

Contributors

Code Contributors

This project exists thanks to all the people who contribute. [Contribute].

Financial Contributors

Become a financial contributor and help us sustain our community. [Contribute]

Individuals

Organizations

Support this project with your organization. Your logo will show up here with a link to your website. [Contribute]

More Repositories

1

my-notes

πŸ“ Just a repo with my study notes. A simple notebook
JavaScript
282
star
2

zaqar

Email microservice writen in Node.js
HTML
70
star
3

event-sourcing-demo-app

Demo application to demonstrate the power of the event sourcing architecture for DevelopersBR livestream
TypeScript
54
star
4

typescript-blockchain

Simple blockchain implementation in TypeScript
TypeScript
50
star
5

promises-talk

Code sources for my promises talk
JavaScript
41
star
6

cdc-kubernetes-sources

RepositΓ³rio com os cΓ³digos fonte utilizados no meu livro sobre Kubernetes publicado pela @casadocodigo
JavaScript
40
star
7

devto-nodejs-sdk

The Node.js SDK for @thepracticaldev
TypeScript
37
star
8

template-node-ts

Template project for a TS application (raw)
Shell
33
star
9

secure-jwt-tokens

Simple repository to show how to store JWT tokens in a secure way
TypeScript
28
star
10

layered-typescript-bookstore

Demo API to show how to build layered applications using TypeScript
TypeScript
28
star
11

event-sourcing-javascript

A JavaScript event sourcing example from scratch
25
star
12

multer-firebase-storage

Multer Storage Engine for Firebase
TypeScript
23
star
13

enigmajs

Full implementation of the 1944 German cryptographic machine in TypeScript with a nice UI
Vue
23
star
14

khaosdoctor

19
star
15

node-ddsp-backend-template

TypeScript
16
star
16

article-cover-creator

Cover image generator for the articles in my blog
TypeScript
15
star
17

knoblr

πŸ“‹ Simple logging library for Node projects
JavaScript
12
star
18

software-testing-exercises

Exercises for my software testing workshop
JavaScript
10
star
19

dynamic-keyboard-poc

Repository to test different implementations of how a multi-number dynamic keyboard would work
10
star
20

dotfiles

My dotFiles
Shell
9
star
21

node-dht

A simple Distributed Hash Table made in NodeJS
JavaScript
9
star
22

PromiseFromScratch

TypeScript
8
star
23

helm-dynamic-envs

Code for the application I used on my "Dynamic testing environments using Helm and Kubernetes"
TypeScript
7
star
24

hermod

MQTT client for RabbitMQ
TypeScript
6
star
25

delay.css

βŒ› CSS Helpers to control CSS animation timming
JavaScript
6
star
26

nodejs-k8s-simple-api

Simple Node.js API to be published in Node.js
JavaScript
5
star
27

kubernetes-book-website

CSS
5
star
28

grpc-guide-part3-typescript-sample

Example repository for my "Guide to gRPC Series"
JavaScript
5
star
29

containerd-integration-example

Exemplo de integração com o containerd usando Go
Go
4
star
30

k8s-dynamic-env-backend

Dynamic envs with Kubernetes and GitHub Actions
TypeScript
4
star
31

sound-recommender

Simple API to recommend songs
TypeScript
4
star
32

presentations

All my talks and presentations
JavaScript
4
star
33

deno-opengraph

Fetches and parses data from website to get their OpenGraph metadata
TypeScript
4
star
34

auto-contrib

Gathers community contributions automatically and uploads to MVP and GDE websites
TypeScript
3
star
35

grpc-nodejs-demo-app

JavaScript
3
star
36

palestra-nodejs-crypto

Repository for my nodeJS crypto talk about best security practices using crypto module
JavaScript
3
star
37

deno-http-request

TypeScript
3
star
38

protots

Generate typescript interfaces from protobuf files
TypeScript
3
star
39

harperdb-migration-demo

Example app to show a migration process from MongoDB to HarperDB
TypeScript
3
star
40

palestra-containers-kubernetes

RepositΓ³rio da palestra sobre escalabilidade de containers usando Kubernetes
3
star
41

setup

πŸ’» My personal setup (this is a work in progress)
Shell
3
star
42

grpc-guide-part-4-sample

JavaScript
3
star
43

linkedeno

LinkedIn client integration for Deno
TypeScript
3
star
44

race-tracker

Race tracking problem
JavaScript
2
star
45

js-containerd-example

Codebase for my talk about integrating JS with containerd
JavaScript
2
star
46

bash-AMI

Bash script to remotely create AWS Machine Images
Shell
2
star
47

Codename

πŸ”– Parsing your semantic version numbers into awesome version names!
JavaScript
2
star
48

telegram-gh-bot

First telegram bot without frameworks for study
TypeScript
2
star
49

live-nodebr-graphql

Live da comunidade NodeBR sobre GraphQL do dia 11/04
JavaScript
2
star
50

nodejs-serverless-framework

Projeto de exemplo para meu curso sobre Serverless framework na Alura
HTML
2
star
51

aks-gh-actions-demo

Demo for my AKS + GH Actions talk (https://speakerdeck.com/khaosdoctor/aks-plus-github-actions)
2
star
52

string-to-objectid

Takes a string data, asserts it is a valid ID and returns its OID representation
TypeScript
2
star
53

example-technical-interview

An example of a possible technical interview for a backend engineer
TypeScript
2
star
54

web-workers-and-service-workers

Code Repository for my talk about Web Workers and Service Workers
HTML
2
star
55

go-vote-api

Go example voting API
Go
1
star
56

curso-performancenode

Curso presencial da Code Prestige - Performance com Node.js
JavaScript
1
star
57

codespace-kubernetes

Template repository for a Kubernetes GitHub Codespace
Shell
1
star
58

deno-talk-examples

TypeScript
1
star
59

ls-news

The landing page for my newsletter registration form
CSS
1
star
60

containerd-js

A JavaScript client to containerd
JavaScript
1
star
61

deno-tcp-server

TypeScript
1
star
62

apps40-scalingdemo-frontend

Improvement for Scott Coulton's learning path on APPS40 creating a GUI for the scaling demo
TypeScript
1
star
63

oauth-signature

OAuth1.0 base string generation
TypeScript
1
star
64

codename-greek-gods

Greek gods name parser for Codename
JavaScript
1
star
65

blog-assets

My personal blog (https://blog.lsantos.dev) post images and assets
1
star
66

helm-actions-dynamic-env-example

Example repository for my "Dynamic environments with helm and GH Actions" content
TypeScript
1
star
67

tag-o-matic

Instagram tag search
JavaScript
1
star
68

nodejs-ts-crud-api

Simple TypeScript CRUD API
TypeScript
1
star
69

zaqar-renderer-ejs

EJS renderer for Zaqar email microservice
JavaScript
1
star
70

reactor-stockholm-ts-api-workshop

TypeScript
1
star
71

electron-learn-project

Simple electron project to learn the framework
JavaScript
1
star
72

donorschoose-cli

Backend CLI for testing purposes
TypeScript
1
star
73

zaqar-renderer-mustache

Mustache renderer for Zaqar email microservice
JavaScript
1
star
74

grpc-guide-part2-javascript-sample

Example repository for my "Guide to gRPC" series
JavaScript
1
star
75

desafio-curso-performance

Desafio final para o curso de performance Node
HTML
1
star
76

openvolt-cli

Fetches electricity information from OpenVolt
TypeScript
1
star