0.0.2 • Published 5 years ago

ts-alias-transformer v0.0.2

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

ts-alias-transformer

TypeScript AST transformer to resolve type aliases into fully formed interfaces. This is not a published package as of yet, so it's pretty painful for others to consume until then. I will publish this soon... at least I think.

Usage

  • Clone repo
  • yarn install
  • npx ts-node src/index.ts ./path/to/you/model/definitions/models.ts
  • outdir hard coded right now
  • your types should now be fully resolved interfaces

Problem I'm trying to solve

I am using GraphQL at work and would like to add some type-safety around resolvers. Type safety in GQL is a bit weird to conceptualize, because resolvers are pretty dynamic by nature. Luckily I came across graphqlgen, which solved a lot of these problems I was having with its concept of models.

At work we run gRPC microservices, and GQL mostly serves as a nice fanout layer for our UI consumers. We already publish TypeScript interfaces that match our published proto contracts. I wanted to consume these types in graphqlgen, but ran into some issues due to type export support and with the way our TypeScript interfaces published (heavily namespaced, lots of references). Additionally, because graphqlgen is using babel-parser to do it's introspection and generation, it's quite limited as far as working with imported types (leads to parsing hell).

This repo is a mixture of me solving my narrow problem for work (and hopefully be extension graphqlgen), as well as demonstrating some of the power of the TypeScript compiler API. Utilizing the Checker API and a custom transformer, I was able to solve my problem without too much hassle.

Problem Visualized

// my_protos in node_modules
export namespace protos {
  export namespace user {
    export interface User {
      username: string;
      info: UserInfo;
    }
    
    export interface UserInfo {
      firstName: string;
      lastName: string;
    }
  }
  
  export namespace todo {
    export interface Todo {
      createdBy: protos.user.User;
      text: string;
    }
  }
}


// src/models.ts <-- models for graphqlgen (models returned from Query resolvers)
import { protos } from 'my_protos';

export type User = protos.user.User;
export type Todo = protos.todo.Todo;

// Run my program here pointing at src/models file

// generated/output.ts
export interface User {
  username: string;
  info: {
    firstName: string;
    lastName: string;
  }
}

export interface Todo {
  createdBy: {
    username: string;
    info: {
      firstName: string;
      lastName: string;
    }
  },
  text: string;
}