<?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"><channel><title><![CDATA[Smith Gajjar Blog's]]></title><description><![CDATA[Full Stack Developer 🚀 and Designer 📟 with a penchant for minimalistic design and Web Technologies 🕸️. I am passionate about enhancing user experience and ma]]></description><link>https://blogs.smithgajjar.dev</link><generator>RSS for Node</generator><lastBuildDate>Wed, 20 May 2026 03:19:01 GMT</lastBuildDate><atom:link href="https://blogs.smithgajjar.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[GraphQL at scale using MongoDB Aggregation and GraphCDN]]></title><description><![CDATA[Almost one and half year ago, I wrote “Building GraphQL API with Nodejs, TypeGraphQL , Typegoose and Troubleshooting common challenges” which covers building a GraphQL API and facing most common challenges that may occur. The major challenge which I ...]]></description><link>https://blogs.smithgajjar.dev/graphql-at-scale-using-mongodb-aggregation-and-graphcdn</link><guid isPermaLink="true">https://blogs.smithgajjar.dev/graphql-at-scale-using-mongodb-aggregation-and-graphcdn</guid><category><![CDATA[GraphQL]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[scalability]]></category><category><![CDATA[MongoDB]]></category><category><![CDATA[Apollo GraphQL]]></category><dc:creator><![CDATA[Smith Gajjar]]></dc:creator><pubDate>Mon, 23 May 2022 18:31:15 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1653330539340/meeZ95bL1.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Almost one and half year ago, I wrote “<a target="_blank" href="https://blogs.smithgajjar.dev/building-graphql-api-with-nodejs-typegraphql-typegoose-and-troubleshooting-common-challenges">Building GraphQL API with Nodejs, TypeGraphQL , Typegoose and Troubleshooting common challenges</a>” which covers building a GraphQL API and facing most common challenges that may occur. The major challenge which I faced was N+1 problem, that was solved using <a target="_blank" href="https://github.com/graphql/dataloader">Dataloader</a>. A lot has changed since then! I have started working at <a target="_blank" href="https://www.tekie.in/">Tekie</a> as Full Stack Developer, this post covers everything we learned while building and scaling out our Backend.</p>
<h2 id="heading-refresher-what-is-graphql"><strong>Refresher: What is GraphQL</strong></h2>
<blockquote>
<p>GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.</p>
</blockquote>
<p>So GraphQL has two major components :</p>
<ul>
<li><strong>Schema :</strong> GraphQL server uses a schema to describe the shape of request / graphs. This schema basically defines a hierarchy of types with fields that are populated from back-end data stores.</li>
<li><strong>Resolvers :</strong> Server needs to know how to populate data for every field in your schema so that it can respond to requests for that data. To accomplish this, it uses resolvers. Resolvers can be of three types-<ul>
<li><strong>Queries</strong></li>
<li><strong>Mutations</strong></li>
<li><strong>Subscriptions</strong></li>
</ul>
</li>
</ul>
<p>To know more, please read this post “<a target="_blank" href="https://blogs.smithgajjar.dev/building-graphql-api-with-nodejs-typegraphql-typegoose-and-troubleshooting-common-challenges">Building GraphQL API with Nodejs, TypeGraphQL , Typegoose and Troubleshooting common challenges</a>”.</p>
<h2 id="heading-the-backstory"><strong>The backstory</strong></h2>
<p>A year ago, when I started working at Tekie. We were more focused into building and shipping our MVP (Minimum Viable Product), Both the User facing and Internal application. We had no issues with the current architecture i.e Nodejs and GraphQL. But as we kept growing and getting more and more users onboard we started to face some latency issues from our GraphQL API.</p>
<p><img src="https://c.tenor.com/MSPxlRhGkJQAAAAC/money-burn.gif" alt="money-burn" /></p>
<p>Adoption of new features were really <em>fast</em> and but as our mongoDB collection size started to grow and queries kept getting more complex, latency issues were a bigger problem now. We started to scale out by increasing our MongoDB clusters and autoscaling backend infrastructure based on kubernetes and AWS. And this is exactly what you don’t want to do and burn cash at blazingly fast pace.</p>
<h2 id="heading-the-usual"><strong>The usual…</strong></h2>
<p>Now we quickly turn our heads to optimizations from development And the first thing we explored was <a target="_blank" href="https://github.com/graphql/dataloader">Dataloader</a> as every GraphQL developer would do to reduce database trips.</p>
<p><img src="https://c.tenor.com/wJBEzOJrc28AAAAC/spongebob-magic.gif" alt="spongebob-magic" /></p>
<p>After a while we found out that the way in which our backend architecture was configured it was not possible to use dataloader. Every field which we requested where actually getting resolved before the result was returned i.e Using graphQL’s field.resolve we would resolve each and every field for every individual object that existed in an array. So this was always on the nextTick of nodejs and dataloader couldn’t batch and cache those requests.</p>
<h2 id="heading-the-sqaure-one"><strong>The sqaure one</strong></h2>
<p>Okay, After a lot of experimentation and reflection we started to test out few Queries with MongDB Aggregation. And the results are simply amazing, we had a reduction of almost 80% in our latency test.</p>
<p><img src="https://c.tenor.com/DdWKcmwa1fwAAAAC/wow-omg-meme.gif" alt="wow-omg-meme" /></p>
<p>We quickly jumped into integrating aggregation pipelines into our generic code so that every query can be optimized. As part of the plan we first decided to build a helper library to easily build aggregation pipelines but there already existed a similar library called <a target="_blank" href="https://www.npmjs.com/package/mongodb-pipeline-builder">mongodb-pipeline-builder</a> we quickly forked the project and started building our custom solutions on top of that already existing library and published a new version <a target="_blank" href="https://www.npmjs.com/package/mongodb-aggregation-builder">mongodb-aggregation-builder</a>.</p>
<h2 id="heading-the-showdown"><strong>The showdown…</strong></h2>
<p>As soon as we had the helper library in place, we started integrating the logic with the help of that library into our generic backend architecture. This was a major change to our architecture which can lead to production bugs. So we decided to create a custom directive called databaseController on Schema Type which would accept the mode of query.</p>
<pre><code class="lang-javascript">type Topic @model @databaseController(mode: <span class="hljs-string">"aggregation"</span>) {
        <span class="hljs-attr">order</span>: Int! 
    title: <span class="hljs-built_in">String</span>! @trim
    <span class="hljs-attr">description</span>: <span class="hljs-built_in">String</span> @trim
    <span class="hljs-attr">status</span>: ContentStatus! @defaultValue(value: <span class="hljs-string">"unpublished"</span>)
}
</code></pre>
<p>So now we were able to control which type would be allowed to query using aggregation pipeline. With this in place we were able to transform following query as seen below.</p>
<p>GraphQL Query: </p>
<pre><code class="lang-javascript">query {
    topics(filter: { <span class="hljs-attr">status</span>: published }, <span class="hljs-attr">order_by</span>: createdAt_DESC) {
        id
        title
        courses(filter: { <span class="hljs-attr">status</span>: published }, <span class="hljs-attr">first</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">order_by</span>: createdAt_DESC) {
            id
            title
        }
    }
}
</code></pre>
<p>Aggregation Pipelines :</p>
<pre><code class="lang-javascript">[
    { <span class="hljs-attr">$match</span> : { <span class="hljs-attr">status</span>: <span class="hljs-string">"published"</span> } },
    { <span class="hljs-attr">$sort</span>: { <span class="hljs-attr">createdAt</span>: <span class="hljs-number">-1</span> } },
    { <span class="hljs-attr">$limit</span>: <span class="hljs-number">1000</span> },
    { <span class="hljs-attr">$lookup</span>: {
      <span class="hljs-attr">from</span>: <span class="hljs-string">"Course"</span>,
      <span class="hljs-attr">let</span>: { <span class="hljs-attr">coursesId</span>: <span class="hljs-string">"$courses.typeId"</span> },
      <span class="hljs-attr">pipeline</span>: [
         { <span class="hljs-attr">$match</span>: { <span class="hljs-attr">$expr</span>: { <span class="hljs-attr">$in</span>: [<span class="hljs-string">"$id"</span>, <span class="hljs-string">"$$coursesId"</span> ] } } },
         { <span class="hljs-attr">$match</span>: { <span class="hljs-attr">status</span>: <span class="hljs-string">"published"</span> } },
         { <span class="hljs-attr">$sort</span>: { <span class="hljs-attr">createdAt</span>: <span class="hljs-number">-1</span> } },
         { <span class="hljs-attr">$limit</span>: <span class="hljs-number">1</span> },
         { <span class="hljs-attr">$projection</span>: { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">title</span>: <span class="hljs-number">1</span> } }
       ]
       <span class="hljs-attr">as</span>: <span class="hljs-string">"courses"</span>,
      } 
    }
    { <span class="hljs-attr">$projection</span>: { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">title</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">courses</span>: <span class="hljs-number">1</span> } }
]
</code></pre>
<p>As a result we were able to reduce the complex query latency by an average of 50% and the number of database calls was just fired once per query 🤯 🚀 compared to 60 - 70 database calls earlier. </p>
<h2 id="heading-the-more-the-merrier"><strong>The more the merrier…</strong></h2>
<p>With the Aggregation Implemented we placed our GraphQL endpoint behind the GraphCDN services. Now with the help of <a target="_blank" href="https://graphcdn.io/">GraphCDN</a> we were able to cache our static content at an edge location. Which resulted into fewer queries hitting our backend as only dynamic data would be required and static content was always served from cache.</p>
<h2 id="heading-whats-next"><strong>What's next</strong></h2>
<p>We were able to scale or optimize our GraphQL Backend latency and different issues. But there’s always few trade off we have to make. After a while we knew that lookup stage in aggregation pipeline are very costly operation if over used, so at that moment we just try to limit fetching relational fields. </p>
<p>But this continues to be a challenge for us. We now look forward to integrate Redis on Query Level with Aggregation Pipelines, architectural restructure to support Dataloader or Complex Filters inside Dataloader with Aggregation. </p>
<p><strong>The Possibilities Are Endless 🔥…</strong></p>
<p>Thanks for reading, stay awesome! ❤</p>
]]></content:encoded></item><item><title><![CDATA[Micro Frontends in a Nutshell]]></title><description><![CDATA[The term "Micro Frontends" is becoming more popular this days. As there are lot of discussions going on regarding its implementation, Whether we should or shouldn't adopt micro-frontends yet. Let's see what micro-frontends really are.
What are Micro-...]]></description><link>https://blogs.smithgajjar.dev/micro-frontends-in-a-nutshell</link><guid isPermaLink="true">https://blogs.smithgajjar.dev/micro-frontends-in-a-nutshell</guid><category><![CDATA[Microservices]]></category><category><![CDATA[frontend]]></category><category><![CDATA[Frontend frameworks]]></category><dc:creator><![CDATA[Smith Gajjar]]></dc:creator><pubDate>Tue, 19 Jan 2021 08:39:36 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1611044572153/IUGoXDpFt.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The term "Micro Frontends" is becoming more popular this days. As there are lot of discussions going on regarding its implementation, Whether we should or shouldn't adopt micro-frontends yet. Let's see what micro-frontends really are.</p>
<h1 id="heading-what-are-micro-frontends-anyway">What are Micro-frontends Anyway</h1>
<p>If you are a backend developer, you might be already familiar with micro-services architecture. But for the front-end developers, it's not that common yet.</p>
<blockquote>
<p>Micro-frontends are basically an architectural pattern in which a front-end codebase is decomposed into individual "microapps" consisting of different frameworks / libraries working loosely together, Obviously inspired by backend micro-services.</p>
</blockquote>
<p>We could have something like this :</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1611038644872/K57pLOPPC.png" alt="microfrontend.png" /></p>
<p>If you notice each microapps can be built with different frameworks or libraries and each microapps can be owned by a single team.</p>
<h1 id="heading-why-micro-frontends">Why Micro-frontends ?</h1>
<p>When I was first introduced with micro-frontends honestly it felt a bit off for me and so is to <a target="_blank" href="https://twitter.com/dan_abramov">@dan_abramov</a></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1611038701084/q9dFVePqf.png" alt="tweet.png" /></p>
<p>But as I started getting familiar with the concept, I realized there are multiple reasons for using micro-frontends. One of the biggest reason would be when migrating from old codebase to a new framework or library.</p>
<h2 id="heading-problems-with-traditional-monolithic-architecture">Problems with traditional monolithic architecture</h2>
<p>In early stages of an application it might not be a big problem, But when application grows, the number of teams increases then it becomes a real challenge . When project is massive it becomes difficult to work with multiple people/teams. Unnecessary codebase being available due to which build time is increased. When using same micro-service API it is difficult to make changes when API responses are refactored.  </p>
<h2 id="heading-micro-frontends-to-the-rescue">Micro-frontends to the rescue</h2>
<p>Adopting micro-frontend approach we could solve some of those problems like assigning individual team with core modules. As unnecessary codebase is removed it is easy to deploy and build time also decreases. individual microapps can be developed, tested, and deployed independently, separate modules can be inserted , removed, or replaced without any refactors, different modules of the frontend can be created using different frameworks or libraries. As organization requirements changes we can easily replace old modules with new ones. So we will continuously evolve our codebases.</p>
<p>Some of the big companies are already using it, to name few Spotify, Klarna, Zalando, Upwork, AirBnB, and Facebook. </p>
<h1 id="heading-different-approaches-towards-micro-frontends">Different approaches towards micro-frontends</h1>
<p>Well while adopting micro-frontend architecture we have few approaches which can be used : </p>
<ul>
<li><p>Using a framework</p>
<p>  We can use <a target="_blank" href="https://single-spa.js.org/">Single-SPA</a> which lets you combine multiple Frameworks or libraries in a single page.</p>
</li>
<li><p>Using Web Components</p>
<p>  Web components can be hosted on different servers with different frameworks or libraries. <strong>Chris Kitson</strong> has discussed it in depth here : <a target="_blank" href="https://medium.com/javascript-in-plain-english/create-micro-frontends-using-web-components-with-support-for-angular-and-react-2d6db18f557a">Creating Micro-frontends using Web Components (with support for Angular and React)</a></p>
</li>
<li><p>Using a separate micro-service for each micro-frontend modules, which can be very beneficial when API changes.</p>
</li>
</ul>
<h1 id="heading-challenges-in-micro-frontends">Challenges in micro-frontends</h1>
<p>As it comes with many advantages it also have some disadvantages too, while application grows we would be left with tons of codebases to maintain and to maintain the same best practices among all the microapps. It would be very hard to run tests on the the entire codebase locally. While different microapps are hosted on different servers there might be some performance issue which costs user experience. Inter microapps communication can be very difficult and complex to work on.</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>So basically, micro frontends are all about splitting up big modules into smaller chunks i.e. more manageable modules, and then being explicit about the dependencies between them. According to me Micro-frontend are the future we are heading into but there's still a long way to go. It certainly depends upon the organization requirements and how big the development team is. I hope you have enjoyed this article and got a sense of what micro-frontends really are and different approaches to it. </p>
<p>Thanks for reading, stay awesome! ❤</p>
<p>Feel free to follow me on <a target="_blank" href="https://www.linkedin.com/in/smith-gajjar-5a27716b/">LinkedIn</a>. Do check my website @ <a target="_blank" href="https://smithgajjar.dev">smithgajjar.dev</a></p>
]]></content:encoded></item><item><title><![CDATA[Building GraphQL API with Nodejs, TypeGraphQL , Typegoose and Troubleshooting common challenges.]]></title><description><![CDATA[I recently started out with this project where I am using Apollo GraphQL with TypeGraphQL , typegoose as mongoose wrapper and Express.js to create an API. I have been searching for different articles on using TypeGraphQL with Typegoose but seems that...]]></description><link>https://blogs.smithgajjar.dev/building-graphql-api-with-nodejs-typegraphql-typegoose-and-troubleshooting-common-challenges</link><guid isPermaLink="true">https://blogs.smithgajjar.dev/building-graphql-api-with-nodejs-typegraphql-typegoose-and-troubleshooting-common-challenges</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[GraphQL]]></category><category><![CDATA[Apollo GraphQL]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[MongoDB]]></category><dc:creator><![CDATA[Smith Gajjar]]></dc:creator><pubDate>Sun, 27 Dec 2020 17:12:18 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1609088911671/wJncjh4wO.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I recently started out with this project where I am using Apollo GraphQL with <a target="_blank" href="https://typegraphql.com/">TypeGraphQL</a> , <a target="_blank" href="https://typegoose.github.io/typegoose/">typegoose</a> as mongoose wrapper and Express.js to create an API. I have been searching for different articles on using TypeGraphQL with Typegoose but seems that no has used it before 🤷‍♂️ also individually their   documentation are top notch , but when trying to use them together I encountered a lot of bugs and challenges.</p>
<p>So It’s probably worth posting out this article so that it could be an help for other developers and to briefly explain some of the codes and concepts around GraphQL.</p>
<p>I have created an boilerplate GraphQL API with <a target="_blank" href="https://nodejs.org/en/">Node.js</a>, <a target="_blank" href="https://www.apollographql.com/">Apollo</a>, <a target="_blank" href="https://typegraphql.com/">TypeGraphQL</a> , <a target="_blank" href="https://www.typescriptlang.org/">TypeScript</a> , <a target="_blank" href="https://nx.dev">Nx</a>, 
<a target="_blank" href="https://www.mongodb.com/">MongoDB</a> , <a target="_blank" href="https://typegoose.github.io/typegoose/">typegoose</a>. You may want to check that out, here's the repository <a target="_blank" href="https://github.com/DevUnderflow/nx-node-apollo-grahql-mongo">github.com/DevUnderflow/nx-node-apollo-grahql-mongo</a></p>
<h3 id="heading-what-is-graphql">What is GraphQL?</h3>
<blockquote>
<p>GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.</p>
</blockquote>
<p>Basically it is new API standard that enables a better way of implementing API's and a great alternative to REST. In REST we need maintain a bunch API endpoints, While in GraphQL there is just a single API endpoint created.</p>
<p>So GraphQL has two major components :</p>
<ul>
<li><p><strong>Schema :</strong>
GraphQL server uses a schema to describe the shape of request / graphs. This schema basically defines a hierarchy of types with fields that are populated from back-end data stores.</p>
<pre><code class="lang-javascript">type User {
   <span class="hljs-attr">username</span>: <span class="hljs-built_in">String</span>
   <span class="hljs-attr">email</span>: <span class="hljs-built_in">String</span> 
}
</code></pre>
</li>
<li><p><strong>Resolvers :</strong>
Server needs to know how to populate data for every field in your schema so that it can respond to requests for that data. To accomplish this, it uses resolvers. Resolvers can be of three types-</p>
<ul>
<li><p><strong>Queries</strong></p>
<pre><code>{
  <span class="hljs-keyword">user</span> {
      username
      email
  }
}
</code></pre></li>
<li><p><strong>Mutations</strong></p>
<pre><code><span class="hljs-selector-tag">mutation</span> {
 <span class="hljs-selector-tag">createUser</span>(<span class="hljs-attribute">username</span>: <span class="hljs-string">"test"</span>, <span class="hljs-attribute">email</span>: <span class="hljs-string">"test@test.com"</span>) {
     <span class="hljs-selector-tag">username</span>
     <span class="hljs-selector-tag">email</span>
 } 
}
</code></pre></li>
<li><strong>Subscriptions</strong><pre><code><span class="hljs-section">subscription</span> {
  <span class="hljs-attribute">users</span>
}
</code></pre></li>
</ul>
</li>
</ul>
<h3 id="heading-why-choose-graphql-over-rest">Why choose GraphQL over REST</h3>
<h4 id="heading-challenges-with-rest">Challenges with REST</h4>
<p>We have been using REST API's for a long time now. But there exists some problems with REST like fetching data from REST API comes with lot of unnecessary data being fetched. Also there is a need to remember a lot of API endpoints. 
With GraphQL we describe in the client which data we want to have instead of just asking all the data.</p>
<h4 id="heading-graphql-solves-the-issue">GraphQL Solves the issue</h4>
<p>In the backend, we need to define our data types which will form our schemas. and the resolvers to resolve the request coming frontend. In GraphQL we only need to maintain a single endpoint where we would request only those data that we need on the frontend. </p>
<p>GraphQL basically reduces the network call by enabling us to fetch all the data that we need in a single query from a single endpoint. GraphQL also comes with a set of challenges which we would discuss later in this article.</p>
<h3 id="heading-using-apollo-with-typegraphql">Using Apollo with TypeGraphQL</h3>
<p>While the most used library for GraphQL is <a target="_blank" href="https://www.apollographql.com/">Apollo</a>. Apollo Server comes with a lot of features like caching , external data loader and many more.
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1609084744472/edTpe0nhw.png" alt="Screenshot 2020-12-27 212843.png" />
The Apollo Client is a tool which helps you use GraphQL in the frontend. It provides different features like in-memory caching, state management etc. It can be integrated  with multiple JavaScript frameworks like React, React Native, Vue, Angular and for iOS and Android, there are also possibilities to use the Apollo Client.</p>
<h4 id="heading-typegraphql">TypeGraphQL</h4>
<p><a target="_blank" href="https://typegraphql.com/">TypeGraphQL</a> is modern framework for creating GraphQL API's. While apollo is really great and solves many problems that we have. But developing a GraphQL API in Node.js with TypeScript is sometimes a bit of a pain. This makes it easy to use with typescript as your first language.</p>
<p>Creating a sample resolver would look like :</p>
<pre><code><span class="hljs-meta">@Resolver()</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserResolver</span> </span>{
  <span class="hljs-keyword">private</span> userCollection: User[] = [];

  async users() {
    <span class="hljs-keyword">return</span> await <span class="hljs-keyword">this</span>.userCollection;
  }
}
</code></pre><h3 id="heading-using-typegraphql-with-typegoose">Using TypeGraphql with Typegoose</h3>
<p>Well <a target="_blank" href="https://typegoose.github.io/typegoose/">Typegoose</a> is basically a TypeScript wrapper around mongoose. It is easy to use in typescript environment and provides a lot features. </p>
<p>The first challenge I encountered while Integrating typegoose with typegraphql is that I had to define multiple interfaces one for typegoose, then one for typegraphql schema, So there was lot of redundancy happing around. So the solution I found was just to use typgraphql decorators on top of typegoose methods.</p>
<pre><code><span class="hljs-variable">@ObjectType</span>()
export class User {
  <span class="hljs-variable">@Field</span>()
  readonly <span class="hljs-attribute">_id</span>: string;

