1.1.3 • Published 5 years ago

graphios-ts v1.1.3

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

Logo

GraphiosTs

npm version Build Status gzip size Coverage Status

GraphiosTs is TypeScript extension of Axios, which transforms Axios into typesafe GraphQl client. It combines the best from Axios and Typescript to provide a lightweight alternative to the Apollo-client. GraphiosTs uses one GraphQl schema source to provide strongly typed requests and responses. In other words: You will get, what you typed. Try interactive demo.;

Typings example

Motivation

In the real world of programming, most of APIs combine GraphQL and REST requests, so you need two separate clients. It puts complexity to handle two clients with similar settings and it is increasing bundle size. With GraphiosTs, you can share this logic with Axios via settings and interceptors. You have one client for both REST and GraphQl requests.

GraphiosTs translates GraphQl schema into GraphiosTs (TypeScript) schema. This schema is used for validation of GraphQL commands and compilation of result based on a command you write. Since GraphiosTs schema holds whole GraphQl logic of your endpoint, there is no need to run compilation every time, some GraphQl command has been changed in a script. With GraphiosTs-Cmd (downloads schema and translates it to GraphiosTs schema) you have only one source of truth... The server one. Every time GraphQl schema on the server will change, you can update GraphiosTs schema via command and Typescript will show you if something is wrong or incompatible.

This package does not try to compete with the Apollo ecosystem. Our main goal was to build simple, lightweight strongly typed graphql client, which can be used in APIs, where every byte of bundle size counts. If you want full-featured GraphQl client with tons of extensions and you don't care about size, take Apollo-client, which provides TypeScript definitions for results as well.

Features

Pitfalls

  • GraphiosTs is driven with TypeScript linter, which has its limitations and some features of GraphQl are difficult to define as typesafe. Currently GraphiosTs does not support Directives and Variables. But this can be resolved with pure JavaScript functions since the request is plain JSON object..
  • GraphiosTs does not support Subscriptions yet. We are planning to implement it in the near feature.

TypeScript

  • Inline Fragments are working properly, but when you use isFragment helper method, fake fragment definitions are still present. Those definitions are typesafe, so they never occur, but for readability of definition, you have to use getFragment helper method to get really typesafe definition.

Instalation

This package is TypeScript ONLY. Without TypeScript this package does not make much sense.

Package

Using NPM:

npm install --save graphios-ts

Interactive example

Basic request example. Swapi on Codesandbox;

Example

Performing simple request

import { GraphiosTs, isFragment , getFragment } from 'graphios-ts';
import { swapiSchema } from './swapi.graphQl';
import Axios from 'axios';


const gql = new GraphiosTs<swapiSchema>(Axios.create())
//Create new query
.create('query','OptionalName')
//GraphQl definition in GraphiosTs commands
.gql({
    //Name of query operation as a Field object
    'Film':{
        //It accepts arguments
        'args':{
            'id':'Foo',
            'title':'Bar'
        }
        //Payload is GraphQl Selection set.
        'payload':{
            //Scalars are defined by `true` value
            'id':true,
            //Field object without arguments
            'characters':{
                'payload':{
                    'id':true
                }
            },
            //Aliased value
            'alias':{
                '__type':'alias',
                'payload':{
                    'director':true
                }
            }
        }
    },
    'node':{
        'args':{
            'id':'Bar'
        },
        'payload':{
            'id':true,
            '__typename':true,
            //Fragment
            '__onFilm':{
                '__type':'fragment',
                'payload':{
                    'director':true
                }
            }
        }
    }
})
/**
 * GraphiosTs will translate it into this Gql:
 * query OptionalName{
 *      Film(id:"Foo",title:"Bar"){
 *          id,
 *          characters{
 *              id
 *          },
 *          MovieMaker:director
 *      },
 *      node(id:"Bar"){
 *          id,
 *          __typename,
 *          ...on Film{
 *              director
 *          }
 *      }
 * }
 */
.request().then((data)=>{
    //Type safe data response
    console.log(data.Film.characters[0].id);
    //Type safe alias
    console.log(data.Film.MovieMaker)
    //Fragments
    //Helper method for selecting fragment
    if(isFragment(data.node,'__onFilm')){
        //Helper method for Type safe fragment definition
        const film = getFragment(data.node);
        //Type safed object.
        console.log(film.director);
    }
});

More examples here

Schema

GraphiosTs uses GraphiosTs-Cmd package, which is command-line utility for conversion of serverside GraphQl schema to GraphiosTs schema. It keeps the source of truth on the server-side, so maintaining of GraphQl requests is significantly easier. Schema can be handwritten as well, but we discourage you from this approach, since maintaining of this schema is extremely difficult.Go to Schema description

GraphiosTs API

Creation of new GraphiosTs instance

import {GraphiosTs} from 'graphios-ts';
import Axios from 'axios';
import schemaDefinition from 'path to schema'
const gts = new GraphiosTs<schemaDefinition>(
    Axios.create(), //Any Axios instance.
    {...} // Optional settings. Description below
);

GraphiosTs settings

{
    /**
     * Axios settings. These settings will be merged with query settings and pased to the Axios. If axios has any default setting, this can override it.
     */
    axios:AxiosRequestConfig;
    /**
     * If server returns status >= 500, it will try again.
     * This specifies how many times should it try. If 0, it will not refetch at all.
     */
    refetch:number;
    /**
     * Pause in ms before another refetch.
     */
    refetchPause:number;
    /**
     * Content type header
     */
    contentType:'application/json' | string;
    /**
     * Batch queue object
     */
    queue?:GraphiosTsQueue;
}

GraphiosTs instance methods

/**
 * GraphiosTs instances is responsible for creation of Requests and handling responses. 
 */
//Creates new GraphiosTsRequest instance.
//See GraphiosTsRequest description below
const request = gts.create('query' | 'mutation');

GraphiosTsRequest

GraphiosTsRequest is request class instance created by GraphiosTs. It holds all logic to define GraphQl operation. Each instance can perform only one operation at a time (query or mutation).

GraphiosTsRequest Instance methods

//Gql command composer. Defines GraphQl command. Uses GraphiosTs payload composition.
request.gql(payloadDefinition);
//Returns GraphQl command as a string
request.parse();
//Sends data to a server. Can be sent only once. Then use refetch method instead
request.request(requestSettings);
//Sends same request again. Cannot be called before request method is called.
request.refetch();

GraphiosTsRequest request settings

{
    //Axios request config 
    axios?:AxiosRequestConfig;
    //If true, request will be added to batch queue and merged with other requests. It requires to have initialized Batch Queue
    batched?:boolean;
}
1.1.3

5 years ago

1.1.2

5 years ago

1.1.1

5 years ago

1.1.0

5 years ago

1.0.4

5 years ago

1.0.3

5 years ago

1.0.2

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago