<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Brett Jurgens on Medium]]></title>
        <description><![CDATA[Stories by Brett Jurgens on Medium]]></description>
        <link>https://medium.com/@brettjurgens?source=rss-b1f108c2bfa9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EzwFSIvW0w5vnFDT5TENCw.jpeg</url>
            <title>Stories by Brett Jurgens on Medium</title>
            <link>https://medium.com/@brettjurgens?source=rss-b1f108c2bfa9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 17:57:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@brettjurgens/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[GQL2TS 1.0.0 and Beyond]]></title>
            <link>https://medium.com/@brettjurgens/gql2ts-1-0-0-and-beyond-d812f95a1ec4?source=rss-b1f108c2bfa9------2</link>
            <guid isPermaLink="false">https://medium.com/p/d812f95a1ec4</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Brett Jurgens]]></dc:creator>
            <pubDate>Mon, 17 Apr 2017 18:31:01 GMT</pubDate>
            <atom:updated>2017-04-17T18:31:01.496Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><a href="https://github.com/avantcredit/gql2ts">gql2ts</a> is a tool that is used to generate TypeScript Interfaces from a GraphQL Schema.</blockquote><p>Last Friday, a massive <a href="https://github.com/avantcredit/gql2ts/pull/46">PR</a> was merged into gql2ts that makes it infinitely more extensible and useful.</p><p>All of the packages referenced below have been published on npm with the tag next. It will be published as latest after some more testing this week.</p><p>Here’s a synopsis of the changes:</p><h3>1. Using a Query to Generate Interfaces</h3><p>The initial goal of gql2ts was to give insight into responses from a GraphQL API. It was simple: take a schema, generate a namespace, gain more confidence. But, it was too general and included too much information. For instance, if the schema looked like:</p><pre>type Query {<br>  customer: Customer;<br>}</pre><pre>type Customer {<br>  id: ID!;<br>  name: String!;<br>  occupation: String;<br>}</pre><p>then the interfaces would look like:</p><pre>namespace GraphQL {<br>  interface IQuery {<br>    __typename: string;<br>    customer: ICustomer;<br>  }</pre><pre>  interface ICustomer {<br>    __typename: string;<br>    id: string;<br>    name: string;<br>    occupation: string | null;<br>  }<br>}</pre><p>But if the query looked like:</p><pre>{<br>  customer {<br>    id <br>  }<br>}</pre><p>Then the interface would have three extraneous fields (__typename, name, occupation) that were not actually present in the response.</p><p>Additionally, if the query had an alias, then the interfaces would be invalid, for instance:</p><pre>query CustomerWithJob {<br>  customer {<br>    id<br>    job: occupation<br>  }<br>}</pre><p>The interfaces are, once again, incorrect. occupation will still be on the ICustomer interface, but it should actually be job.</p><p>This use-case encompasses most of the perceived utility of the library and not having it covered was a sore spot. In v1.0.0 this will change. There is now an option to include a file with a query and have it generate the interfaces based on that. (The old use case is untouched, just don’t provide a query!)</p><p>So for the above query, the generated interface will look something like:</p><pre>interface CustomerWithJob {<br>  customer: SelectionOnCustomer;<br>}</pre><pre>interface SelectionOnCustomer {<br>  id: string;<br>  job: string;<br>}</pre><p>You may have noticed the SelectionOnCustomer interface, I’ll get to that next.</p><h4>Sub Selections as Separate Interfaces</h4><p>A problem with other tools that have a similar function is that they wind up generating code that looks like:</p><pre>interface Customer {<br>  employer: {<br>    name: string;<br>    employees: Array&lt;{<br>      id: string;<br>      name: string;<br>    }&gt;;<br>  }<br>}</pre><p>At some point it gets to be quite hard to read. Also, since there’s no good way to get a “subtype” from a TypeScript interface, it makes writing actual code a bit difficult. Consider the following code:</p><pre>const customer: Customer = getCustomer();<br>const formatEmployer = employer =&gt; { }<br>return formatEmployer(customer.employer)</pre><p>What type can you use for employer? You’ll either have to write your own interface that can become inconsistent with your query or use the any type.</p><p>This is why gql2ts will, by default, return an interface like:</p><pre>interface Customer {<br>  employer: SelectionOnEmployer;<br>}</pre><pre>interface SelectionOnEmployer {<br>  name: string;<br>  employees: Array&lt;SelectionOnEmployees&gt;;<br>}</pre><pre>interface SelectionOnEmployees {<br>  id: string;<br>  name: string;<br>}</pre><p>Now we can easily add type-checking to the previous code example:</p><pre>const customer: Customer = getCustomer();<br>const formatEmployer = (employer: SelectionOnEmployer) =&gt; { }<br>return formatEmployer(customer.employer);</pre><p>This also has a built-in caching mechanism, so duplicate names are not generated (e.g. two interfaces named SelectionOnCustomer). If the name has been used before and it is requesting different fields, a “high-tech counter” will append a sequential number to the end of the name. 😉</p><p>If, for some reason, the subtype feature is undesirable, it can be switched off by providing an alternate generateSubTypeInterfaceName function which returns null (or, if not type-checking, any falsey value).</p><h3>2. Programmatic Usage</h3><p>gql2ts was originally designed as a simple CLI. However, in v1.0.0 it provides first-class support for programmatic usage. Installing the packages @gql2ts/from-schema or @gqlts/from-query will give you access to the same functions that the CLI uses. This is extremely useful if you generate your type definitions as a part of a grunt/gulp/brunch/etc. task or a webpack loader. In fact, at <a href="https://www.avant.com/">Avant</a>, we use the @gql2ts/from-query package in this exact way. Our script reads query.graphql files and generates complimentary query.graphql.d.ts files with the type definitions.</p><h3>3. Ability to Override Default Formatters</h3><p>Not everyone’s code style is the same, so hardcoding default formatters can be harmful to other users. gql2ts now provides a way to pass overrides for defaults. You simply just need to make a file that provides these overrides and make a default export (or module.exports = { default: { ...overrides } }). Additionally these overrides can be published on npm and reused in other projects.</p><h3>4. Language Support</h3><p>gql2ts was obviously created to support TypeScript. However, TypeScript is not the only strongly-typed language that people use. Because default formatters can be overridden, this makes supporting different targets incredibly simple. For instance, <a href="https://github.com/avantcredit/gql2ts/tree/master/packages/language-flow">@gql2ts/language-flow</a> is an example of targeting <a href="https://flow.org/">flow</a> instead of TypeScript. Docs for developing new languages are forthcoming, but until then, the <a href="https://github.com/avantcredit/gql2ts/tree/master/packages/types">@gql2ts/types</a> package has the type that is expected from a language.</p><h3>5. Lerna</h3><p>gql2ts has made the move to using <a href="https://lernajs.io/">lerna</a> to manage its repo. This allows extremely easy development with the new modular components.</p><h3>6. Rewritten in TypeScript</h3><p>It’s kind of funny that a tool developed for TypeScript wasn’t written in it, but it started as a quick (100 or so line) hack. Naturally, Javascript was the language of choice.</p><h3>7. Drop Support for node 4/5</h3><p>In order to use Map/Set without additional polyfills, node 4/5 had to be dropped. Previous polyfills were also removed. Node 8 is set to be released this month, so 6/7/8 should be a reasonable requirement.</p><p>I’m quite excited about this release and the potential future that this more-extensible and featured version of gql2ts has. We’ve been using the alpha versions at <a href="https://www.avant.com/">Avant</a> and it has definitely improved the quality of our typings.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d812f95a1ec4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GraphQL + Typescript: Strongly Typed API Responses]]></title>
            <link>https://medium.com/@brettjurgens/graphql-typescript-strongly-typed-api-responses-f8aea1e81b93?source=rss-b1f108c2bfa9------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8aea1e81b93</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Brett Jurgens]]></dc:creator>
            <pubDate>Sat, 04 Jun 2016 20:21:22 GMT</pubDate>
            <atom:updated>2017-11-29T19:34:53.164Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>🎊 V1.0.0 has been released 🎊. Read <a href="https://medium.com/@brettjurgens/gql2ts-1-0-0-and-beyond-d812f95a1ec4">this post</a> to learn more.</blockquote><p>Over at Avant, I’ve been working on removing some of our internal tools from our existing monolithic Rails application and putting them into services.</p><p>In the early stages of the move, we decided on using GraphQL to power our communication between services. Although it was still relatively new (outside of Facebook, that is) we felt that it would speed up our development on our mostly frontend application.</p><p>Fast forward a few months and our service is now powered by GraphQL. Now, however, I am in the process of building an app using TypeScript that largely consumes this API.</p><p>After a while my client looked something like this:</p><pre>const GRAPHQL_URL: string = &#39;<a href="https://example&/#39;">https://example</a>&#39;;<br>const CONSUMER_QUERY: string = &#39;query { customer(id: 1) { id } }&#39;;</pre><pre>function client(query: string): Promise&lt;IResponse&gt; {<br>  return fetch(GRAPHQL_URL, { <br>    method: &#39;POST&#39;, <br>    body: JSON.stringify({ query }) <br>  });<br>}</pre><pre>async function consumer (): void {<br>  let response: any = await client(CONSUMER_QUERY);</pre><pre>  // =&gt; null<br>  console.log(response.data.customer.notARealField);</pre><pre>  // =&gt; Uncaught TypeError: Cannot read property ‘id’ of undefined<br>  console.log(response.data.customer.notARealField.id);<br>}</pre><p>Considering GraphQL and TypeScript are both Strongly Typed, I shouldn’t be having to use an any type. Nor did I want to write interfaces for every expected response.</p><p>I did some Googling and did not find any posts about this, so I decided to spend some time on it and fix it.</p><p>Because of its awesome introspection, GraphQL makes it simple to get the graph’s schema. The <a href="https://github.com/graphql/graphql-js">graphql-js</a> reference implementation includes an <a href="https://github.com/graphql/graphql-js/blob/master/src/utilities/introspectionQuery.js#L15-L106">Introspection Query</a> to get all relevant information from the graph.</p><p>Using this introspection query, we can arrive at a JSON response like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1dcabfebdaf5a37c447e39d5ab681ef0/href">https://medium.com/media/1dcabfebdaf5a37c447e39d5ab681ef0/href</a></iframe><p>Luckily, this response contains all of the relevant information we need to create interfaces for use in TypeScript.</p><p>So I wrote a utility named <a href="https://github.com/avantcredit/gql2ts">gql2ts</a> to convert this schema to TypeScript definitions. This is the output from the sample schema above:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eee5d6ac1288463e55e2e87c60555d2b/href">https://medium.com/media/eee5d6ac1288463e55e2e87c60555d2b/href</a></iframe><p>Awesome. Now we have some more type safety in our API responses.</p><pre>import GQL from &#39;gql&#39;;</pre><pre>const GRAPHQL_URL: string = &#39;<a href="https://example'/">https://example</a>&#39;;<br>const CONSUMER_QUERY: string = &#39;query { customer(id: 1) { id } }&#39;;</pre><pre>function client(query: string): Promise&lt;GQL.IGraphQLResponseRoot&gt; {<br>  return fetch(GRAPHQL_URL, { <br>    method: ‘POST’, <br>    body: JSON.stringify({ query }) <br>  });<br>}</pre><pre>async function consumer (): void {<br>  let response: GQL.IGraphQLResponseRoot = await client(CONSUMER_QUERY);</pre><pre>  // =&gt; works!<br>  let foo: string = response.data.customer.id;</pre><pre>  // =&gt; doesn&#39;t compile<br>  let bar: number = response.data.customer.id;</pre><pre>  // =&gt; doesn&#39;t compile<br>  console.log(response.data.customer.notARealField);</pre><pre>  // =&gt; doesn&#39;t compile<br>  console.log(response.data.customer.notARealField.id);<br>}</pre><p>Obviously this is an extremely contrived example, but I hope the utility can be seen.</p><p>If you’re interested, gql2ts can be installed via npm:</p><pre>$ npm install -g gql2ts</pre><p>It’s run very simply:</p><pre>$ gql2ts schema.json</pre><p>By default, this will output a file named graphqlInterfaces.d.ts with a module named GQL.</p><p>Optionally you can ignore certain types, use a custom module name, and write to a different file. For instance:</p><pre>$ gql2ts -m AwesomeModule -i Customer -o awesome.d.ts schema.json</pre><p>There’s still some more stuff to do, but I think this is a good starting point and hopefully will help some others.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8aea1e81b93" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>