  <span class="hljs-variable">@Field</span>()
  <span class="hljs-variable">@prop</span>()
  public <span class="hljs-attribute">username</span>: string;

  <span class="hljs-variable">@Field</span>()
  <span class="hljs-variable">@IsEmail</span>()
  <span class="hljs-variable">@prop</span>()
  public <span class="hljs-attribute">email</span>: string;
}
</code></pre><p>So here we define our mongoDB models with prop() decorator from typegoose and along with we simultaneously define our GraphQL schemas with ObjectType() and Field() decorators form typegraphql. It basically removes all the redundant interfaces we had earlier.</p>
<p>The second challenge I encountered is that during the initial phase I was writing all my core logic directly into resolver methods which eventually created lot of problems in maintaining the codebase 
So the solution was that I started refactoring all my codebase into different folder structure. I started using typescript decorator features for services and used dependency Injector to inject all my Database models and Services directly into Resolvers.</p>
<pre><code><span class="hljs-keyword">import</span> { Service, Inject } <span class="hljs-keyword">from</span> <span class="hljs-string">"typedi"</span>;
<span class="hljs-meta">@Service</span>()
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> UserService {
  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-meta">@Inject</span>(<span class="hljs-string">"userModel"</span>) <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> UserModel</span>) {}
  <span class="hljs-keyword">async</span> getAll() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.UserModel.find();
  }
}
</code></pre><p>So here we are creating UserService which injects userModel. now once we have our service running we can inject this directly into our Resolvers as : </p>
<pre><code><span class="hljs-variable">@Resolver</span>()
export class UserResolver {
  <span class="hljs-selector-tag">constructor</span>(
    private readonly <span class="hljs-attribute">userService</span>: UserService,
  ) { }
  <span class="hljs-variable">@Query</span>(() =&gt; [User])
  async users() {
    <span class="hljs-selector-tag">return</span> <span class="hljs-selector-tag">this</span><span class="hljs-selector-class">.userService</span><span class="hljs-selector-class">.getAll</span>();
  }
}
</code></pre><h3 id="heading-most-common-challenge-youll-face">Most Common Challenge you'll face</h3>
<p>When using GraphQL we have a lot advantages but it comes with its own set of challenges or cons you would say. The most common problem you would face is that server making a lot of multiple request to the database then expected. Suppose you have a list of posts, in which each of post has a user document to it. Now you may want to fetch all of these posts, with user data. When using REST this would be like having two database calls. One for posts and one for users corresponding to these posts.</p>
<p>But what in GraphQL? we now have an extra call to fetch each user data per resolver that is per. Now let's say we have 10 posts and each post also has 5 comments, each of which has an user document. So the number of calls we'll have is one for the list of posts, 10 for the post authors, 10 for each sub-list of 5 comments and 50 for the comment users which sums up to around 71 database calls to fetch a set of data!</p>
<p>Nobody would want this to happen, waiting 15 secs to load a set of posts. To solve this problem we have Dataloader library.</p>
<p>Dataloader basically lets will let you combine or batch multiple similar requests and cache database calls. Now the dataloader detects that posts having similar id's and batch them together and will reuse the user document which it already has in memory instead of making a new database call.</p>
<p>So These were the challenges I have came across till now while building a GraphQL based API.  </p>
<p>The source code for the Nx-Node-Apollo Graphql API is here <a target="_blank" href="https://github.com/DevUnderflow/nx-node-apollo-grahql-mongo">github.com/DevUnderflow/nx-node-apollo-grahql-mongo</a></p>
<h3 id="heading-thanks-for-reading-stay-awesome">Thanks for reading, stay awesome! ❤</h3>
<p>I hope you have enjoyed this article and you may avoid above problems beforehand , I also hope that if it gave you some sort of inspiration for your work.</p>
<p>If you may want to checkout other articles its right here <a target="_blank" href="https://blogs.smithgajjar.dev/">blogs.smithgajjar.dev</a>. Feel free to follow me on <a target="_blank" href="https://www.linkedin.com/in/smith-gajjar-5a27716b/">LinkedIn</a>.</p>
<p>Do checkout my website at <a target="_blank" href="https://smithgajjar.dev">smithgajjar.dev</a>.</p>
<div class="hn-embed-widget" id="buymeacoffee"></div>]]></content:encoded></item><item><title><![CDATA[Why I love TypeScript 💕]]></title><description><![CDATA[It's been 2 years now I started writing JavaScript applications and JavaScript became my go-to language. So, a year ago I got an internship opportunity at an amazing startup called InVideo. I was told to learn Angular which led me to Typescript. An o...]]></description><link>https://blogs.smithgajjar.dev/why-i-love-typescript</link><guid isPermaLink="true">https://blogs.smithgajjar.dev/why-i-love-typescript</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[api]]></category><dc:creator><![CDATA[Smith Gajjar]]></dc:creator><pubDate>Sat, 21 Nov 2020 06:14:51 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1605939235384/tBfGht2g3.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>It's been 2 years now I started writing JavaScript applications and JavaScript became my go-to language. So, a year ago I got an internship opportunity at an amazing startup called <a target="_blank" href="https://invideo.io/">InVideo</a>. I was told to learn Angular which led me to Typescript. An open source language backed by Microsoft. To be honest it was not easy to learn angular and typescript but eventually ended up liking it even more. Now a year later I have been using a lot of TypeScript, be it in small or large projects, react or NodeJS everywhere.</p>
<p>Let's focus on why this is my default go-to language and why I prefer to write code using TypeScript rather than JavaScript.</p>
<h3 id="heading-typescript-javascript-with-superpowers"><strong>TypeScript - JavaScript With Superpowers</strong></h3>
<p>Believe it or not but typescript has saved me a lot of time by catching errors and providing fixes before actually running the code.</p>
<p>Let's see how </p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/yqs0wf1qg4jnhkz4plkg.PNG" alt="Alt Text" /></p>
<p>Did you see that little red underline? That’s what TypeScript giving us a hint that something has gone wrong while writing code.
You may have already figured out what's wrong here. Number has been given to user method instead of a string. </p>
<p>That’s the reason why I love TypeScript ❤.</p>
<p>Moving on, there's lot more to typescript than just type checking. Most important features I use every day is Decorators and interfaces</p>
<p><strong>Decorators</strong></p>
<p>Decorators are special kind of declaration or method that can be attached to a class, method, property, or any parameter. Decorators use the @decorator_name, where decorator_name must evaluate to a method that will be called at runtime with information about the decorated declaration.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/malb3e064mzoy7jkttox.PNG" alt="Alt Text" /></p>
<p><strong>Interfaces</strong></p>
<p>Providing a type shape to JavaScript objects.Interfaces are the powerful way of defining contracts within your code as well as contracts with code outside of your project.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/jlw72gkww4m2bjh5o0by.PNG" alt="Alt Text" /></p>
<p>Typescript works great with VS Code. Anyways official Typescript <a target="_blank" href="https://www.typescriptlang.org/docs/handbook/intro.html">docs</a> is a great way to learn language in detail.  </p>
<h3 id="heading-how-to-get-started-with-typescript"><strong>How To Get Started With Typescript</strong></h3>
<p>It is available as a package on the npm registry available as "typescript".</p>
<p>Node.js environment is must to run the package. Then dependency manager like npm, yarn can be used to download TypeScript into your project.</p>
<pre><code><span class="hljs-built_in">npm</span> install -g typescript
</code></pre><p>You can then run the TypeScript compiler using one of the following commands:</p>
<pre><code><span class="hljs-attribute">npx</span> tsc
</code></pre><p>Now we initialize a new typescript project using </p>
<pre><code>tsc <span class="hljs-operator">-</span><span class="hljs-operator">-</span>init
</code></pre><p>You should end up with the TypeScript config.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/x98hud8warbke5gbal7u.PNG" alt="Alt Text" /></p>
<p>Now all you need is to create a <code>.ts</code> file and start writing code in typescript. Once you are done you can compile <code>.ts</code> file into <code>.js</code> using following command</p>
<pre><code><span class="hljs-selector-tag">tsc</span> <span class="hljs-selector-tag">filename</span><span class="hljs-selector-class">.ts</span>
</code></pre><p>Great 🎉 Now you can start building something awesome with Typescript.</p>
<p>If you have already been using it and wants to start using typescript in your NodeJS application I have a Nodejs / Typescript starter project built using Nx workspace and express server includes MongoDB and jest testing framework. If you like the project leave a star🌟</p>
<blockquote>
<p><a target="_blank" href="https://github.com/DevUnderflow/nx-node-typescript-api">Github Repository : nx-node-typescript-api</a></p>
</blockquote>
<h3 id="heading-to-conclude"><strong>To conclude</strong></h3>
<p>That's why I love TypeScript. Basically, Typescript allows you to write better, cleaner, productive and more maintainable code. Obviously, you don’t have to go all out for TypeScript directly and start using decorators, interfaces or classes. Initially I have used TypeScript only with type checking on small projects. and gradually you can start adding more and more features.</p>
<p>I hope this post helps you decide if you should give it a try, and I strongly encourage you to start using it.</p>
<p>Thanks for reading, stay awesome! ❤</p>
<p><strong>Do check my website <a target="_blank" href="https://smithgajjar.dev">smithgajjar.dev</a></strong>
<strong>Follow me on <a target="_blank" href="https://www.linkedin.com/in/smith-gajjar-5a27716b/">LinkedIn</a></strong></p>
<div class="hn-embed-widget" id="buymeacoffee"></div>]]></content:encoded></item><item><title><![CDATA[Is Deno the new Node?🦕]]></title><description><![CDATA[So In 2018, Ryan Dahl  (the creator of Node.js) issued “10 Things I Regret About Node.js” in JSConf , He goes on including     several regrets about design he took over Node.js in 2009. Almost half of his talk, he showed us an experimental prototype ...]]></description><link>https://blogs.smithgajjar.dev/is-deno-the-new-node</link><guid isPermaLink="true">https://blogs.smithgajjar.dev/is-deno-the-new-node</guid><category><![CDATA[Deno]]></category><category><![CDATA[node]]></category><category><![CDATA[TypeScript]]></category><dc:creator><![CDATA[Smith Gajjar]]></dc:creator><pubDate>Tue, 19 May 2020 17:41:28 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1606066963522/5YsYsaAQt.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>So In 2018, <a target="_blank" href="https://en.wikipedia.org/wiki/Ryan_Dahl">Ryan Dahl</a>  (the creator of Node.js) issued “<a target="_blank" href="https://www.youtube.com/watch?v=M3BM9TB-8yA">10 Things I Regret About Node.js</a>” in JSConf , He goes on including     several regrets about design he took over Node.js in 2009. Almost half of his talk, he showed us an experimental prototype called Deno successor of Nodejs which aimed to fix previous problems.</p>
<p>Deno  <a target="_blank" href="https://github.com/denoland/deno/releases">v1.0</a> has launched and I think that it may be on the right track to replace Node.js in the future.</p>
<h1 id="heading-deno"><strong>Deno</strong></h1>
<p><strong>Deno</strong> is a secure runtime for JavaScript and TypeScript. Imagine if you could write TypeScript without any config files, and bundle it all together into a single ES Module where both the TypeScript support and bundler are present in the core. That’s what it feels like when you get started with <strong>Deno</strong>.</p>
<p>It’s a modern and secure runtime for JavaScript and TypeScript that uses V8 and is built in Rust. Whereas Node.js is written in C++ and JavaScript.</p>
<p><strong>Fun fact</strong>: Deno is an anagram of Node. If you sort()  <code>node</code>  it becomes  <code>deno</code>🦕.</p>
<p>Deno ships with many features required for writing modern JavaScript &amp; TypeScript, and WebAssembly code.</p>
<ul>
<li>📦 bundler</li>
<li>🐛 debugger</li>
<li>🤖 test runner</li>
<li>🧶 code formatter</li>
<li>📖 docs generator</li>
<li>🧵 WebAssembly support</li>
</ul>
<h4 id="heading-deno-has-some-interesting-features">Deno has some interesting features</h4>
<ul>
<li><strong>Secure by default.</strong><br />No file, network, or environment access, unless explicitly enabled.</li>
<li><strong>Single Executable.</strong><br />Ships only a single executable file.</li>
<li><strong>TypeScript Support</strong>
Deno ships with out of the box TypeScript compiler.</li>
<li><strong>Module system</strong>
 No  <code>package.json</code>, no  <code>node_modules</code>. Source files can be imported using a relative path, an absolute path or a fully qualified URL of a source file:<pre><code class="lang-sh">import { <span class="hljs-built_in">test</span> } from <span class="hljs-string">"https://unpkg.com/deno_testing@0.0.5/testing.ts"</span>  
