npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

graphql-types-generator

v2.2.7

Published

Generates typescript types from raw graphql queries, based on server types and the most common naming of variables of certain types

Downloads

27

Readme

graphql-types-generator

An Alternative type generator for graphql client

Features:

A direct alternative to this package is only a combination of @graphql-codegen/typescript and @graphql-codegen/typescript-operations. So, if you want, you can consider it two in one.

But not only that. This package can do a little more little joys:

  • binding output and input graphql types - @graphql-codegen/typescript-operations is able to generate output types and incoming types based on graphql types. And it's actually very cool, but these remain for each separated case two independent types, and some more work needs to be done to link them. This work can be done manually or with the help of an additional script that you will have to write. graphql-types-generator does this work for you via one of two ways:

    • with the declarateSource option. Creates .d.ts file with generics directly linking arguments to types:
      export const someQueryVar: QueryString<OutputType, InputType>
    • using the matchTypeNames option, which creates a special type of relations.:
       export type ArgTypes = {
           // ...
           OutputType: InputType,      
       }
  • branded types for unknown types - in the case, when graphql server does not provide any data about type (codegen in this case simply substitutes any type for the fields (possible to changed via defaultScalarType option to another, like unknown or Object, for example, but no more)) graphql-types-generator generates appropriate human-readable branded types. A trifle, but nice.

    codegen:

     type SomeType = {
        errors?: any
     }

    graphql-types-generator

     type SomeType = {
        errors?: ExpectedErrorType
     }
  • generates types directly from javascript code - generates types directly from javascript code, which avoids code duplication, whereas codegen is designed for the * format.graphql files, for generating javascript code from which a separate package is needed.

  • generate types for unknown types - the possibility to define types, about which server dpusn't give any data. This is very rare case. Unlike the previous paragraphs, I do not attribute it to the advantages, rather to the specificity of the current package.

  • has possibility to specify more tiny type for types generation via specify naming rules or server type description (look up typeFromDescMark option). Its may be usefull for example for Unions of some fixed strings or numbers instead of base scalar types or using string template literal in the types. That maky possible use the types as generics for more typing covering

  • Performs generation faster then codegen/typescript-operations

  • supports watch mode - these mode soesn't supplied in codegen out of the box - you need install special package called @parcel/watcher. The graphql-types-generator in opposite supports the feature out of the box

Currently there is support:

  • ✅ queries result typing
  • ✅ mutation result typing
  • ✅ supports of nested interfaces (like relay)
  • ✅ queries and mutation arguments typing including:
    • ✅ nullable arguments
    • ✅ required arguments
    • ✅ complex arguments (required unique field names of each argument in once query)

Does not support:

  • subscriptions - may be will be done in the distant future
  • fragments - unlike due to the lack of need for such entities in meta-development, which is implied by this package

Frequently asked questions

Installation

npm i graphql-types-generator -D

Terminal usage:

types-gen -s "./examples/queries.js"

or

npm graphql-types-generator -s "./examples/queries.js"

Advanced possible options:

  • -t - target file name
  • -p - graphql server port
  • -h - graphql server host
  • --ds - generate *.d.ts file for source file with QueryString type declarations for each query
  • --m - attach 'QueryTypes' type listing all names of generated queries types with links to appropriate types
  • --w - watch mode

Programmatic usage:

// from forked repo:
const typesGenerate = require('./sources/main');
// or
const typesGenerate = require('graphql-types-generator');

async function main() {
   await typesGenerate({
      filename: './examples/mutations.js',
      // ...other options
   });	
}

main();

Possible options:

  • filename: string - path to js file with graphql queries wrapped to tagged template gql (possible to use glob pattern) (required)
  • files?: string[] - as alternative filename option allowing multiple source files passing at same time
  • declarateSource?: Array<string> - list of files for generating declaration (*.d.ts) files (may match with files option. useful for covering query argument types).
  • declTemplate?: string - file name of template using for *.d.ts files generation (look up examples directory)
  • target?: string - target file name
  • attachTypeName?: boolean - attach __typename field for each query type
  • matchTypeNames?: boolean - attach 'QueryTypes' type
  • useServerTypes?: boolean - using server types for generation
  • screentypes?: boolean - set human understandable type names for specific graphql types (JSONstring, Base64String and DateString by default)
  • rules?: object - naming rules to generate types like {number: ['count', 'amount']} (applies if the server type is not found or disabled)
  • overRules?: object - rules over server types (override server types!). For example: {cursor: 'Base64String'}
  • separateFileForArgumentsTypes?: boolean - separate argument types and queries result types
  • verbose?: boolean - includes additional logs output to the console
  • watch?: boolean | number - watch mode (number by default is the delay between flogging the file (by default is 250 ms))

How it works by rules?

legacy feature

By default (useServerTypes by default always is true) it expects server on http://127.0.0.1:8000/graphql and generates types based on types provided by this one. If some primitive type in not provided by server, it generates the type based on naming rule. If the server doesn't exists, it returns warning about an server unavailability and generates types purely based on naming rules. By default the rules look so:

rules = {
   string: ['Name', 'Title', 'Date', 'Time'],    // endsWith
   bool: ['is'],                                 // startsWith
   number: ['Id', 'Count', 'Sum']                // endsWith
}	

source:

export const GET_DIALOGS_INIT = gql`
   query profileInfo {
      users {
         username,
            firstName
      },
      dialogs{
         id,
         title
      }
   }
`;

results:

export type profileInfo = {
   users: Array<{
      username: string,
      firstName: string,
   }>,
   dialogs: Array<{
      id: number,
      title: string,
   }>,
};

usefull links:

  • npm repo of the graphql-types-generator
  • github repo of graphql-code-generator as alternative
  • documentation over programming usage of graphql-code-generator as alternative

PS:

  • use npm run generate for graphql types generation from backend. See more detail here.