<?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 Borre Mosch on Medium]]></title>
        <description><![CDATA[Stories by Borre Mosch on Medium]]></description>
        <link>https://medium.com/@borremosch?source=rss-f779fc98f55b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*V3My6rM7r9c7Aqb3.jpg</url>
            <title>Stories by Borre Mosch on Medium</title>
            <link>https://medium.com/@borremosch?source=rss-f779fc98f55b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 05:54:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@borremosch/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[Type safety in microservices using GraphQL and TypeScript]]></title>
            <link>https://medium.com/@borremosch/ensuring-type-safety-in-a-microservices-architecture-using-graphql-and-typescript-part-ii-type-381c7b8f4da9?source=rss-f779fc98f55b------2</link>
            <guid isPermaLink="false">https://medium.com/p/381c7b8f4da9</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Borre Mosch]]></dc:creator>
            <pubDate>Wed, 14 Aug 2019 13:57:40 GMT</pubDate>
            <atom:updated>2019-08-14T14:16:57.349Z</atom:updated>
            <content:encoded><![CDATA[<h3>Type safety in microservices using GraphQL and TypeScript part II: GraphQL schema combination</h3><p><em>This is part two in a two-part series of blog posts about type safety in a microservices architecture. In </em><a href="https://medium.com/@borremosch/ensuring-type-safety-in-a-microservices-architecture-using-graphql-and-typescript-part-i-type-d79c7fad63a0"><em>part I</em></a><em>, we have looked at a way to ensure type safety between the backend and frontend. In this part, we will generalize this approach to communication between any two (micro)services and discuss a novel, code-first approach to combining GraphQL schemas into a single endpoint.</em></p><p>In the previous part of this blog series, we have set up a frontend and backend that are able to communicate in a type-safe manner. To do this, we used two pieces of tooling:</p><ol><li><strong>TypeGraphQL</strong>, used to generate a GraphQL schema from TypeScript code + decorators</li><li><strong>graphql-codegen</strong>, used to generate code on the client from the GraphQL schema exposed on the server</li></ol><h3>Generalizing the approach</h3><p>The techniques used in <a href="https://medium.com/@borremosch/ensuring-type-safety-in-a-microservices-architecture-using-graphql-and-typescript-part-i-type-d79c7fad63a0">part I</a> are by no means specific to a frontend-backend relation. We will be able to set up any typesafe client-server relation in much the same way. Let’s consider the case in which we have our frontend clients, we have our Gateway API, and we have some other microservices. Also, we would like everything to communicate using GraphQL for type safety:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vIBOQWAApwlmCv3BCyP1nA.png" /><figcaption>Figure 1: Our GraphQL microservices setup</figcaption></figure><p>Now, let’s say that the shipping service has a query that will take a shipment tracking code, and return the status of a shipment (pending, in transit, delivered), the weight of the package, and any other relevant details. We would like to expose this functionality to the frontend. We could start out by writing a resolver in the shipping service, use TypeGraphQL to generate a GraphQL schema, and use graphql-codegen in the GraphQL API gateway to generate types from the GraphQL schema:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*quSuiONQSkVrPSPop-wiyw.png" /><figcaption>Figure 2: Connection between shipping service and API gateway</figcaption></figure><p>However, we now end up with non-decorated code in the GraphQL API gateway. There is no way for us to use the types from the shipping service and expose them to the frontend. To tackle this problem, Cubonacci has written <a href="https://www.npmjs.com/package/@graphql-codegen/typescript-type-graphql">a plugin for graphql-codegen to generate TypeGraphQL compatible types</a>. We can replace the @graphql-codegen/typescript package with @graphql-codegen/typescript-type-graphql, and that’s it. The types generated by graphql-codegen can now be directly fed into TypeGraphQL to generate the GraphQL API gateway schema, closing our code-schema generation cycle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l98ojEvNPbRRl21eOdfm7Q.png" /><figcaption>Figure 3: The code-schema generation cycle</figcaption></figure><h4>Combining schemas</h4><p>Now that all the puzzle pieces required to consume GraphQL endpoints and re-expose them in another service are available, we can combine the GraphQL schemas from multiple microservices into one schema that will be exposed by the gateway API. This comes with some clear benefits:</p><ul><li>All communication in the application is now type safe. Attempted calls to services that are incompatible are discovered during build time, saving development time and ultimately money.</li><li>The frontend can now talk to all pieces of the application if necessary.</li><li>The gateway API can be configured to expose any query, mutation or type from any of the microservices, but is agnostic to most of their implementation details.</li><li>This is a code-first solution, giving developers the benefit of using their existing knowledge instead of having to dig deep into the GraphQL SDL.</li></ul><h3>Alternatives​</h3><p>In this article we have described our solution to making a microservices architecture type safe and our method of combining schemas into one. We know of some alternative methods that do the same, and they are listed here together with the reasons why we chose not to go with these methods.</p><h4>Redefining types in gateway API​</h4><p>It is not necessary to immediately re-expose types consumed from downstream services in the Gateway API in an automated way. Our first attempt was actually to generate (undecorated) types from downstream services, and then redefining them in the Gateway API in a TypeGraphQL compatible way. You could even argue that this is safer because there is no way for the Gateway API to expose types and fields that it is not aware of.</p><p>However, this method led to a lot of code duplication. This code duplication led to a lot of confusion with our developers. Since confusion leads to bugs, we decided fairly quickly that we wanted to remove the duplication in our code and use graphql-codegen to generate TypeGraphQL compatible code.</p><h4>Apollo Schema Stitching</h4><p>One of the most well known methods of combining multiple GraphQL schemas into one is Apollo schema stitching. Apollo schema stitching has recently been succeeded by Apollo Federation, described below. Although obsolete, we list it here because it is a fairly well-known method of combining GraphQL schemas.</p><h4>Apollo Federation</h4><p>Apollo federation is the successor to Apollo Schema Stitching. It is a schema-first method of combining multiple schemas into one, which is the number one reason we chose not to use it. Apart from that, it has been very recently released for the first time and seems to be lacking some basic features as of yet, like hiding fields from the federated Gateway schema. This is a big deal, since microservices usually also communicate internally using non-public methods, and there is currently no way to prohibit the outside world access to these methods through federation.</p><p>Additionally, this is a Apollo-specific approach using GraphQL directives that will only be understood by Apollo GraphQL clients and servers. Even if other vendors would embrace Federation as a standard, and all missing features would be in place, we believe a schema-first approach will never be as powerful as a code-first approach, nor will it be as intuitive to developers.</p><h3>Next steps</h3><p>At <a href="https://cubonacci.com/">Cubonacci</a>, we are very happy with the type safe microservices architecture we have set up. Build time type checking on communication protocols is already saving us a tremendous amount of development time! However, for us the GraphQL journey does not end here.</p><p>In a proper microservices architecture, every single element in the architecture should be expected to fail at some point, and a good architecture should be able to handle failure gracefully. Synchronous communication between microservices like we are using now (GraphQL over HTTP) does not suit this requirement well enough. If a component of the microservice architecture fails, the synchronous connection breaks, and the client will receive an error message.</p><p>As an alternative, message brokers such as RabbitMQ or Kafka can be used. Any request to a microservices can be pushed onto a queue, and the microservice can take one item off the queue at a time and process it. If at some point the service crashes, it will restart, get the last unprocessed item from the queue and keep doing what it is doing. No client will receive an error message in this scenario, and we will have successfully handled the failure.</p><p>Because GraphQL does not make any specification with regards to the underlying network infrastructure, it should be possible to build a GraphQL infrastructure on top of a message broker, making communication more robust. In fact, some work has been done in this domain, such as a subscriptions library built on top of RabbitMQ. None of this work seems mature enough to use at the moment though, so we will be continuing our search towards better architecture. Once we have it figured out, we will be sure to write a blog post about it.</p><p>If you have any remarks, opinions, or questions following from this article, do not hesitate to get in touch!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=381c7b8f4da9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Type safety in microservices using GraphQL and TypeScript]]></title>
            <link>https://medium.com/@borremosch/ensuring-type-safety-in-a-microservices-architecture-using-graphql-and-typescript-part-i-type-d79c7fad63a0?source=rss-f779fc98f55b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d79c7fad63a0</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Borre Mosch]]></dc:creator>
            <pubDate>Wed, 14 Aug 2019 13:52:07 GMT</pubDate>
            <atom:updated>2019-08-14T14:16:04.209Z</atom:updated>
            <content:encoded><![CDATA[<h3>Type safety in microservices using GraphQL and TypeScript part I: backend and frontend</h3><p><em>This is part one in a two-part series of blog posts about type safety in a microservices architecture. In this part, we will look at a way to ensure type safety between the backend and frontend. In </em><a href="https://medium.com/@borremosch/ensuring-type-safety-in-a-microservices-architecture-using-graphql-and-typescript-part-ii-type-381c7b8f4da9"><em>part II</em></a><em>, we will generalize this approach to communication between any two (micro)services and discuss a novel, code-first approach to combining GraphQL schemas into a single endpoint.</em></p><p>Over the last couple of years, the GraphQL hype train has been steadily gaining speed, especially within the JavaScript ecosystem. So when the <a href="https://cubonacci.com/">Cubonacci</a> development team started out working on our new product, it was naturally decided that we should consider GraphQL as a method of communication in our microservices setup.</p><figure><img alt="Monthly GraphQL downloads on NPM" src="https://cdn-images-1.medium.com/max/1024/1*rxKzjIaxOH90jA2pW0r5bA.png" /><figcaption>Figure 1: Monthly GraphQL downloads on NPM</figcaption></figure><h3>The GraphQL API gateway</h3><p>The most common GraphQL use case today seems to be one where a GraphQL-based service is used as a gateway API. Frontend applications — such as web and mobile applications, and any other external clients — connect to the GraphQL API Gateway using the GraphQL protocol. The GraphQL API Gateway then communicates with all internal services using any protocol, most often a REST interface, RPC, or sometimes a message broker such as Kafka or RabbitMQ<a href="https://hackernoon.com/wiring-communication-between-microservices-5e51183462d6">[1]</a>.</p><p>Using GraphQL instead of a RESTful connection between frontend and backend has a number of nice benefits. This blog post will not go into detail on this, as some great articles have been dedicated to this topic already.<a href="https://blog.apollographql.com/graphql-vs-rest-5d425123e34b">[2]</a><a href="https://www.howtographql.com/basics/1-graphql-is-the-better-rest/">[3]</a><a href="https://medium.com/codingthesmartway-com-blog/rest-vs-graphql-418eac2e3083">[4]</a></p><figure><img alt="The GraphQL API Gateway" src="https://cdn-images-1.medium.com/max/1024/1*sRcR2yhmKmCZ_hX_6QUImA.png" /><figcaption>Figure 2: The GraphQL API Gateway</figcaption></figure><h3>Type safety between the backend code and the GraphQL schema​</h3><p>Because GraphQL aims to be compatible with any programming language, including typed languages, GraphQL itself is a typed query language. The types used in GraphQL are laid out in a GraphQL schema. The GraphQL schema has support for a limited set of scalar types — integers, floating-point numbers, strings, Booleans, and identifiers –, and can be extended with objects, enumerations, arrays, and a number of other constructs.</p><p>Synchronizing the (typed) GraphQL schema with our (typed) code can be done in one of two ways:</p><ol><li><strong>Code-first</strong>: The GraphQL schema can be generated from code</li><li><strong>Schema-first</strong>: The code can be generated from the GraphQL schema</li></ol><p>For our product we went with a code-first approach, as this allows us to keep writing in the language that we already know and love: TypeScript.</p><p>While schema-first approaches are wide-spread, we believe that the amount of new expertise that developers are required to learn before being able to properly build scalable architecture using GraphQL’s Schema Definition Language (SDL) is a big drawback. As will become apparent later in this post and in <a href="https://medium.com/@borremosch/ensuring-type-safety-in-a-microservices-architecture-using-graphql-and-typescript-part-ii-type-381c7b8f4da9">part II</a> of this series, we are using a novel approach to code-first GraphQL development. This new approach will enable us to gain some abilities previously only available to the schema-first paradigm.</p><h4>Code-first approach: generating the GraphQL schema from code​</h4><p>As it turns out, there exists an amazing initiative that allows one to generate a GraphQL schema from code in TypeScript named <a href="https://typegraphql.ml/">TypeGraphQL</a>. By adding decorators to our data types and GraphQL resolvers, the GraphQL schema can be automatically inferred. Let’s try this out in a very simple application. We will specify a single data type User, a resolver UserResolver, and an index.ts file that runs TypeGraphQL’s buildSchema command to generate a GraphQL schema:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea05c4462219c22f202cac79f42c37be/href">https://medium.com/media/ea05c4462219c22f202cac79f42c37be/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47c06a7be0bb7e60a544ae1f672ef49f/href">https://medium.com/media/47c06a7be0bb7e60a544ae1f672ef49f/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db175fcf0cf2d527c9ada42bc84758d0/href">https://medium.com/media/db175fcf0cf2d527c9ada42bc84758d0/href</a></iframe><p>When running our application, it will log the GraphQL schema that was created:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80c01fe1a8c683fcdf53edf82e707135/href">https://medium.com/media/80c01fe1a8c683fcdf53edf82e707135/href</a></iframe><h3>Establishing type safety between the GraphQL schema and the frontend​</h3><p>Great, so now we have generated a GraphQL schema from our server-side code. Generally, the GraphQL schema is exposed on the backend side by a GraphQL server such as express-graphql or Apollo Server. The schema is then consumed on the frontend side either using plain calls to the GraphQL API, or more sophisticatedly using a framework such as Apollo Client. This communication between backend and frontend is usually, but not necessarily, done over the HTTP protocol.</p><p>We cannot wait for the types to travel along on this journey, as we are using TypeScript, which requires build-time type information rather than runtime. Fortunately, another amazing effort exists to convert types exposed in a GraphQL schema back into TypeScript types and optionally functions, called <a href="https://graphql-code-generator.com/">GraphQL Codegen</a>.</p><h4>Generating TypeScript types from our GraphQL schema​</h4><p>Let’s assume that we have set up a server on localhost:4000 using the GraphQL schema we generated previously. We now want to generate types in the frontend that correspond to the schema exposed by the backend. First, we install the required dependencies into the frontend project:</p><pre>npm i graphql @graphql-codegen/cli @graphql-codegen/typescript</pre><p>Then, we create a configuration file named codegen.json specifying the types we want to generate in the frontend:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c1d0292fb5eb88135977a72549f3227/href">https://medium.com/media/7c1d0292fb5eb88135977a72549f3227/href</a></iframe><p>Finally, we call graphql-codegen to generate out types:</p><pre>./node_modules/.bin/graphql-codegen --config codegen.json</pre><p>And the types are automatically generated:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4053b3560d75317e4c417a0cb7f1ed58/href">https://medium.com/media/4053b3560d75317e4c417a0cb7f1ed58/href</a></iframe><h4>Doing more with graphql-codegen​</h4><p>GraphQL is a powerful tool, with a rich and ever expanding plugin ecosystem. Generating simple types like we did in the example above is only the start of it. For example, you can use it to automatically generate React HOCs (Higher Order Components) or hooks for pre-defined queries, making connecting to your backend a breeze. All of it type safe of course!</p><p>Another possibility of graphql-codegen is actually to write your backend schema in GraphQL SDL first and then generate resolvers for the schema (schema-first approach). However, like stated before, this is not our preferred approach. At some point in time, you might want to combine schemas exposed by several services into a single schema exposed by your gateway API. At this point, things become complex and the merit of the code-first approach will become more apparent.</p><h3>Recap​</h3><p>Up until now, we have created a backend service with decorated types to automatically generate a GraphQL schema. Next, we have used the schema in our frontend application to generate TypeScript types. The connection between our backend and frontend is now completely type safe, something which would have been very hard without the excellent tooling made available over the last year.</p><p>Keep in mind, every time you change any of the types in the backend, you will need to run codegen in your frontend to keep type annotations synchronized. Even better is to make this a task of your Continuous Integration (CI) server. Whenever a new build is done, the CI server should check whether running GraphQL codegen changes the frontend types. If so, they are out of sync and calls to the backend could fail. This situation should fail the CI build.</p><p>Another option to consider is adding a pre-commit hook to check whether types are synchronized between the services. This will save developers time compared to committing their code and then finding out their build fails because they forgot to run GraphQL codegen in their frontend.</p><h3>Next steps​</h3><p>At this point we have two services which we consider to be typesafe. Changing one in a way incompatible with the other should result in code that will not build. This is great, because that means we will find bugs earlier in the process.</p><p>Up next in <a href="https://medium.com/@borremosch/ensuring-type-safety-in-a-microservices-architecture-using-graphql-and-typescript-part-ii-type-381c7b8f4da9">part II</a> of this series, we will see how we can build on the technology we considered in this article to make all of our microservices typesafe, and how to combine GraphQL schemas into a single endpoint using our code-first approach.</p><p>If you have any remarks, opinions, or questions following from this article, do not hesitate to get in touch!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d79c7fad63a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>