import { <span class="hljs-built_in">log</span> } from <span class="hljs-string">"./util.ts"</span>
</code></pre>
</li>
</ul>
<h4 id="heading-what-are-the-main-issues-with-nodejs"><strong>What are the main issues with Node.js?</strong></h4>
<ul>
<li><p><strong>Any program can write to the filesystem and the network</strong>
  This might be a security problem, especially when intalling untrusted packages from npm.  <a target="_blank" href="https://blog.npmjs.org/post/163723642530/crossenv-malware-on-the-npm-registry">The</a> <code>[crossenv](https://blog.npmjs.org/post/163723642530/crossenv-malware-on-the-npm-registry)</code> <a target="_blank" href="https://blog.npmjs.org/post/163723642530/crossenv-malware-on-the-npm-registry">incident</a>  is an example. If  <code>crossenv</code>had not had writing permissions, this would not have happened.</p>
</li>
<li><p><strong>The build system (GYP)</strong>
  Using GYP to build a module that links to a C library is a big pain. In order to have a sane DX you’ll have to use  <code>node-gyp</code>  (a layer on top of GYP) and maybe other layers (like  <code>[nan](https://www.npmjs.com/package/nan)</code>).</p>
</li>
<li><p><strong>The module system and npm</strong>
  The main problem here is that the module system isn’t compatible with browsers so our code isn’t fully isomorphic. This is mainly caused by two reasons: storing dependencies in  <code>node_modules</code>  and having a  <code>package.json</code>.</p>
</li>
</ul>
<h1 id="heading-lets-get-started-with-installing-deno"><strong>Let's get started with installing Deno</strong></h1>
<p>Using PowerShell (Windows):</p>
<pre><code class="lang-sh">iwr https://deno.land/x/install/install.ps1 -useb | iex
</code></pre>
<p>With Shell:</p>
<pre><code class="lang-bash">curl -fsSL https://deno.land/x/install/install.sh | sh
</code></pre>
<p>With Homebrew:</p>
<pre><code class="lang-bash">brew install deno
</code></pre>
<p>Now check if  <code>deno</code>  was installed by running the  <code>deno --version</code>  command in your terminal.</p>
<h1 id="heading-simple-http-server"><strong>Simple http server</strong></h1>
<p>This example contains a simple http server  (app.ts):</p>
<pre><code class="lang-sh"> import  { serve }  from  <span class="hljs-string">"https://deno.land/std@0.50.0/http/server.ts"</span>;
 const s =  serve({ port:  8000  });
 console.log(<span class="hljs-string">"http://localhost:8000/"</span>);
 <span class="hljs-keyword">for</span>  await  (const req of s)  {
    req.respond({ body:  <span class="hljs-string">"Hello World\n"</span>  });
 }
</code></pre>
<p>Run the code:</p>
<pre><code class="lang-bash"> deno run app.ts
</code></pre>
<p>This results into permission error</p>
<pre><code class="lang-sh"> error: Uncaught PermissionDenied: <span class="hljs-built_in">read</span> access to <span class="hljs-string">"http/server.ts"</span>, run  again with the --allow-read flag

 ► <span class="hljs-variable">$deno</span>$/dispatch_json.ts:40:11
 at DenoError (<span class="hljs-variable">$deno</span>$/errors.ts:20:5)
 ...
</code></pre>
<p>This is because deno allows you to control the granularity of permissions. To run above  application you need set some flags indicating deno that particular permission are allowed. </p>
<pre><code class="lang-sh"> deno run --allow-net app.ts
 &gt; http://localhost:8000/
</code></pre>
<p>Now open up your browser at localhost:8000. You will be see the <strong>Hello World</strong> text.
Okay this was just a basic demonstration of how you could create simple http server using deno. </p>
<blockquote>
<p>See more example <a target="_blank" href="https://deno.land/std/examples">here</a></p>
</blockquote>
<p>I  have created User REST API in deno feel free to check it out  <a target="_blank" href="https://github.com/smithg09/Deno_REST_API">here</a>. Clone the Repo and play around. Contribution are always welcome🎉</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>There's still a long time until Deno reaches a production-ready state, but I think it’s on the right path in order to be a better Javascript runtime than Node.js🔥.
Thanks for reading! 👋👋</p>
<p><strong>Do check my website <a target="_blank" href="https://smithgajjar.dev">smithgajjar.dev</a> and GitHub <a target="_blank" href="https://github.com/smithg09">here</a></strong>
<strong>Follow me on <a target="_blank" href="https://www.linkedin.com/in/smith-gajjar-5a27716b/">LinkedIn</a></strong></p>
<div class="hn-embed-widget" id="buymeacoffee"></div>]]></content:encoded></item></channel></rss>