<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Smrity Das</title>
    <description>The latest articles on DEV Community by Smrity Das (@smritydas16).</description>
    <link>https://dev.to/smritydas16</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1085480%2F651a7cd8-d479-406f-ab8b-7414eec49961.jpg</url>
      <title>DEV Community: Smrity Das</title>
      <link>https://dev.to/smritydas16</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/smritydas16"/>
    <language>en</language>
    <item>
      <title>Nest.js GraphQL - The Code First Approach</title>
      <dc:creator>Smrity Das</dc:creator>
      <pubDate>Fri, 09 Jun 2023 07:47:23 +0000</pubDate>
      <link>https://dev.to/smritydas16/nestjs-graphql-thecode-first-approach-3f9l</link>
      <guid>https://dev.to/smritydas16/nestjs-graphql-thecode-first-approach-3f9l</guid>
      <description>&lt;p&gt;&lt;strong&gt;Introduction&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;REST has been the industry standard for creating web APIs in recent years. It offers a set of guidelines that can produce completely functional web services, but Rest's rules and restrictions become problematic. GraphQL enters software development to address Rest's issues.&lt;/p&gt;

&lt;p&gt;API development is made simpler and more widely available by GraphQL. The purpose of this article is to introduce you to GraphQL and show you how to integrate the GraphQL client with React.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is GraphQL?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;GraphQL is a query language for APIs. It 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. Being able to request the precise or exact data format that the client requires makes it more versatile than REST APIs.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why NestJS?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;NestJS is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with and fully supports TypeScript (yet still enables developers to code in pure JavaScript) and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Reactive Programming). GraphQL and NestJS &lt;br&gt;
combined with TypeScript helps you develop better type safety with your GraphQL queries, giving you end-to-end typing.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Code First&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Instead of generating our GraphQL schema by manually writing GraphQL SDL, we use the code first methodology. Instead, we create the SDL from TypeScript class definitions using TypeScript decorators. The @nestjs/graphql package automatically creates the schema for you by reading the metadata specified by the decorators.&lt;/p&gt;

&lt;p&gt;Nest.js GraphQL - The Code First Approach&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Installation&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;First create a new project using Nest CLI and cd into that folder.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;nest new your_project_name&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Now let’s install the GraphQL dependencies.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;npm i @nestjs/graphql @nestjs/apollo graphql apollo-server-express&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Let’s install other dependencies we’ll be needing.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;npm i class-transformer class-validator @prisma/client bson-objectid npm i -D prisma&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Configure GraphQL Module&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Once the required packages have been installed, we can import the &lt;code&gt;GraphQLModule&lt;/code&gt; and set its &lt;code&gt;forRoot()&lt;/code&gt; static method configuration.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--HWKZdPlT--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/abdtuymsme5in8k6b62x.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--HWKZdPlT--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/abdtuymsme5in8k6b62x.jpg" alt="Image description" width="594" height="388"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Nest.js GraphQL - The Code First Approach&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;forRoot()&lt;/code&gt; takes an options object as an argument. These options are passed through to the underlying driver instance. Here we’re using Apollo as our driver.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Initialize Prisma Schema&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Since we’ll be using prisma let’s generate the schema for it. To generate a prisma schema run the following command&lt;/p&gt;

&lt;p&gt;&lt;code&gt;npx prisma generate&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This command will create a &lt;code&gt;prisma&lt;/code&gt; folder and a &lt;code&gt;schema.prisma&lt;/code&gt; file inside it. Let’s modify it add the following code.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--rxPlgAqy--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7vpm3ie8mioaf2qwpy2h.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--rxPlgAqy--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7vpm3ie8mioaf2qwpy2h.png" alt="Image description" width="599" height="448"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This Coffees model will represent out collection in the database. You can add more fields if you want to.&lt;/p&gt;

