New GraphQL Client For TypeScript

Hi guys. I'm happy to introduce my open-source framework "https://github.com/babyfish-ct/graphql-ts-client", it's a new GraphQL client for TypeScript.

This framework is different from other similar GraphQL client frameworks because it can automatically infer the type of the returned data according to the strongly typed query request. 

Like this:

Is this GIF animation magical?

It is executed according to the following methods.

When the last request parameter is,

employee$.id

The http request is generated like this,

query {
    findDepartmentsLikeName(name: null) {
        id
    }
}

The type of each returned object can be inferred by the last request parameter, that type is,

{ readonly id: string; }

So "data[0]" contains one field: "id".

When the last parameter is,

employee$.id.name

The http request is generated like this,

query {
    findDepartmentsLikeName(name: null) {
        id
        name
    }
}

The type of each returned object can be inferred by the last request parameter, that type is,

{
    readonly id: string,
        readonly name: string
}

So "data[0]" contains two fields: "id" and "name".

When the last parameter is,

employee$.id.name.employees(employee$.id.firstName)

The http request is generated like this,

query {
    findDepartmentsLikeName(name: null) {
        id
        name
        employees {
            id
            firstName
        }
    }
}

The type of each returned object can be inferred by the last request parameter, that type is,

{
    readonly id: string,
        readonly name: string,
        readonly employees: ReadonlyArray < {
            readonly id: string,
            readonly firstName: string
        } >
}

So "data[0]" contains three fields: "id", "name" and "employees", and "data[0].employees[0]" contains two felds: "id" and "firstName".

The type of returned data changes with the change of the parameter type, which is called "Automatically infers the type of the returned data according to the strongly typed query request". This framework unifies the dynamics of graphql and the type safety of typescript.

The code generators of some other frameworks work in this way. They require developers to provide a special exhaustive list of all special query cases(for example, in that GIF animation, we have three special cases), and then generate TypeScript for these special cases one by one. This actually erase the dynamics of GraphQL, and will lead to a poor developer experience and high redundancy in the generated code.

This framework completely retains the dynamics of GraphQL and generates universal TypeScript code for GraphQL schema definitions. The type of returned data will be inferred automatically by the alibility of TypeScript itself until any special case of the query is executed.


Similar Articles