&lt;p&gt;That prisma command will also generate a .env file where you can put your database URL. I’ll be using MongoDB Atlas for this project. So create a database and add that to your .env file. Don’t forget to add it to your &lt;code&gt;.gitignore&lt;/code&gt; file.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Prisma Module&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let’s generate the prisma module and service we’ll be using throughout the app for database interactions.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;nest g mo prisma&lt;br&gt;
nest g service prisma --no-spec&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;These command will create a &lt;code&gt;prisma&lt;/code&gt; folder inside &lt;code&gt;src&lt;/code&gt; and add two files &lt;code&gt;prisma.module.ts&lt;/code&gt; and &lt;code&gt;prisma.service.ts&lt;/code&gt; Open the &lt;code&gt;prisma.service.ts&lt;/code&gt; file and the following code.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--HNYiyC4j--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sakiekbjw77st41f3qt0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--HNYiyC4j--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sakiekbjw77st41f3qt0.png" alt="Image description" width="599" height="538"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Coffee Module&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We’ll be building an imaginary coffee GraphQL api. Let’s generate the module, resolver and service for coffees.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;nest g mo coffee&lt;br&gt;
nest g resolver coffee --no-spec nest g service coffee --no-spec&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Before continuing let’s add the following code in your &lt;code&gt;nest-cli.json file.&lt;/code&gt; This will help us to remove a lot of redundant typing.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;"compilerOptions": {&lt;br&gt;
"plugins": ["@nestjs/graphql"]&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Coffee Model&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Coffee model will represent the coffee collection and &lt;code&gt;ObjectType&lt;/code&gt; which is required if you want to use that as response type. Create a model folder inside coffee folder and  &lt;code&gt;coffee.model.ts&lt;/code&gt; and add the following code.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--bLYUyiLh--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k44v4tmc1pb3mw9ts65i.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--bLYUyiLh--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k44v4tmc1pb3mw9ts65i.png" alt="Image description" width="599" height="330"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Most of the definitions in a GraphQL schema are &lt;strong&gt;object types&lt;/strong&gt;. Each object type you define should represent a domain object that an application client might need to interact with. Coffee will be the response type that’s why we’ve use the &lt;code&gt;ObjectType&lt;/code&gt; decorator.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Generating Input Types&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If the mutation or query needs to take an object as an argument, we can create an &lt;strong&gt;input type&lt;/strong&gt;. The input type is a special kind of object type that can be passed in as an argument. To declare an input type, use the &lt;code&gt;@InputType()&lt;/code&gt; decorator. We’ll need 3 input types for creating coffee, updating coffee and pagination. So, create a folder &lt;code&gt;tscoffee/dto&lt;/code&gt; and add 3 files, create-&lt;code&gt;coffee.dto.ts&lt;/code&gt; , &lt;code&gt;update-coffee.dto.ts&lt;/code&gt; and &lt;code&gt;pagination.dto.ts&lt;/code&gt; and add the following code.&lt;br&gt;
&lt;code&gt;create-coffee.dto.ts&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--tKFRwKuk--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o255mix9shmiq29jbn2r.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--tKFRwKuk--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o255mix9shmiq29jbn2r.png" alt="Image description" width="599" height="582"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;update-coffee.dto.ts&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--0YX_x6vf--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/90dl41oiur85nbu6isbs.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--0YX_x6vf--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/90dl41oiur85nbu6isbs.png" alt="Image description" width="598" height="300"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;pagination.dto.ts&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--a4nyhvtC--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pr57gq6sowrp0bwkehkn.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--a4nyhvtC--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pr57gq6sowrp0bwkehkn.png" alt="Image description" width="599" height="434"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Providers&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;An essential idea in Nest is the concept of providers. The core Nest classes, such as services, repositories, factories, helpers, and so forth, can be be thought of as providers. The fundamental benefit of a provider is that it may be injected as a dependency. &lt;/p&gt;

&lt;p&gt;As a result, objects can establish a variety of connections with one another, and the Nest runtime system can take on a considerable portion of the work of "wiring up" instances of objects.&lt;/p&gt;

&lt;p&gt;Our &lt;code&gt;coffee.service.ts&lt;/code&gt;    file will act as abstract layer for interacting with the coffees collection. Open it and add the following code.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--HIf5nrZQ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u6imfxyd551fqo074k5v.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--HIf5nrZQ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u6imfxyd551fqo074k5v.jpg" alt="Image description" width="469" height="913"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This is our typical CRUD operations logic. Here I’m using the &lt;code&gt;PrismaErrorCodes&lt;/code&gt; enum to store the conflict error code.&lt;br&gt;
&lt;code&gt;prisma-error-codes.enum.ts&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--iKjqiqXQ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s963vz3padst8ijkyht8.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--iKjqiqXQ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s963vz3padst8ijkyht8.jpg" alt="Image description" width="599" height="157"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Resolvers&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Resolvers offer the guidelines for converting a GraphQL operation (a query, mutation, or subscription) into data. They deliver the exact data shape that we specify in our schema, either synchronously or as a promise that resolves to that shape's result. A resolver map is often made by hand. On the other hand, the &lt;code&gt;@nestjs/graphql&lt;/code&gt; package automatically creates a resolver map using the metadata supplied by the decorators you use to annotate classes.&lt;/p&gt;

&lt;p&gt;At this point, we've defined the objects (type definitions) that can exist in our data graph, but clients don't yet have a way to interact with those objects. To address that, we need to create a resolver class. Resolver decorator exported from &lt;code&gt;@nestjs/graphql&lt;/code&gt; package marks a class as a resolver. To query something we need to use the Query decorator exported from &lt;code&gt;@nestjs/graphql.&lt;/code&gt; For example -&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Xu3xkiC1--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yyw265j82rktxxmrbah2.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Xu3xkiC1--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yyw265j82rktxxmrbah2.jpg" alt="Image description" width="597" height="215"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here I’m using &lt;code&gt;@Query()&lt;/code&gt; decorator to mark &lt;code&gt;findAll&lt;/code&gt; method as a query type. I’m returning an array of coffees to indicate that when this query is resolved it will return an array of coffee. By default the query will be named as same as the method name that is &lt;code&gt;findAll.&lt;/code&gt; Using the name property will override it. If you need any arguments to your query or mutation use can use the &lt;code&gt;@Args()&lt;/code&gt; decorator.&lt;/p&gt;

&lt;p&gt;For normal types like string or number NestJS GraphQL package will automatically infer them. But sometimes our input types are complicated which can’t be inferred. In that case we can use the type property to provide metadata. You mutate we use the&lt;br&gt;
&lt;code&gt;@Mutation()&lt;/code&gt; decorator.&lt;/p&gt;

&lt;p&gt;Now that you understand all the decorators open the &lt;code&gt;coffee.resolver.ts&lt;/code&gt; file that we generated a while ago and add the following code.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--XJ0D-vUs--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/biq3lntoetvmhajwkpvs.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--XJ0D-vUs--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/biq3lntoetvmhajwkpvs.png" alt="Image description" width="594" height="798"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Subscriptions&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The GraphQL specification includes a third operation type called subscription in addition to query-based data retrieval and mutation-based data modification. Data can be pushed from the server to clients who opt to receive real-time messages from the server via GraphQL subscriptions. Similar to queries in that they describe a collection of fields to be supplied to the client, subscriptions establish a channel and send a result to the client each time a specific event occurs on the server rather than returning a single answer right away.&lt;/p&gt;

&lt;p&gt;To add subscriptions to our API we need to add the subscriptions property in &lt;code&gt;app.module.ts.&lt;/code&gt; Let’s modify the &lt;code&gt;app.module.ts&lt;/code&gt; and replace with the following code.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--6C3gaCiJ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gtdlc5qu758uysj0x4pt.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--6C3gaCiJ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gtdlc5qu758uysj0x4pt.jpg" alt="Image description" width="594" height="376"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We utilize the &lt;code&gt;@Subscription()&lt;/code&gt; decorator (exported from the @nestjs/graphql package) and the PubSub class from the &lt;code&gt;graphql-subscriptions&lt;/code&gt; package, which provides a straightforward publish/subscribe API, to construct a subscription using the code first methodology.&lt;br&gt;
&lt;code&gt;npm i graphql-subscriptions&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Add the following code to &lt;code&gt;coffee/constants/subscriptions.ts&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--nd2hNMBC--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zkznpdonjsc5mn2e74yp.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--nd2hNMBC--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zkznpdonjsc5mn2e74yp.jpg" alt="Image description" width="595" height="128"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We’ll add subscriptions to &lt;code&gt;createCoffee&lt;/code&gt; . So each time we create a new coffee we’ll get the real time updates. &lt;/p&gt;

&lt;p&gt;Import the &lt;code&gt;PubSub&lt;/code&gt; constructor from &lt;code&gt;graphql-subscriptions&lt;/code&gt; and create an instance.&lt;/p&gt;

&lt;p&gt;Now open &lt;code&gt;coffee.resolver.ts&lt;/code&gt; file and add the following code.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--TCjqeqw8--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vggzo1g1b69w6na0zdgz.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--TCjqeqw8--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vggzo1g1b69w6na0zdgz.jpg" alt="Image description" width="595" height="128"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Remember to import the &lt;code&gt;@Subscription&lt;/code&gt; decorator from &lt;code&gt;@nestjs/graphql&lt;/code&gt; and the &lt;code&gt;COFFEE_ADDED&lt;/code&gt; constants. &lt;/p&gt;

&lt;p&gt;Now replace the &lt;code&gt;createCoffee&lt;/code&gt; mutation code with the following.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Z4x1IH1d--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/emunt1zy63l6mopfkjxv.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Z4x1IH1d--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/emunt1zy63l6mopfkjxv.jpg" alt="Image description" width="593" height="165"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Generated Schema&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--jha9hlk---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ly4kctagfk74folqejgn.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--jha9hlk---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ly4kctagfk74folqejgn.jpg" alt="Image description" width="595" height="335"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Query Examples&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--wgCtyG8d--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rrqe1nq5xifo469x6jou.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--wgCtyG8d--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rrqe1nq5xifo469x6jou.jpg" alt="Image description" width="595" height="335"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--9xQHNIQZ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ktb0ya57k8pwdl21vode.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--9xQHNIQZ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ktb0ya57k8pwdl21vode.jpg" alt="Image description" width="595" height="335"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Read an article on &lt;a href="https://careinsider.ai/"&gt;Care Insider&lt;/a&gt;&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>graphql</category>
      <category>nestjs</category>
    </item>
    <item>
      <title>Nodejs Async Hooks 101</title>
      <dc:creator>Smrity Das</dc:creator>
      <pubDate>Fri, 19 May 2023 07:54:06 +0000</pubDate>
      <link>https://dev.to/smritydas16/nodejs-async-hooks-101-5cn4</link>
      <guid>https://dev.to/smritydas16/nodejs-async-hooks-101-5cn4</guid>
      <description>&lt;p&gt;Node.js is a highly scalable and performance-oriented platform that enables developers to create applications that are fast, efficient, and lightweight. One of Node.js' key features is its ability to handle multiple asynchronous operations at the same time using a single-threaded event loop.&lt;/p&gt;

&lt;p&gt;Async Hooks is a new Node.js feature that allows developers to access the event loop and track the lifecycle of asynchronous operations in their applications. This feature provides information about how asynchronous operations are carried out and can aid in the identification of potential performance issues and bottlenecks.&lt;/p&gt;

&lt;p&gt;Developers can use Async Hooks to get information about the current state of an asynchronous operation and receive notifications when it begins, ends, or encounters an error. This data can be used to determine how long an asynchronous operation takes, what resources it consumes, and how it affects the application's overall performance.&lt;/p&gt;

&lt;p&gt;Async Hooks are implemented as Node.js callbacks registered with the &lt;strong&gt;async_hooks&lt;/strong&gt; module. Callbacks are informed about the current asynchronous operation and can be used to record data, track resources, and manage performance.&lt;/p&gt;

&lt;p&gt;Async Hooks can be used to provide custom logic for monitoring and managing asynchronous actions in addition to offering performance insights. Async Hooks can be used by developers, for instance, to provide unique resource management, error handling, and logging solutions.&lt;/p&gt;

&lt;p&gt;Async Hooks, a potent new feature of Node.js that gives developers more insight into the inner workings of asynchronous actions, is summarised above. With this knowledge, programmers may create apps that are quicker and more effective, and they can also rapidly locate and fix performance problems.&lt;/p&gt;

&lt;p&gt;Example of &lt;strong&gt;aync_hook&lt;/strong&gt; implementation:&lt;/p&gt;

&lt;p&gt;In this example, we define a set of hooks for tracking asynchronous operations. The hooks include &lt;code&gt;init&lt;/code&gt; , &lt;code&gt;before&lt;/code&gt; , &lt;code&gt;after&lt;/code&gt; , &lt;code&gt;destroy&lt;/code&gt; , and &lt;code&gt;promiseResolve&lt;/code&gt; .&lt;/p&gt;

&lt;p&gt;We then create an Async Hook using &lt;code&gt;async_hooks.createHook&lt;/code&gt; and pass in the hooks. The created hook is then enabled using &lt;code&gt;asyncHook.enable()&lt;/code&gt; .&lt;/p&gt;

&lt;p&gt;We also have a &lt;code&gt;setTimeout&lt;/code&gt; function that will execute after 1000 milliseconds, which will trigger the hooks to be called.&lt;/p&gt;

&lt;p&gt;Finally, when the Node.js process is about to exit, the hook is disabled using a&lt;code&gt;syncHook.disable()&lt;/code&gt; .&lt;/p&gt;

&lt;p&gt;When you run this code, you will see output from the hooks that log information about the asynchronous operation triggered by the &lt;code&gt;setTimeout&lt;/code&gt; function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const async_hooks = require('async_hooks');
const hooks = {
init: (asyncId, type, triggerAsyncId, resource) =&amp;gt; {
console.log(`Init Hook: asyncId: ${asyncId}, type: ${type}`);
},
before: (asyncId) =&amp;gt; {
console.log(`Before Hook: asyncId: ${asyncId}`);
},
after: (asyncId) =&amp;gt; {
console.log(`After Hook: asyncId: ${asyncId}`);
},
destroy: (asyncId) =&amp;gt; {
console.log(`Destroy Hook: asyncId: ${asyncId}`);
},
promiseResolve: (asyncId) =&amp;gt; {
console.log(`Promise Resolve Hook: asyncId: ${asyncId}`);
},
};

const asyncHook = async_hooks.createHook(hooks);
asyncHook.enable();
setTimeout(() =&amp;gt; {
console.log('Timeout finished');
}, 1000);
process.on('exit', () =&amp;gt; {
asyncHook.disable();
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;&lt;strong&gt;Async Hooks should be used in the following scenarios&lt;/strong&gt;:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;u&gt;Performance Monitoring&lt;/u&gt;: Async Hooks offers information on the manner in which asynchronous operations are carried out, how long they take to complete, and what resources they use. This data can be used to track your application's performance and spot any potential performance bottlenecks.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;u&gt;Resource management&lt;/u&gt;: Resources connected to asynchronous operations can be managed and tracked using async hooks. Async Hooks can be used, for instance, to track and release file descriptors, network connections, and other resources that&lt;br&gt;
asynchronous actions acquire and use.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;u&gt;Error Handling&lt;/u&gt;: Custom error handling for asynchronous activities can be implemented using async hooks. Instead of handling errors in each individual asynchronous action, you may utilize Async Hooks to find errors and handle them centrally.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;u&gt;Logging&lt;/u&gt;: Async Hooks can be used to log information about asynchronous operations and their lifecycle. This information can be used for debugging and troubleshooting, as well as for performance analysis and optimization.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Async Hook &lt;strong&gt;Resource Management&lt;/strong&gt; Example:&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const async_hooks = require('async_hooks');
const fs = require('fs');
const activeResources = new Map();
const hooks = {
init: (asyncId, type, triggerAsyncId, resource) =&amp;gt; {
if (type === 'FSREQWRAP') {
activeResources.set(asyncId, resource);
}
},
before: (asyncId) =&amp;gt; {},
after: (asyncId) =&amp;gt; {},
destroy: (asyncId) =&amp;gt; {
const resource = activeResources.get(asyncId);
if (resource) {
resource.close();
activeResources.delete(asyncId);
}
},
promiseResolve: (asyncId) =&amp;gt; {},
};

const asyncHook = async_hooks.createHook(hooks);
asyncHook.enable();
fs.open('test.txt', 'r', (err, fd) =&amp;gt; {
if (err) {
console.error(err);
return;
}
console.log(`Opened file descriptor: ${fd}`);
});
process.on('exit', () =&amp;gt; {
asyncHook.disable();
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;&lt;strong&gt;Read an article on EHR Integration&lt;/strong&gt; &lt;/p&gt;
&lt;div class="crayons-card c-embed text-styles text-styles--secondary"&gt;
    &lt;a href="https://techvariable.com/blogs/ehr-integration/" rel="noopener noreferrer"&gt;
      techvariable.com
    &lt;/a&gt;
&lt;/div&gt;



</description>
      <category>node</category>
      <category>async</category>
      <category>hooks</category>
      <category>asynchronousoperation</category>
    </item>
  </channel>
</rss>
