<?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 Arda Örkin on Medium]]></title>
        <description><![CDATA[Stories by Arda Örkin on Medium]]></description>
        <link>https://medium.com/@ardaorkin?source=rss-4ac7b9d750f3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3B2T8kwvGQnwkIVsxfANOw.jpeg</url>
            <title>Stories by Arda Örkin on Medium</title>
            <link>https://medium.com/@ardaorkin?source=rss-4ac7b9d750f3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 06:09:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ardaorkin/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[The Journey to a Safer Frontend: Why We Removed React.FC]]></title>
            <link>https://engineering.gusto.com/the-journey-to-a-safer-frontend-why-we-removed-react-fc-095ff0b3e2e4?source=rss-4ac7b9d750f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/095ff0b3e2e4</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[team-collaboration]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Arda Örkin]]></dc:creator>
            <pubDate>Mon, 09 Feb 2026 17:01:01 GMT</pubDate>
            <atom:updated>2026-02-09T17:01:01.215Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pTEZWxEA2QrUTbIzfjTbtg.avif" /><figcaption>Person in parachute over mountains during daytime</figcaption></figure><p>Sometimes, engineering improvements don’t begin with a grand roadmap. They start with a small moment of curiosity.</p><p>One afternoon, while working on a React component, I noticed something strange.</p><p>When I typed my component props directly, TypeScript flagged an unused prop. But when I wrapped the same component in React.FC, the warning vanished.</p><p>That didn’t feel right. TypeScript is supposed to <em>protect</em> us from mistakes — not silently ignore them.</p><p>I opened up a TypeScript playground and tried a few experiments. Sure enough, React.FC was changing how the compiler treated props. It was as if TypeScript was politely saying, “Don’t worry, everything’s fine,” even when it wasn’t.</p><p>That small hunch kicked off a journey that eventually touched thousands of files and changed how we write components across Gusto’s frontend.</p><h3>A Familiar Pattern–with Hidden Costs</h3><p>In Gusto, many of our React components followed a familiar pattern:</p><pre>type ButtonProps = {<br>  label: string<br>  onClick?: () =&gt; void<br>}<br><br>const Button: React.FC&lt;ButtonProps&gt; = ({ label, onClick }) =&gt; (<br>  &lt;button onClick={onClick}&gt;{label}&lt;/button&gt;<br>)</pre><p>This convention made sense years ago. React.FC looked clean and convenient, and it was widely recommended in early TypeScript + React guides</p><p>But as I started digging deeper, the cracks started to show.</p><p>React.FC does a few things behind the scenes that can quietly mislead developers:</p><ul><li>It <strong>allows invalid default prop values</strong> without error.</li><li>It <strong>hides unused props</strong>, so TypeScript doesn’t warn you about dead code.</li><li>It <strong>breaks type inference for generics</strong>, making reusable components harder to type.</li></ul><p>Individually, these issues are subtle. Together, they add up to technical debt that TypeScript is supposed to help us avoid.</p><p>In practice, this meant we were quietly accumulating technical debt.</p><h3>The Moment It Clicked</h3><p>The problem became obvious when I compared two versions of the same component — one typed with React.FC, one without:</p><pre>// With React.FC — no warning<br>const Example: React.FC&lt;{ used: string; unused: string }&gt; = ({ used }) =&gt; {<br>  return &lt;div&gt;{used}&lt;/div&gt;<br>}<br><br>// Without React.FC — correct warning<br>const Example = ({ used }: { used: string; unused: string }): React.ReactNode =&gt; {<br>  return &lt;div&gt;{used}&lt;/div&gt;<br>}</pre><p>In the first case, TypeScript didn’t complain that the <strong>unused</strong> variable wasn’t being used. In the second, it did exactly what we’d expect.</p><p>That’s when it clicked: our type system was only as good as the types we chose to trust. And in this case, <strong>React.FC</strong> was making promises it couldn’t keep.</p><h3>From a Conversation to a Codebase-Wide Change</h3><p>I shared the discovery in a developer chat. At first, it was a casual “today I learned” post — the kind that might get a few emoji reactions and then fade away. But this one sparked a real discussion. Other engineers chimed in, sharing similar frustrations and half-remembered TypeScript quirks.</p><p>It quickly became clear that we weren’t alone — and that we could actually do something about it.</p><p>This is a good moment to pause and talk about <strong>Gusto’s engineering culture</strong>, because it played a critical role in what happened next. At Gusto, turning an idea into action rarely feels like a solo effort. Collaboration isn’t just an abstract value — it’s supported by concrete structures that make it easy to surface ideas and get meaningful feedback.</p><p>We have guilds, Architecture Decision Records (ADRs), Tech Spec reviews, recurring office hours, and open Slack channels that create clear paths for discussion. If you want to raise a frontend-specific concern, you can bring it to the Web team’s office hours. If the change touches shared infrastructure or conventions, there are established channels and forums where those conversations naturally happen. And if an idea needs broader alignment, it can be formalized through an ADR and reviewed openly.</p><p>That environment made all the difference here. What started as a casual observation didn’t stall at “interesting, but risky.” Instead, it quickly found collaborators, skeptics, and champions — people who helped pressure-test the idea and shape it into something actionable.</p><p>Within days, we decided to see how far the problem went. The answer: very far. Our main frontend repository contained thousands of components typed with <strong>React.FC</strong>. Fixing this would mean touching nearly every package.</p><p>It was ambitious — maybe even a little reckless. But we had the tools, the support, and the shared understanding that the payoff — real, enforced type safety — would be worth it.</p><h3>Automating the Change</h3><p><strong>Step 1: Rewrite Component Declarations</strong></p><p>We wrote a transformation script that scanned the entire codebase for components defined with <strong>React.FC</strong>. For each one, it:</p><ul><li>Extracted the props type from <strong>React.FC&lt;Props&gt;</strong></li><li>Inlined that type into the component’s parameter</li><li>Added a clear return type <strong>(React.ReactNode)</strong></li></ul><pre>// Before<br>const Card: React.FC&lt;CardProps&gt; = ({ title }) =&gt; &lt;div&gt;{title}&lt;/div&gt;<br><br>// After<br>const Card = ({ title }: CardProps): React.ReactNode =&gt; &lt;div&gt;{title}&lt;/div&gt;</pre><p>The result was simpler, stricter, and easier for TypeScript to reason about.</p><p><strong>Step 2: Enforce Explicit Return Types</strong></p><p>Next, we ensured every exported component explicitly declared its return type. If a component returned JSX but didn’t specify a type, we added one automatically:</p><pre>// Before<br>export function Modal({ isOpen }: ModalProps) {<br>  return isOpen ? &lt;div&gt;Open&lt;/div&gt; : null<br>}<br><br>// After<br>export function Modal({ isOpen }: ModalProps): React.ReactNode {<br>  return isOpen ? &lt;div&gt;Open&lt;/div&gt; : null<br>}</pre><p>This gave every component a clear contract — one TypeScript could enforce.</p><h3>The Cleanup Ripple Effect</h3><p>Once the migration ran, something unexpected happened: the compiler began surfacing errors we didn’t know existed:</p><ul><li><strong>Unused props</strong> that had quietly survived through multiple refactors</li><li><strong>Default values with invalid types</strong></li><li><strong>Inconsistent component definitions</strong> across projects</li></ul><p>By removing one abstraction, we exposed dozens of small issues that had gone unnoticed. What started as a typing cleanup turned into a meaningful improvement in overall code health.</p><h3>Keeping It That Way</h3><p>After the migration, we wanted to make sure React.FC didn’t creep back in. So we added a linter rule to block it entirely:</p><pre>&quot;@typescript-eslint/no-restricted-types&quot;: [<br>  &quot;error&quot;,<br>  {<br>    &quot;types&quot;: {<br>      &quot;FC&quot;: {<br>        &quot;message&quot;: &quot;Avoid React.FC. Use explicit prop types and return values instead.&quot;<br>      }<br>    }<br>  }<br>]</pre><p>Now the rule enforces the convention automatically.</p><h3>What We Gained</h3><p>By the end of the project:</p><ul><li><strong>Over 5,000 files updated</strong></li><li><strong>Dozens of frontend packages standardized</strong></li><li><strong>Dozens of hidden bugs fixed</strong></li><li><strong>Our type system became more predictable and trustworthy</strong></li></ul><p>But the real win wasn’t just technical. It was cultural.<br>This project reminded us that engineering excellence often comes from <em>paying attention</em> — from noticing when something feels off and following that thread until you understand it fully.</p><h3>Conclusion</h3><p>Removing <strong>React.FC</strong> wasn’t about being pedantic — it was about precision.<br>By choosing explicit, predictable typing over hidden convenience, we gained stronger guarantees and a cleaner foundation for the future.</p><p>Sometimes, progress isn’t about adopting the newest tool — it’s about questioning the ones we’ve quietly accepted.</p><h3>Further Reading</h3><ul><li><a href="https://github.com/facebook/create-react-app/pull/8177">Removed React.FC from Create React App templates (facebook/create-react-app#8177)</a></li><li><a href="https://github.com/typescript-cheatsheets/react#function-components">React + TypeScript Cheatsheets: Function Components</a></li></ul><p>Gusto is hiring! If you enjoy solving difficult problems and multiplying your impact, check out our careers page at <a href="https://gusto.com/careers">gusto.com/careers</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=095ff0b3e2e4" width="1" height="1" alt=""><hr><p><a href="https://engineering.gusto.com/the-journey-to-a-safer-frontend-why-we-removed-react-fc-095ff0b3e2e4">The Journey to a Safer Frontend: Why We Removed React.FC</a> was originally published in <a href="https://engineering.gusto.com/">Gusto Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Behind the Scenes with Jotform’s PDF Editor]]></title>
            <link>https://medium.com/jotform-tech/behind-the-scenes-with-jotforms-pdf-editor-ab5d0c001768?source=rss-4ac7b9d750f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab5d0c001768</guid>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[pdf-editing]]></category>
            <category><![CDATA[pdf-editor-software]]></category>
            <category><![CDATA[pdf-editor]]></category>
            <category><![CDATA[jotform]]></category>
            <dc:creator><![CDATA[Arda Örkin]]></dc:creator>
            <pubDate>Mon, 20 Mar 2023 13:23:12 GMT</pubDate>
            <atom:updated>2023-03-20T13:23:12.101Z</atom:updated>
            <content:encoded><![CDATA[<p>The PDF, or portable document format, was invented in 1993 by a research and development team called Camelot, led by Adobe co-founder John Warnock. It is now a widely used format that allows users to open these documents on a variety of platforms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lt6567f0kUhdekxT" /></figure><p>At Jotform, we are fully aware of how useful and widespread this document format is, so we give our users the opportunity to create and share their own PDFs. With Jotform PDF Editor, our users are able to receive PDFs of form submissions, send respondents either default or customized PDF documents, download all submission data in a zipped format, and more.</p><p>All of Jotform’s products interact with the Jotform PDF Editor at some point. Therefore, running some codes on PDF Editor source code requires a lot of attention, calculation, and precaution. In upcoming articles, we’ll talk about what factors we have to pay special attention to when we are doing some code practice. In this article, though, we’ll look behind the scenes of producing a PDF document at Jotform.</p><h4>Running a browser to welcome a request from another browser</h4><p>Let’s say we’ve created a form using Jotform’s Form Builder to collect people’s names, phone numbers, email addresses, and mailing addresses. After getting a certain number of submissions, we decide we want to get submission data in a PDF format. To achieve that goal, we just need to open Jotform’s PDF Editor in a browser, where we’ll see a screen like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dM1SGhhMmaCbo_Wg" /></figure><p>When we open the URL of Jotform’s PDF Editor, we can instantly see our submissions in PDF format. This is just a preview of what our PDF document will look like. Behind the scenes, submission data is being obtained with an API call and is used to fill the editor area. But when we want to download a submission as a PDF document, a Node.js-based microservice does the job for us.</p><p>The main job of the microservice is to open exactly the same page that we saw when we opened Jotform’s PDF Editor in our web browser, convert what it sees to a PDF document, save it to a file, and send back the URL of the file to the front-end where the request was made. When the front-end code receives the URL of the document, it redirects to the URL, and the PDF downloads.</p><p>So, when we look at the process from a bird’s-eye view, we can say that to produce a PDF document via the request that has been made by Jotform’s PDF Editor using a browser, we mainly open another browser to receive the document.</p><p>But how is a browser opened using Node.js? This question takes us to a Node.js library called Puppeteer.</p><h4><strong>Open Sesame</strong></h4><p>Data is a treasure. And it’s even more valuable when you can see it. Jotform lets its users collect data through its powerful products and then show that data in a variety of ways. So, as both a user and developer of Jotform, whenever I stand in front of a form and a submission, I feel like I am standing at a secret door to a cave full of treasures.</p><p>For me, clicking on the download button on Jotform’s PDF Editor page is like saying the secret words to open a gigantic door (because Jotform has strong security walls) with a tiny amount of effort. Instead of open sesame or mellon, for me, those magic words are:</p><pre>node run puppeteer.js</pre><p>As its creators’ clear definition states: “<em>Puppeteer is a Node.js library that provides a high-level API to control Chrome/Chromium over the DevTools Protocol.</em>” And Jotform uses this wonderful tool to create PDF documents behind the scenes. Although you, wise reader, can easily learn how to create a PDF document by using the puppeteer.js library, I want to show a simple example of it.<br>First, let’s write some HTML and CSS. Let’s create a file called index.html and write the lines below into it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b872e852161d0297cd64cdb48cadbbdd/href">https://medium.com/media/b872e852161d0297cd64cdb48cadbbdd/href</a></iframe><p>And now add some styling to that HTML file. Let’s create a file named style.css and write these lines into it:</p><p>Put these two files into a directory and serve the directory at <a href="http://localhost:3000/">http://localhost:3000</a>. I personally use <a href="https://www.npmjs.com/package/serve">serve</a> to achieve that.</p><p>Then create another directory where we will write our puppeteer server’s source code.</p><p>Run the below commands respectively under that directory</p><pre>npm init<br>npm i puppeteer</pre><p>Create a file called <strong>index.js </strong>and write below code into it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eba34d96cfbaf990e7e01182a248d828/href">https://medium.com/media/eba34d96cfbaf990e7e01182a248d828/href</a></iframe><p>Finally, execute index.js by running the below command:</p><pre>npm run index.js</pre><p>If you did everything write, you will be able to see a file called <strong>i_love_jotform.pdf </strong>inside the directory where the puppeteer server’s source code is in.</p><p><strong>The End Of The Beginning</strong></p><p>We are having so much experience in generating, delivering, and receiving PDF documents in Jotform. These experiences are occurring on both the product level and the software side. Hence, there is a lot to tell and hear about the journey of the PDF in Jotform. We are starting to follow the path of that journey through this very first article. Let’s see what is waiting for us in upcoming articles.</p><p>Arda Örkin — Frontend Developer</p><p><a href="https://www.linkedin.com/in/ardaorkin">LinkedIn</a></p><p><a href="https://twitter.com/ardaorkin">Twitter</a></p><p><a href="https://github.com/ardaorkin">GitHub</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab5d0c001768" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jotform-tech/behind-the-scenes-with-jotforms-pdf-editor-ab5d0c001768">Behind the Scenes with Jotform’s PDF Editor</a> was originally published in <a href="https://medium.com/jotform-tech">Jotform Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dockerizing A NodeJS App Along With PostgreSQL Database]]></title>
            <link>https://ardaorkin.medium.com/dockerizing-a-nodejs-app-along-with-postgresql-database-ff0d8870f219?source=rss-4ac7b9d750f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff0d8870f219</guid>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[sequelize]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Arda Örkin]]></dc:creator>
            <pubDate>Sat, 06 Nov 2021 16:07:26 GMT</pubDate>
            <atom:updated>2021-11-22T08:17:30.417Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CNFS1xrJ29e2FfO7dVfEOA.png" /></figure><p>Building an app is an adventure with many processes, algorithms, schema, design, etc. Even though it is not easy to build a robust app, publishing the project’s first release is a real pleasure. While there can be so many problems developers have to deal with throughout the production, deploying comes with its problems and questions like hows, wheres, whats… And when it comes to deployment, Docker is a powerful tool to use.</p><p>In this post, I am going to show how to deploy a NodeJS App along with PostgreSQL as a Docker image. Additionally, we are going to use Express.js and Sequelize ORM.</p><p>Here we go.</p><p><strong>Project Structure</strong></p><p>As the post is aiming to discuss deployment issues, we are going to pass the installation of the environment as quickly as possible. So let’s run this command in a shell:</p><pre>npx express-generator example-project</pre><p>It will create a project directory called <strong>example-project,</strong> let’s open it in a text editor. Then install the dependencies and run the project.</p><pre>npm i &amp;&amp; npm start</pre><pre>//or with yarn<br>yarn &amp;&amp; yarn start</pre><p>The project will run on port 3000 of your localhost. Now we are going to create our database schemas using Sequelize ORM. Create a file called <strong>.sequelizerc </strong>in the project root folder and add these lines to it:</p><pre>const path = require(&#39;path&#39;);</pre><pre>module.exports = {<br>  &#39;config&#39;: path.resolve(&#39;config&#39;, &#39;config.js&#39;),<br>  &#39;models-path&#39;: path.resolve(&#39;db&#39;, &#39;models&#39;),<br>  &#39;seeders-path&#39;: path.resolve(&#39;db&#39;, &#39;seeders&#39;),<br>  &#39;migrations-path&#39;: path.resolve(&#39;db&#39;, &#39;migrations&#39;)<br>};</pre><p>Then install the <a href="https://www.npmjs.com/package/sequelize">sequelize</a> library with npm or yarn. Once you have installed it, run this command:</p><pre>npx sequelize-cli init</pre><p>This command, using the .sequelizerc file, will create two directories. One is the <strong>config</strong> folder which includes database configurations and the other called <strong>db</strong> which has database models along with other directories that we are not going to talk about in this post.</p><p>And we need to install the <a href="https://www.npmjs.com/package/pg">pg</a> package to use PostgreSQL in our NodeJS app.</p><p><strong>Database Structure</strong></p><p>In this section, we are going to configure a database structure. First, rename the config/database.json file as config/config.js. Then open the .sequelizerc file and change database.json to config.js. It helps Sequelize to find the configuration file. Change the content of the config/config.js like that:</p><pre>module.exports = {<br>  development: {<br>    username: &quot;postgres&quot;,<br>    password: &quot;postgres&quot;,<br>    database: &quot;postgres&quot;,<br>    host: &quot;localhost&quot;,<br>    dialect: &quot;postgres&quot;,<br>  },<br>  test: {<br>    username: process.env.CI_DB_USERNAME,<br>    password: process.env.CI_DB_PASSWORD,<br>    database: process.env.CI_DB_NAME,<br>    host: process.env.CI_DB_HOSTNAME,<br>    dialect: &quot;postgres&quot;,<br>  },<br>  production: {<br>    username: process.env.PROD_DB_USERNAME,<br>    password: process.env.PROD_DB_PASSWORD,<br>    database: process.env.PROD_DB_NAME,<br>    host: process.env.PROD_DB_HOSTNAME,<br>    dialect: &quot;postgres&quot;,<br>  },<br>};</pre><p>Now we are going to create our first model. Let’s run this command:</p><pre>npx sequelize-cli model:generate --name User --attributes firstName:string,lastName:string,email:string</pre><p>It will create a file called user.js inside the db/model directory. And by that, we created our first model.</p><p>Next, we need to start the database connection before the app starts. To do that let’s call db class which is exported from the db/models/index.js and change relevant lines like that in the bin/www file:</p><pre>...</pre><pre>const db = require(&quot;../db/models&quot;);</pre><pre>...</pre><pre>/**<br> * Listen on provided port, on all network interfaces.<br> */</pre><pre>server.listen(port);<br>db.sequelize.sync({ force: false }).then(function () {<br>  server.on(&quot;error&quot;, onError);<br>  server.on(&quot;listening&quot;, onListening);<br>  console.log(&quot;Database created successfully.&quot;);<br>});</pre><p>It is time to create a route to add some users. Let’s go.</p><p><strong>Creating Database Record</strong></p><p>Let’s open routes/index.js and change it like that:</p><pre>var express = require(&quot;express&quot;);<br>var router = express.Router();<br>const db = require(&quot;../db/models/index&quot;);</pre><pre>/* GET users listing. */<br>router.get(&quot;/&quot;, async function (req, res, next) {<br>  const users = await db.User.findAll();<br>  res.render(&quot;index&quot;, { users });<br>});<br>/*POST user*/<br>router.post(&quot;/&quot;, async function (req, res, next) {<br>  const newUser = await db.User.create({ ...req.body });<br>  res.json(newUser);<br>});</pre><pre>module.exports = router;</pre><p>That’s it. We have created our first two routes one for creating users and the other for listing them.</p><p>Now, we need to change the frontend slightly so that we can add and list users via the app. So, change views/index.jade like that:</p><pre>extends layout</pre><pre>block content<br>  h1= title<br>  p Welcome to #{title}<br>  form(name=&quot;add-estimation&quot;, method=&quot;post&quot;)<br>    div.input<br>        span.label First Name<br>        input(type=&quot;text&quot;, name=&quot;firstName&quot;)<br>    div.input<br>        span.label Last Name<br>        input(type=&quot;text&quot;, name=&quot;lastName&quot;)<br>    div.input<br>        span.label Email<br>        input(type=&quot;text&quot;, name=&quot;email&quot;)<br>    div.actions<br>        input(type=&quot;submit&quot;, value=&quot;Add&quot;)<br>  if users<br>    ul<br>      each user in users<br>        if user<br>          li=user.firstName + &quot; &quot; + user.lastName + &quot; &quot; + user.email</pre><p>It is time to create Docker configuration files.</p><p><strong>Docker Configuration</strong></p><p>First, we need a Dockerfile. This is going to be like that:</p><pre>FROM node:12.13.0-alpine</pre><pre>RUN mkdir -p /opt/app</pre><pre>WORKDIR /opt/app</pre><pre>RUN adduser -S app</pre><pre>COPY . .</pre><pre>RUN npm install</pre><pre>RUN chown -R app /opt/app</pre><pre>USER app</pre><pre>EXPOSE 3000</pre><pre>CMD [ &quot;npm&quot;, &quot;start&quot; ]</pre><p>Then we need to create a <strong>docker-compose.yaml</strong> file and put these lines in it:</p><pre>version: &quot;3.7&quot;<br>services:<br>  postgres:<br>    image: postgres<br>    environment:<br>      POSTGRES_USER: postgres<br>      POSTGRES_PASSWORD: postgres<br>    ports:<br>      - &quot;5432:5432&quot;<br>    volumes:<br>      - example-db:/var/lib/postgresql/data</pre><pre>example:<br>    build:<br>      context: .<br>    environment:<br>      PROD_DB_NAME: postgres<br>      PROD_DB_USERNAME: postgres<br>      PROD_DB_PASSWORD: postgres<br>      PROD_DB_HOSTNAME: postgres<br>    depends_on:<br>      - postgres<br>    ports:<br>      - &quot;3000:3000&quot;</pre><pre>volumes:<br>  example-db:</pre><p>Now, we need persistent data storage that the database will use so that our data isn’t removed in case the container is going down. Persistent data storage are added as running this command:</p><pre>docker volume create example-db</pre><p>Now run these commands and then go to the <a href="http://localhost:3000/">http://localhost:3000</a></p><pre>docker build -t example-project . &amp;&amp; docker-compose up -d</pre><p>You will see a form in the <a href="http://localhost:3000:">http://localhost:3000:</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*bkKZr7ZYNyzn51CiZsZHIA.png" /></figure><p>Let’s add a user. Then reload the page. You should see the user you added on the page.</p><p>Finally to make sure that the persistent volume works successfully, lets down and up the Docker containers with this command:</p><pre>docker-compose down &amp;&amp; docker-compose up -d</pre><p>After that, if you still see the user you added in the <a href="http://localhost:3000,">http://localhost:3000,</a> then congratulations, you have Dockerized a NodeJS app with a PostgreSQL database, using Express.js and Sequelize ORM!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff0d8870f219" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Todo App With GraphQL, Express.js & React — Episode 2]]></title>
            <link>https://ardaorkin.medium.com/todo-app-with-graphql-express-js-react-episode-2-b56167d8c19e?source=rss-4ac7b9d750f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/b56167d8c19e</guid>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Arda Örkin]]></dc:creator>
            <pubDate>Mon, 10 May 2021 00:23:43 GMT</pubDate>
            <atom:updated>2021-11-07T20:16:12.441Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://medium.com/nerd-for-tech/todo-app-with-graphql-express-js-redux-episode-1-ccbe54b40c89?source=your_stories_page-------------------------------------">Todo App With GraphQL, Express.js And React — Episode </a>2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/0*sWGnui8mov15ZZxd.png" /></figure><p>Welcome. In this episode, we are going to add user authentication and authorization features to our app. These two concepts are often confused or used interchangeably. In fact, authentication means “identifying who the user is” and authorization means “determining what the user is and isn’t allowed to do.”</p><p>For now, our to-do lists are accessible for everyone. We want to restrict access for the sake of security, so anybody can’t add a new task to our list and can’t change or delete existing ones. To achieve that, we are going to make some back-end configurations, and lucky us, Apollo-server has some build-in helpers to help us while we make user authentication and authorization.</p><p>All right, let’s rock!</p><p><strong>Schema Configuration For User</strong></p><p>We are going to need to make some configurations in our GraphQL schema to handle user operations. To do that, we will create a type, an input, a query, and a mutation definition alongside a query function and a mutation resolver function. So, open the <strong>schmea/typeDefs/index.js </strong>file and write this line above the <strong>Query</strong> type definition</p><pre>type User {</pre><pre>_id: ID</pre><pre>username: String</pre><pre>password: String</pre><pre>}</pre><pre>input UserInput {</pre><pre>username: String</pre><pre>password: String</pre><pre>}</pre><p>This type of definition will be used for user operations. Now, let’s add a query definition. Let’s write the below line into the <strong>Query </strong>type:</p><pre>getUsers: [User]</pre><p>And add the below lines to the <strong>Mutation:</strong></p><pre>addUser(user: UserInput): User</pre><p>Let’s open the <strong>resolvers/index.js </strong>file and write this line in the <strong>Query</strong> object:</p><pre>getUsers: async (parent, args, context) =&gt;</pre><pre>  await context.models.Todo.queries.getUsers(),</pre><p>Then add this line to the <strong>Mutation </strong>object:</p><pre>addUser: async (parent, args, context) =&gt;</pre><pre>  await context.models.Todo.mutations.addUser(</pre><pre>   JSON.parse(JSON.stringify(args.user))</pre><pre>  ),</pre><p>Now, open up the <strong>models/index.js</strong> file. First import the<strong> User</strong> model which we will create next section:</p><pre>import User from &quot;../../db/models/UserModel&quot;;</pre><p>and write these lines in the <strong>queries </strong>object:</p><pre>getUsers: () =&gt;</pre><pre>  new Promise(</pre><pre>    async (resolve, reject) =&gt;</pre><pre>      await User.find({}, (err, users) =&gt;</pre><pre>        err</pre><pre>          ? reject(err)</pre><pre>          : resolve(users)</pre><pre>      )</pre><pre>  ),</pre><p>And write these lines to the <strong>mutation </strong>object:</p><pre>addUser: (user) =&gt;</pre><pre>  new Promise((resolve, reject) =&gt;</pre><pre>    new User(user).save((err, user) =&gt; (err ? reject(err) : resolve(user)))</pre><pre>  ),</pre><p>Well, that&#39;s it. Our schema is ready to handle basic user operations. Now, let’s create a <strong>User</strong> model in our database.</p><p><strong>Database Configurations For User</strong></p><p>To make sense of our GraphQL configurations, we have to create a model to which our resolvers and type definitions point to. To achieve those, create a file named <strong>UserModel.js </strong>under the <strong>db/models</strong> directory and write the below lines down into it:</p><pre>import mongoose from &quot;mongoose&quot;;</pre><pre>const userSchema = new mongoose.Schema({</pre><pre>  username: { type: String, unique: true },</pre><pre>  password: String,</pre><pre>},</pre><pre>{ timestamps: true }</pre><pre>);</pre><pre>const User = mongoose.model(&quot;User&quot;, userSchema);</pre><pre>export default User;</pre><p>Now, it is time to test. Open <a href="http://http//localhost:4000/graphql">HTTP://localhost:4000/graphql</a> and add a user like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p4rqhZ4fym-bb4AfB1QFGg.png" /></figure><p>Let’s query our first user. Make it like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6zHOZScVAW9JUDkfigtEXA.png" /></figure><p>After we ensured that everything is okay, we can sign the todo items with the creator users’ id.</p><p><strong>Sign Todo Item</strong></p><p>To add user id to todo items, open up the <strong>schema/typeDefs </strong>and add change type and input definition of the <strong>Todo</strong> like that:</p><pre>type Todo {</pre><pre>_id: ID</pre><pre>title: String</pre><pre>mission: String</pre><pre>createdAt: String</pre><pre>updatedAt: String</pre><pre>isDone: Boolean</pre><pre>owner_id: ID</pre><pre>}</pre><pre>input TodoInput {</pre><pre>title: String</pre><pre>mission: String</pre><pre>isDone: Boolean</pre><pre>owner_id: ID!</pre><pre>}</pre><p>And open <strong>db/models/TodoModel.js </strong>and change the schema like that:</p><pre>const todoSchema = new mongoose.Schema(</pre><pre>{</pre><pre>title: String,</pre><pre>mission: String,</pre><pre>isDone: Boolean,</pre><pre>owner_id: { type: mongoose.SchemaTypes.ObjectId, required: true },</pre><pre>},</pre><pre>{ timestamps: true }</pre><pre>);</pre><p>That’s it! We add required configurations to sign to-do items when they are added. Let’s test it. Copy our first users&#39; id and run this mutation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Q3qghMRzLd3uvAKiDaUZw.png" /><figcaption>In your case, you will most probably have to change the owner_id.</figcaption></figure><p>That’s it. We just added a new to-do item and signed it with our users’ id. Let&#39;s change our mutation, so return to-do items according to the given username and password. To make this happen, let’s open the<strong> schema/models/index.js </strong>and add this function to the <strong>queries </strong>object like this:</p><pre>getUserNotes: (id) =&gt;</pre><pre>  new Promise(</pre><pre>    async (resolve, reject) =&gt;</pre><pre>      await Todo.find({ owner_id: id }, (err, notes) =&gt;</pre><pre>        err ? reject(err) : resolve(notes)</pre><pre>    )</pre><pre>  ),</pre><p>And add these lines into the <strong>Query </strong>object in the <strong>schema/resolvers/index.js </strong>file:</p><pre>getUserNotes: async (parent, args, context) =&gt;</pre><pre>  await context.models.Todo.queries.getUserNotes(</pre><pre>    JSON.parse(JSON.stringify(args.owner_id))</pre><pre>  ),</pre><p>And add these lines into the <strong>Query </strong>type definition in the <strong>schema/typeDefs/index.js</strong>:</p><pre>getUserNotes(owner_id: ID!): [Todo]</pre><p>And run test query:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WqiZhbNaGcV8457-StIL5w.png" /></figure><p>If everything is working fine, let’s go to the next chapter: make login authentication required.</p><h4>Making Login Authentication Required In Apollo Server</h4><p>To make login authentication required, open the <strong>server.js </strong>and change the <strong>context </strong>object like that:</p><pre>context: ({ req }) =&gt; {</pre><pre>  const username = req?.headers?.username;</pre><pre>  const password = req?.headers?.password;</pre><pre>  const user = await validateUser({ username, password })</pre><pre>    .then((result) =&gt; result)</pre><pre>    .catch((err) =&gt; console.log(err));</pre><pre>  return {</pre><pre>    user,</pre><pre>    models: {<br>      user,</pre><pre>      Todo: generateTodoModel(user),</pre><pre>    },</pre><pre>  };</pre><pre>},</pre><p>Create a directory named <strong>controllers </strong>and create a file in it named <strong>validateUser.js</strong>. Open the <strong>validateUser.js </strong>and write these lines into it:</p><pre>import User from &quot;../db/models/UserModel&quot;;</pre><pre>const validateUser = (user) =&gt;</pre><pre>  new Promise(</pre><pre>    async (resolve, reject) =&gt;</pre><pre>      await User.findOne({ ...user }, (err, user) =&gt;</pre><pre>        err</pre><pre>        ? reject(err)</pre><pre>        : user === null</pre><pre>        ? reject(new Error(&quot;User not found&quot;))</pre><pre>        : resolve(user)</pre><pre>    )</pre><pre>  );</pre><pre>export default validateUser;</pre><p>Now, open the <strong>schema/resolvers/index.js</strong> and change the <strong>getUserNotes</strong> function like that:</p><pre>getUserNotes: async (parent, args, context) =&gt;</pre><pre>  await context.models.Todo.queries.getUserNotes()</pre><p>Then open up the <strong>schema/models/index.js</strong> file and add a <strong>user</strong> parameter to the <strong>generateTodoModel </strong>function:</p><pre>const generateTodoModel = ({user}) =&gt; ({<br>...</pre><p>And change the <strong>getUserNotes</strong> in the <strong>queries </strong>object, like that:</p><pre>getUserNotes: () =&gt;</pre><pre>  !user</pre><pre>    ? null</pre><pre>      : new Promise(</pre><pre>        async (resolve, reject) =&gt;</pre><pre>          await Todo.find({ owner_id: user._id }, (err, notes) =&gt;</pre><pre>            err ? reject(err) : resolve(notes)</pre><pre>          )</pre><pre>        ),</pre><p>Open the <strong>schema/typeDefs/index.js </strong>and change the <strong>getUserNotes </strong>query definition like in the below:</p><pre>getUserNotes: [Todo]</pre><p>Let’s open <a href="http://localhost:4000/graphql">http://localhost:4000/graphql</a>. Click the tab where the <strong>GetUserNotes</strong> query in, then click the <strong>HTTP HEADERS </strong>tab below the page and write these lines:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*gKZRwckF4kUOP-FHPinBlA.png" /></figure><p>Then run the query! If your screen is like this, then congrats, you have just added user authentication and authorization:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KDBhdWdGZnqOLw_9lfXKaw.png" /></figure><p>To sign the newly added to-do item automatically with the currently logged-in users’ id, change the <strong>addUser </strong>mutation like below. In the <strong>schema/models/index.js </strong>change it like that:</p><pre>addTodo: (todo) =&gt;</pre><pre>  !user</pre><pre>    ? null</pre><pre>      : new Promise((resolve, reject) =&gt;</pre><pre>        new Todo(</pre><pre>          Object.assign({}, { ...todo }, { owner_id: user._id })</pre><pre>        ).save((err, todo) =&gt; (err ? reject(err) : resolve(todo)))</pre><pre>      ),</pre><p>…and in the <strong>schema/resolvers/index.js </strong>change it like that:</p><pre>addUser: async (parent, args, context) =&gt;</pre><pre>  await context.models.Todo.mutations.addUser(</pre><pre>    JSON.parse(JSON.stringify(args.user))</pre><pre>  ),</pre><p>Finally, change the input definition in the <strong>schema/typeDefs/index.js </strong>like that:</p><pre>input TodoInput {</pre><pre>  title: String</pre><pre>  mission: String</pre><pre>  isDone: Boolean</pre><pre>}</pre><h3><strong>Conclusion</strong></h3><p>User authentication and authorization are core concepts for nearly every application. I tried to explain how these concepts can be implied to an Apollo Server. For checkout other further configurations, you can clone the <a href="https://github.com/ardaorkin/todo-app-server"><strong>repo</strong></a><strong>.</strong></p><p>We are going to create an Apollo Client with React in the next episode.</p><p>Thank you for your interest.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b56167d8c19e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Todo App With GraphQL, Express.js & Redux — Episode 1]]></title>
            <link>https://ardaorkin.medium.com/todo-app-with-graphql-express-js-redux-episode-1-ccbe54b40c89?source=rss-4ac7b9d750f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccbe54b40c89</guid>
            <category><![CDATA[apollo]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Arda Örkin]]></dc:creator>
            <pubDate>Mon, 03 May 2021 00:41:07 GMT</pubDate>
            <atom:updated>2021-11-07T20:16:26.890Z</atom:updated>
            <content:encoded><![CDATA[<h3>Todo App With GraphQL, Express.js And React — Episode 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*nkG4MeJ05GClnO2Xx0UQ0Q.png" /></figure><h3>Building Basic API</h3><p>Welcome. Making API calls and render the responses on a web page is fun. But, creating an API and querying it is wonderful! Besides, creating an API allows us to gain more insight into how APIs work, what is the logic behind them, and what is going on in the back-end when an API call is received. So if you feel that you have done enough making API calls so far in your projects, and you decided to deep down to understand the whole process of any application, I can say that this article may help you.</p><p>We are going to build a todo application in this project. We will use these technologies:</p><ul><li>Express.js</li><li>GraphQL</li><li>Apollo</li><li>Mongo</li><li>React</li></ul><p>Our project structure is going to be like shown on the below graphic:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xHjiqP0ijRUT2hRUJccyZg.png" /></figure><p>This series of articles is planned to consist of 3 episodes. These episodes will have these headers:</p><ul><li>Build basic API</li><li>Build user authentication</li><li>Render and manipulate data on front-end</li></ul><p>In this episode, we are going to build a basic API. It will contain one query to get Todo items and three mutations to create items, modify and delete them.</p><p>Here is the final code of <a href="https://github.com/ardaorkin/todo-app-server">this episode</a>.</p><p>Ready? Let’s go then!</p><h4>Requirements</h4><ul><li>NodeJS 14v+</li><li>NPM or YARN</li><li>NPX</li><li>React Developer Tools</li><li>Apollo Client Devtools</li></ul><h4>Building Development Environment</h4><p>Create a folder named <strong>todo-app </strong>and create two more folders in the <strong>todo-app </strong>folder, named <strong>server </strong>and <strong>client</strong>.</p><p>Open the <strong>todo-app/server </strong>folder in a code editor and run this command to build a NodeJS project and install dependencies:</p><pre>npm init -y &amp;&amp; npm i express apollo-server-express graphql mongoose dotenv cors &amp;&amp; npm i --save-dev nodemon @babel/core @babel/node @babel/preset-env babel-loader</pre><p>Now create your back-end project structure like shown in the below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/1*kaWZsTRe8IYqD_jhNLFVyA.png" /><figcaption>package.json, package-lock.json files, and node_modules directory will be created automatically as you install project dependencies. So you don’t need to create them manually.</figcaption></figure><p>After creating all files and directories, open up the .babelrc file and write these lines into it:</p><pre>{</pre><pre>&quot;presets&quot;: [&quot;@babel/env&quot;]</pre><pre>}</pre><p>The configuration we made in the .babelrc file is going to provide us to use ES6 while module importing.</p><p>Before going further on server configuration, let’s create a MongoDB cloud account.</p><h4>MongoDB Configuration</h4><p>To configure MongoDB, let’s create an account in <a href="https://www.mongodb.com/cloud">mongodb.com/cloud</a>. Later on create an organization, a project in the organization, and a cluster in the project. After the cluster is created, in the page where the cluster is in, click Database Access. Click ADD NEW DATABASE USER choice there and create a database user. Later on, click the Cluster option on the left bar. On the opened page, click the Connect button. In the Setup connection security step, choose Allow anywhere option and click Choose a connection method. Then let’s click the Connect your application option and copy the connection information under <strong>Add your connection string into your application code</strong>.<strong> </strong>Let’s go back to the text editor, and create a variable named MONGODB_URL in the .env file and assign the MongoDB connection information to the variable. Change with the password just created in the Database Access step and change the <strong>myFirstDatabase</strong> as <strong>todolist</strong>:</p><pre>MONGODB_URL=&quot;mongodb+srv://username:12345@cluster0.mjh9d.mongodb.net/todolist?retryWrites=true&amp;w=majority&quot;</pre><p>Now, open up the <strong>db/connection/index.js </strong>file, and write these lines down:</p><pre>import dotenv from &quot;dotenv&quot;;</pre><pre>import mongoose from &quot;mongoose&quot;;</pre><pre>dotenv.config();</pre><pre>const dbConnection = () =&gt;</pre><pre>  new Promise((resolve, reject) =&gt; {</pre><pre>    mongoose.connect(process.env.MONGODB_URL, {</pre><pre>      useNewUrlParser: true,</pre><pre>      useUnifiedTopology: true,</pre><pre>      useFindAndModify: false,</pre><pre>    });</pre><pre>  const db = mongoose.connection;</pre><pre>  db.on(&quot;error&quot;, () =&gt; {</pre><pre>    console.error.bind(console, &quot;connection error:&quot;);</pre><pre>      reject(</pre><pre>        new Error(</pre><pre>          &quot;Connection error has occurred when trying to connect to the database!&quot;</pre><pre>      )</pre><pre>    );</pre><pre>  });</pre><pre>  db.once(&quot;open&quot;, () =&gt; resolve(&quot;🚀 Successful database connection.&quot;));</pre><pre>});</pre><pre>export default dbConnection;</pre><p>By this configuration, we define the connection information of our MongoDB and we provide a promise function that can be used anywhere in the project. It is a good idea to create Promise functions, and add them error handling lines, as much as we can when coding a backend project with JavaScript.</p><p>Later on, open up the <strong>db/models/TodoModel.js </strong>file and fill it with these lines:</p><pre>import mongoose from &quot;mongoose&quot;;<br></pre><pre>const todoSchema = new mongoose.Schema({</pre><pre>  user: String,</pre><pre>  title: String,</pre><pre>  mission: String,</pre><pre>  isDone: Boolean,</pre><pre>},</pre><pre>{ timestamps: true });</pre><pre>const Todo = mongoose.model(&quot;Todo&quot;, todoSchema);</pre><pre>export default Todo;</pre><p>Now we have created the schema of our collection which will place on the database and reproduced a model from the schema. Let’s continue with server configuration, and run the server to connect to the database.</p><h4>Server Configuration</h4><p>Below we have created the MongoDB configuration. Now, let’s use it!</p><p>Open up the <strong>server.js </strong>file and write these lines to it:</p><pre>import express from &quot;express&quot;;</pre><pre>import dbConnection from &quot;./db/connection&quot;;</pre><pre>const startServer = async () =&gt; {</pre><pre>  await dbConnection()</pre><pre>    .then((result) =&gt; console.log(result))</pre><pre>    .catch((err) =&gt; console.log(err));</pre><pre>  const app = express();</pre><pre><br>  app.use(&quot;/&quot;, (req, res) =&gt; res.send(&quot;Welcome to Todo App&quot;));</pre><pre>app.listen(4000, () =&gt; console.log(`🚀 Server listening on port 4000`));</pre><pre>};</pre><pre>startServer();</pre><p>Now open the <strong>package.json</strong> file and write this line into the script section:</p><pre>&quot;start&quot;: &quot;nodemon ./server --exec babel-node -e js&quot;,</pre><p>After writing the start script, your <strong>package.json</strong>’s scripts section should look like this:</p><pre>&quot;scripts&quot;: {</pre><pre>  &quot;start&quot;: &quot;nodemon ./server --exec babel-node -e js&quot;,</pre><pre>  &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;</pre><pre>},</pre><p>Open up a console and run the server with this command:</p><pre>npm start</pre><p>If you see these two messages on the output of the terminal, it means you made configurations successfully:</p><pre>🚀 Successful database connection.<br>🚀 Server listening on port 4000</pre><p>It is time to build GraphQL schema and run Apollo server!</p><h4>Building GrapQL Schema &amp; Apollo Server</h4><p>To build a GraphQL structure, it is a good idea to start with creating type definitions. To do it, open the <strong>schema/typeDefs/index.js</strong> file and write these lines:</p><pre>import { gql } from &quot;apollo-server-express&quot;;</pre><pre>const typeDefs = gql`</pre><pre>  type Todo {</pre><pre>    user: String</pre><pre>    title: String</pre><pre>    mission: String</pre><pre>    createdAt: String</pre><pre>    updatedAt: String</pre><pre>    isDone: Boolean</pre><pre> }</pre><pre>  input TodoInput {</pre><pre>    user: String</pre><pre>    title: String</pre><pre>    mission: String</pre><pre>    isDone: Boolean</pre><pre>  }</pre><pre>  type Query {</pre><pre>    getTodoList: [Todo]</pre><pre>  }</pre><pre>  type Mutation {</pre><pre>    addTodo(todo: TodoInput): Todo</pre><pre>  }`;<br></pre><pre>export default typeDefs;</pre><p>This way we have defined a Todo type that is parallel with the database collection schema, an input type that is also parallel with both the Todo type and the Todo schema. We have also defined built-in GraphQL types: Query and Mutation. We will define a <strong>resolver</strong> object and we will use the same property name for the Query and Mutation types in it; additionally, we are going to assign MongoDB query functions to the properties in the <strong>resolver</strong> object. We are going to write the query functions into models. Later we will merge the type definitions, resolvers, and models in the Apollo Server configuration, and in this way, we will build the relationship between the <strong>type definitions, </strong>the <strong>resolvers, </strong>and the <strong>models</strong>.</p><p>Now, let’s create the models. To do it open up the <strong>schema/models/index.js</strong> file and write these lines down into it:</p><pre>import Todo from &quot;../../db/models/TodoModel&quot;;</pre><pre>const generateTodoModel = () =&gt; ({</pre><pre>queries: {</pre><pre>  getAll: () =&gt;</pre><pre>    new Promise(</pre><pre>      async (resolve, reject) =&gt;</pre><pre>        await Todo.find({}, (err, todo) =&gt;</pre><pre>          err ? reject(err) : resolve(todo)</pre><pre>      )<br>    ),</pre><pre>  },</pre><pre>  mutations: {</pre><pre>    addTodo: (todo) =&gt;</pre><pre>      new Promise((resolve, reject) =&gt;</pre><pre>        new Todo(todo).save((err, todo) =&gt; (err ? reject(err) : resolve(todo)))</pre><pre>      ),</pre><pre>  },</pre><pre>});</pre><pre>export default generateTodoModel;</pre><p>In this way, we have created the query functions which will be executed on the Todo model we imported, and assign those functions to the model placed in the GraphQL schema we created. Later, in the resolver object, we will call these functions via context object which is defined in the Apollo server, and assign them to properties as values. For now, let’s create the resolver object and assign console.log() functions to the properties. To do that, open the <strong>schema/resolvers/index.js</strong> and write these lines into it:</p><pre>const resolvers = {</pre><pre>  Query: {</pre><pre>    getTodoList: async (parent, args, context) =&gt;</pre><pre>      console.log(JSON.parse(JSON.stringify(args.todo)), context)</pre><pre>  },</pre><pre>  Mutation: {</pre><pre>    addTodo: async (parent, args, context) =&gt;</pre><pre>      console.log(JSON.parse(JSON.stringify(args.todo)), context)</pre><pre>  },</pre><pre>};</pre><pre>export default resolvers;</pre><p>Now, we have created the <strong>type definitions</strong>,<strong> </strong>the <strong>resolvers</strong>,<strong> </strong>and the <strong>models</strong>. It is time to create the Apollo Server configuration and build the relation with those GraphQL elements. To achieve this, open up the <strong>server.js file </strong>and change it like that:</p><pre>import express from &quot;express&quot;;</pre><pre>import { ApolloServer } from &quot;apollo-server-express&quot;;</pre><pre>import typeDefs from &quot;./schema/typeDefs&quot;;</pre><pre>import resolvers from &quot;./schema/resolvers&quot;;</pre><pre>import generateTodoModel from &quot;./schema/models&quot;;</pre><pre>import dbConnection from &quot;./db/connection&quot;;</pre><pre>import cors from &quot;cors&quot;<br></pre><pre>const startApolloServer = async () =&gt; {</pre><pre>  await dbConnection()</pre><pre>    .then((result) =&gt; console.log(result))</pre><pre>    .catch((err) =&gt; console.log(err));</pre><pre>  const app = express();<br>  app.use(cors())</pre><pre>  const server = new ApolloServer({</pre><pre>    typeDefs,</pre><pre>    resolvers,</pre><pre>    subscriptions: { path: &quot;/subscriptions&quot; },</pre><pre>    context: ({ req }) =&gt; {</pre><pre>      return {</pre><pre>        models: {</pre><pre>          Todo: generateTodoModel(),</pre><pre>        },</pre><pre>      };</pre><pre>    },</pre><pre>  });</pre><pre>  await server.start();</pre><pre>  server.applyMiddleware({ app });</pre><pre>  app.use((req, res) =&gt; {</pre><pre>    res.status(200);</pre><pre>    res.send(&quot;Welcome Todo App&quot;);</pre><pre>    res.end();</pre><pre>  });<br></pre><pre>  await new Promise((resolve) =&gt; app.listen({ port: 4000 }, resolve));</pre><pre>  console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`);</pre><pre>  console.log(</pre><pre>`🚀 Subscriptions ready at ws://localhost:4000${server.subscriptionsPath}`</pre><pre>  );</pre><pre>  return { server, app };</pre><pre>};</pre><pre>startApolloServer();</pre><p>As you can see, we build the Apollo Server and create the relation between the <strong>type definitions</strong>, the <strong>resolvers</strong>, and the <strong>models</strong> in it. Now, check out the terminal where you ran the npm start command before. If you see these messages on the output of the terminal…</p><pre>🚀 Successful database connection.<br>🚀 Server ready at <a href="http://localhost:4000/graphql">http://localhost:4000/graphql</a><br>🚀 Subscriptions ready at <a href="http://localhost:4000/subscriptions">ws://localhost:4000/subscriptions</a></pre><p>…congratulations, you have an Apollo Server running on successfully!</p><p>Do you see the <strong>context</strong> function in the Apollo Server configuration? It takes the <strong>req </strong>object from the <strong>express server </strong>as a parameter. It doesn’t use it now, however. Anyway, the more important thing is to see what the <strong>context </strong>function returns — it returns the models we defined in the GraphQL Schema!</p><p>Now, in the resolvers, let’s call the functions which are defined in models. Remember, we just logged to the console the query elements so far. Instead of just logging things to the console, let’s run a real database query via the resolvers. To do it, open up the <strong>schema/resolvers/index.js </strong>and change it like that:</p><pre>const resolvers = {</pre><pre>  Query: {</pre><pre>    getTodoList: async (parent, args, context) =&gt;</pre><pre>      await context.models.Todo.queries.getAll(),</pre><pre>  },</pre><pre>  Mutation: {</pre><pre>    addTodo: async (parent, args, context) =&gt;</pre><pre>      await context.models.Todo.mutations.addTodo(</pre><pre>        JSON.parse(JSON.stringify(args.todo))</pre><pre>      ),</pre><pre>  },</pre><pre>};</pre><pre>export default resolvers;</pre><p>With this configuration, we have been able to run the MongoDB queries using GraphQL query language. To run a real query, open <a href="http://localhost:4000/graphql">http://localhost:4000/graphql</a> address in a browser and run a mutation which will create a new todo, like that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bffSJLcj_36meD8kCrhkaQ.png" /></figure><p>If you see the <strong>data </strong>object, it means you have done the right configuration and you have added a todo object to the MongoDB. To be sure, check the MongoDB collection. Click the Collections tab in the Cluster page in the MongoDB Cloud. On the page that came up, click the collection named <strong>todo</strong> under the database named <strong>todolist</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MzgqO5awgUlXAELQBFH8vA.png" /></figure><p>So far, we have added one Query resolver and one Mutation resolver. Let’s add two more Mutation resolvers to modify and delete the todo item. Todo that, open the <strong>schema/models/index.js </strong>file, and write these to function into the <strong>mutations </strong>object:</p><pre>modifyItem: (body) =&gt;</pre><pre>  new Promise(</pre><pre>    async (resolve, reject) =&gt;</pre><pre>      await Todo.findByIdAndUpdate(body.id, body.query, (err, todo) =&gt;</pre><pre>        err ? reject(err) : resolve(todo)</pre><pre>        )</pre><pre>  ),</pre><pre>  deleteItem: (id) =&gt;</pre><pre>    new Promise(</pre><pre>      async (resolve, reject) =&gt;</pre><pre>        await Todo.findByIdAndDelete(id, (err, todo) =&gt;</pre><pre>          err ? reject(err) : resolve(todo)</pre><pre>        )</pre><pre>   ),</pre><p>Then go to the <strong>schema/resolvers/index.js </strong>file and write these line into the <strong>Mutations</strong>:</p><pre>modifyItem: async (parent, args, context) =&gt;</pre><pre>  await context.models.Todo.mutations.modifyItem(</pre><pre>    JSON.parse(JSON.stringify(args))</pre><pre>  ),</pre><pre>deleteItem: async (parent, args, context) =&gt;</pre><pre>  await context.models.Todo.mutations.deleteItem(</pre><pre>    JSON.parse(JSON.stringify(args.id))</pre><pre>  ),</pre><p>Finally, go to the <strong>schema/typeDefs/index.js </strong>file and write these lines into the <strong>Mutations </strong>type:</p><pre>modifyItem(id: ID!, query: TodoInput): Todo</pre><pre>deleteItem(id: ID!): Todo</pre><p>Now, open <a href="http://localhost:4000/graphql">http://localhost:4000/graphql</a> in the browser. And run the <strong>GetTodos </strong>query:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IeMc3zSJ-DZoMWxjZI1RkA.png" /></figure><p>Copy the <strong>_id </strong>property from returned value, open a new tab on the Apollo playground and run a <strong>ModifyItem</strong> mutation like that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4BG3xSblv3QwBIjAhThcjQ.png" /></figure><p>See the <strong>updatedAt </strong>and <strong>isDone</strong> property has changed. In MongoDB connection configurations, we provided the updateAt property to change in every update action, and we have changed the <strong>isDone </strong>with a query ran on the Apollo server. Let’s run a delete query. Open a new tab in the playground and run a delete query like that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r-Bzdsdc_-8Sj7uefN4oQw.png" /></figure><p>And that’s it! We have an API on which we can run GraphQL queries, we have a NoSQL database and we have an Apollo Server which integrated with express.js. Well done!</p><p>Next time we are going to reproduce JSON Web Token based on API calls and make user authentication and authorization configurations on Apollo Server!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccbe54b40c89" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parcel Tracking Application With RabbitMQ]]></title>
            <link>https://ardaorkin.medium.com/parcel-tracking-application-with-rabbitmq-1e022b2ff190?source=rss-4ac7b9d750f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e022b2ff190</guid>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[socketio]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Arda Örkin]]></dc:creator>
            <pubDate>Mon, 19 Apr 2021 09:40:48 GMT</pubDate>
            <atom:updated>2021-05-03T19:58:34.052Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j-T3fET2B1bZ0rr7Kdw2NA.png" /></figure><p>In the development process, besides specify which technologies are going to be used, it is important to determine how the project architecture is going to be. These days, the most common project architecture is microservice architecture. One of the basic features of the microservice architecture is that every service can be deployed separately. Thanks to this feature, every single service can use a different protocol(s) in the project. It means a project can contain both HTTP, AMQP, and WS connection protocols.</p><p>In this article, we are going to build a service that uses both HTTP, AMQP, and WS. In this service we are going to use these technologies:</p><ul><li>Express.js</li><li>MongoDB</li><li><a href="http://socket.io/">Socket.IO</a></li><li>RabbitMQ</li><li>ReactJS</li></ul><p>We will use the Express.js library to handle HTTP requests. When HTTP requests are received we will execute <em>publishers</em> which publish a message about the event to the RabbitMQ message broker. We will also create consumers to listen to the messages which are sent to the RabbitMQ message broker by the publishers, and save them to the MongoDB database. At last, we will use <a href="http://socket.io/">Socket.IO</a> in order to track every change in MongoDB and to provide rendering those changes in the frontend built by using React, without refreshing the page.</p><p>Here is the final code of the <a href="https://github.com/ardaorkin/rabbitmq-parcel-tracking.git">project</a></p><h3>Requirements</h3><ul><li>NodeJS 12v+</li></ul><h3>Building Development Environment</h3><h3>Server</h3><ul><li>First of all, let’s create a folder called parcel-tracking-system. In that folder, let’s create one more folder called server. Then open up a terminal and go to the directory where our server folder in you just created and run npm init -y.</li></ul><p>Then go back again to the terminal and to install project dependencies run this command in the directory where the folder named server is in:</p><pre>npm i express dotenv tortoise mongoose socket.io nodemon</pre><p>To ensure that command was executed successfully and packages were installed both look at the message returned in the terminal and open up the package.json file and look dependencies section.</p><p>Also, let’s install development environment dependencies:</p><p>npm i --save-dev @babel/core @babel/preset-env babel-loader</p><p>Later on, create a file named .babelrc and write this code in it:</p><pre>{                                        <br>    &quot;presets&quot;: [&quot;@babel/env&quot;]                                        <br>}</pre><p>Now let’s create one more file named server.js and write this code in it:</p><pre>//server.js</pre><pre>import express from &quot;express&quot;              </pre><pre>const app = express()              </pre><pre>app.use(&quot;/&quot;, (req, res) =&gt; {                </pre><pre>res.send(&quot;Welcome to parcel tracking system&quot;)              </pre><pre>})              </pre><pre>app.listen(8000, () =&gt; console.log(`Server listening on 8000`))</pre><p>Execute server.js with this command:</p><pre>nodemon ./server --exec babel -e js</pre><p>After the execution, open <a href="http://localhost:3000/">localhost:3000</a> in a browser. If the “Welcome to parcel tracking system” message comes up on the page, it means Express.js installation has successfully ended.</p><h3>Publisher and Consumer Creation</h3><p>In these steps, we are going to create our first publisher and consumer. Publisher will publish a message, send it to <em>exchange</em> where is in RabbitMQ message broker and the <em>exhange</em> will send the message to the message queue and the <em>consumer</em> which listens to the messages which are it cares in the queue, will take the message and will do what we want to do.</p><p>For now, we will log to the console the message which we get via the consumer. To do that let’s create two folders named publisher and consumer under the folder called server. In the publisher folder, create a file named shippingPublihser.js and in the consumer folder, create a file named shippingConsumer.js.</p><p>Write this code down to the shippingPublihser.js file:</p><pre>//shippingPublisher.js</pre><pre>import Tortoise from &quot;tortoise&quot;          <br>import dotenv from &quot;dotenv&quot;;          <br>dotenv.config()          </pre><pre>const tortoise = new Tortoise(process.env.AMQP_URL)    <br>        tortoise      <br>            .exchange(&quot;parcel-tracking&quot;, &quot;topic&quot;, { durable: false })      <br>            .publish(&quot;parcel.shipping&quot;, { name: &quot;test&quot;, status: &quot;shipping&quot; });</pre><p>Now, let’s write the consumer which is going to take the message which is sent to the message broker by the publisher. To do this write this code down to the shippingConsumer.js file:</p><pre>//shippingConsumer.js</pre><pre>import Tortoise from &quot;tortoise&quot;                            <br>import dotenv from &quot;dotenv&quot;;                            <br>dotenv.config()                            </pre><pre>const tortoise = new Tortoise(process.env.AMQP_URL)                            </pre><pre>tortoise  <br>    .queue(&quot;&quot;, { durable: false })  <br>    .exchange(&quot;parcel-tracking&quot;, &quot;topic&quot;, &quot;*.shipping&quot;, { durable: false })  <br>    .prefetch(1)  <br>    .json()  <br>    .subscribe((msg, ack, nack) =&gt; {    <br>        console.log(msg)    <br>        ack();  <br>    });</pre><p>We can prefer to install RabbitMQ on our local machine but in that case, the installation steps would be different from the operating system to the operating system and we would need to mess with some network settings. Therefore, we make this step with <a href="http://cloudamqp.com/">cloudamqp.com</a>. To do that let’s create <a href="https://cloudamqp.com/">cloudamqp.com</a>. Later on, click on the button Create New Instance and create a new message broker instance. We can name the instance as we wish. To free plan, choose the Little Lemur option. Then press the buttons named Select Region &gt; Review &gt; Create Instance respectively. Go to the <a href="https://customer.cloudamqp.com/instance">page</a> where message brokers are listed and click on the name of the message broker instance we just created. Copy the value of AMQP URL in the Details section where is in the page came up. After applying these steps, go back to the server folder is in and creates a file named .env. Write these lines down in this .env file:</p><pre>AMQP_URL=&quot;&lt;copied_amqp_url&gt;&quot;</pre><p>By this process, we create an AQMP service. Now it is time to run our publisher and consumer. To do this, in two separate terminals, run these commands respectively:</p><pre>nodemon ./consumers/shippingConsumer --exec babel-node -e js          <br>nodemon ./publishers/shippingPublisher --exec babel-node -e js</pre><p>After applying these steps, we should see this message in the terminal where shippingConsumer.js is running:</p><pre>{ name: &#39;test&#39;, status: &#39;shipping&#39; }</pre><p>At this time we have a working service! This service is using AMQP as a communication protocol. The service has two ends; one is a publisher, and the other is a consumer. The publisher sends a message to the message broker after this process publisher’s job is done and it doesn’t wait for any reply. The consumer just cares about what the message header includes. In that case, the consumer cares about messages which have <em>shipping</em> statement in their header. There are nothing consumer needs except the message header.</p><p>In the next step, we are going to publish messages when an HTTP request is received.</p><h3>Handling HTTP Requests</h3><p>Let’s create two more each publisher and consumer. Again to the server folder. Create these files in the publishers folder:</p><ul><li>onroadPublisher.js</li><li>deliveredPublisher.js</li></ul><p>And create these files in the consumers folder:</p><ul><li>onroadConsumer.js</li><li>deliveredConsumer.js</li></ul><p>Now we are going to write all publisher files as <em>Promises</em>:</p><pre>//shippingPublisher.js</pre><pre>import Tortoise from &quot;tortoise&quot;;            <br>import dotenv from &quot;dotenv&quot;;            <br>dotenv.config();            </pre><pre>const tortoise = new Tortoise(process.env.AMQP_SERVER);            </pre><pre>const shippingPublisher = (name) =&gt;              <br>    new Promise((resolve, reject) =&gt; {                <br>        tortoise                  <br>            .exchange(&quot;parcel-tracking&quot;, &quot;topic&quot;, { durable: false })                  <br>            .publish(&quot;parcel.shipping&quot;, { name, status: &quot;shipping&quot; });                  <br>        resolve({ name, status: &quot;shipping&quot; });              <br>});            </pre><pre>export default shippingPublisher;</pre><pre>//onroadPublisher.js</pre><pre>import Tortoise from &quot;tortoise&quot;;            <br>import dotenv from &quot;dotenv&quot;;            <br>dotenv.config();            </pre><pre>const tortoise = new Tortoise(process.env.AMQP_SERVER);            </pre><pre>const onroadPublisher = (name) =&gt;              <br>    new Promise((resolve, reject) =&gt; {                <br>        tortoise                  <br>            .exchange(&quot;parcel-tracking&quot;, &quot;topic&quot;, { durable: false })                  <br>            .publish(&quot;parcel.onroad&quot;, { name, status: &quot;onroad&quot; });                  <br>        resolve({ name, status: &quot;onroad&quot; });              <br>});            </pre><pre>export default onroadPublisher;</pre><pre>//deliveredPublisher.js</pre><pre>import Tortoise from &quot;tortoise&quot;;            <br>import dotenv from &quot;dotenv&quot;;            <br>dotenv.config();            </pre><pre>const tortoise = new Tortoise(process.env.AMQP_SERVER);            </pre><pre>const deliveredPublisher = (name) =&gt;              <br>    new Promise((resolve, reject) =&gt; {                <br>        tortoise                  <br>            .exchange(&quot;parcel-tracking&quot;, &quot;topic&quot;, { durable: false })                  <br>            .publish(&quot;parcel.delivered&quot;, { name, status: &quot;delivered&quot; });                  <br>        resolve({ name, status: &quot;delivered&quot; });              <br>});            </pre><pre>export default deliveredPublisher;</pre><p>Later on, let’s code consumers:</p><pre>//shippingConsumer.js</pre><pre>import Tortoise from &quot;tortoise&quot;;            <br>import dotenv from &quot;dotenv&quot;;            <br>dotenv.config();            </pre><pre>const tortoise = new Tortoise(process.env.AMQP_SERVER);            <br>tortoise              <br>    .queue(&quot;&quot;, { durable: false })              <br>    .exchange(&quot;parcel-tracking&quot;, &quot;topic&quot;, &quot;*.shipping&quot;, { durable: false })              <br>    .prefetch(1)              <br>    .json()              <br>    .subscribe((msg, ack, nack) =&gt; {                <br>        console.log(msg)                <br>    ack();              <br>    });</pre><pre>//onroadConsumer.js</pre><pre>import Tortoise from &quot;tortoise&quot;;            <br>import dotenv from &quot;dotenv&quot;;            <br>dotenv.config();            </pre><pre>const tortoise = new Tortoise(process.env.AMQP_SERVER);            <br>tortoise              <br>    .queue(&quot;&quot;, { durable: false })              <br>    .exchange(&quot;parcel-tracking&quot;, &quot;topic&quot;, &quot;*.onroad&quot;, { durable: false })              <br>    .prefetch(1)              <br>    .json()              <br>    .subscribe((msg, ack, nack) =&gt; {                <br>        console.log(msg)                <br>    ack();              <br>    });</pre><pre>//deliveredConsumer.js</pre><pre>import Tortoise from &quot;tortoise&quot;;            <br>import dotenv from &quot;dotenv&quot;;            <br>dotenv.config();            </pre><pre>const tortoise = new Tortoise(process.env.AMQP_SERVER);            <br>tortoise              <br>    .queue(&quot;&quot;, { durable: false })              <br>    .exchange(&quot;parcel-tracking&quot;, &quot;topic&quot;, &quot;*.delivered&quot;, { durable: false })              <br>    .prefetch(1)              <br>    .json()              <br>    .subscribe((msg, ack, nack) =&gt; {                <br>        console.log(msg)                <br>    ack();              <br>    });</pre><p>After these configurations, as the server receives HTTP requests, publishers will be executed and as these publishers send messages to the message broker, our consumers are going to listen to these messages.</p><p>Now let’s create HTTP routes. For the sake of best practice and clean code create a folder named routes under the server folder and create a file named index.js in it. Later write these lines down to the index.js file:</p><pre>//index.js</pre><pre>import { Router } from &quot;express&quot;;            <br>import shippingPublishers from &quot;../publishers/shippingPublisher&quot;;            <br>import onroadPublisher from &quot;../publishers/onroadPublisher&quot;;            <br>import deliveredPublisher from &quot;../publishers/deliveredPublisher&quot;;            </pre><pre>const router = Router();            </pre><pre>router.get(&quot;/&quot;, (req, res) =&gt; {              <br>    res.send(&quot;Welcome to parcel-tracking system&quot;);            <br>});            </pre><pre>router.get(&quot;/shipping/:name&quot;, async (req, res, next) =&gt; {              <br>    const name = req.params.name;              <br>    await shippingPublishers(name).then((message) =&gt; res.json(message));            <br>});            </pre><pre>router.get(&quot;/onroad/:name&quot;, async (req, res, next) =&gt; {              <br>    const name = req.params.name;              <br>    await onroadPublisher(name).then((message) =&gt; res.json(message));            <br>});            </pre><pre>router.get(&quot;/delivered/:name&quot;, async (req, res, next) =&gt; {              <br>    const name = req.params.name;              <br>    await deliveredPublisher(name).then((message) =&gt; res.json(message));            <br>});            </pre><pre>export default router;</pre><p>After creating HTTP routes, let’s modify all server.js file like that:</p><pre>//server.js</pre><pre>import express from &quot;express&quot;;<br>import router from &quot;./routes&quot;;            </pre><pre>const app = express();<br>const port = process.env.PORT || 8000;</pre><pre>app.use(router);</pre><pre>app.listen(port, () =&gt; console.log(`Server listening on port ${port}`));</pre><p>Later on, go to under the server folder and run these commands:</p><pre>nodemon ./server --exec babel-node -e js            <br>nodemon ./consumers/shippingConsumer --exec babel-node -e js            <br>nodemon ./consumers/onroadConsumer --exec babel-node -e js            <br>nodemon ./consumers/deliveredConsumer --exec babel-node -e js</pre><p>After all, commands run, open these links up in a browser respectively:</p><ul><li><a href="http://localhost:8000/shipping/test">localhost:8000/shipping/test</a></li><li><a href="http://localhost:8000/onroad/test">localhost:8000/onroad/test</a></li><li><a href="http://localhost:8000/delivered/test">localhost:8000/delivered/test</a></li></ul><p>As we open up the links, we should see messages which go to the message broker, in the terminal in JSON format.</p><p>After seeing both the terminal where consumers are running on and the JSON data which are returned in the browser, we can be sure that both publishers and consumers are running as the server receives HTTP requests.</p><p>In the next step, we are going to save the messages to MongoDB.</p><h3>MongoDB Configuration</h3><p>To configure MongoDB, let’s create an account in <a href="https://www.mongodb.com/cloud">mongodb.com/cloud</a>. Later on create an organization, a project in the organization, and a cluster in the project. After the cluster is created, in the page where the cluster is in, click Database Access. Click ADD NEW DATABASE USER choice there and create a database user. Later on, click the Cluster option on the left bar. On the opened page, click the Connect button. In Setup connection security step, choose Allow anywhere option and click Choose a connection method. Then let’s click the Connect your application option and copy the connection information under Add your connection string into your application code. Let’s go back to the text editor and create a variable named MONGODB_URL in the .env file and assign the MongoDB connection information to the variable. Change with the password just created in Database Access step and change myFirstDatabase as parceltracking:</p><pre>MONGODB_URL=&quot;mongodb+srv://username:12345@cluster0.mjh9d.mongodb.net/parceltracking?retryWrites=true&amp;w=majority&quot;</pre><p>After these steps, go to server.js file and write down these lines just after the line where the routes folder is imported:</p><pre>//server.js</pre><pre>import mongoose from &quot;mongoose&quot;<br>import dotenv from &quot;dotenv&quot;<br>dotenv.config()              <br>mongoose.connect(process.env.MONGODB_URL, {              <br>    useNewUrlParser: true,              <br>    useUnifiedTopology: true,            <br>});            </pre><pre>const db = mongoose.connection;            <br>db.on(&quot;error&quot;, console.error.bind(console, &quot;connection error:&quot;));            <br>db.once(&quot;open&quot;, () =&gt; console.log(&quot;Connected to database&quot;));</pre><p>With these lines, we opened up a MongoDB connection. To be sure that everything is okay, let’s run server.js with this command:</p><pre>nodemon ./server --exec babel-node -e js</pre><p>If we see the message Connected to database in the console of our terminal, it means we did the database configuration correctly. In the next step, we are going to create a MongoDB schema and model. To do that, let’s create a folder named model in the server folder. In the model folder, create a file named Tracking.js and write this code down:</p><pre>//Tracking.js</pre><pre>import mongoose from &quot;mongoose&quot;;</pre><pre>const trackingSchema = new mongoose.Schema({              <br>    name: String,              <br>    status: String,            <br>});            </pre><pre>const Track = mongoose.model(&quot;Track&quot;, trackingSchema);            </pre><pre>export default Track;</pre><p>After creating the model, we will use it for consumers. But while we use the save() method from the mongoose library, the updateOne() method is going to be used in other consumers. First of all, let’s modify the shippinConsumer.js file like that:</p><pre>//shippingConsumer.js</pre><pre>import Tortoise from &quot;tortoise&quot;;            <br>import mongoose from &quot;mongoose&quot;            <br>import Track from &quot;../model/Tracking&quot;;            <br>import dotenv from &quot;dotenv&quot;            <br>dotenv.config()                          <br>mongoose.connect(process.env.MONGODB_URL, {                          <br>    useNewUrlParser: true,                          <br>    useUnifiedTopology: true,                        <br>});                        </pre><pre>const db = mongoose.connection;                        <br>db.on(&quot;error&quot;, console.error.bind(console, &quot;connection error:&quot;));                        <br>db.once(&quot;open&quot;, () =&gt; console.log(&quot;Connected to database&quot;));            </pre><pre>const tortoise = new Tortoise(process.env.AMQP_SERVER);            <br>tortoise              <br>    .queue(&quot;&quot;, { durable: false })              <br>    .exchange(&quot;parcel-tracking&quot;, &quot;topic&quot;, &quot;*.shipping&quot;, { durable: false })              <br>    .prefetch(1)              <br>    .json()              <br>    .subscribe((msg, ack, nack) =&gt; {                <br>        const newParcel = new Track(msg);                <br>        newParcel.save((err, parcel) =&gt; {                  <br>            if (err) throw err;                  <br>            console.log(&quot;shipped parcel:&quot;, parcel);                  <br>            return parcel;                  <br>        });                <br>        ack();              <br>    });</pre><p>In this way, shippinConsumer.js will create a new record in MongoDB. Now, it is time to update this record. To do that let’s modify onroadConsumer and deliveredConsumer like that:</p><pre>//onroadConsumer.js</pre><pre>import Tortoise from &quot;tortoise&quot;;              <br>import mongoose from &quot;mongoose&quot;              <br>import Track from &quot;../model/Tracking&quot;;              <br>import dotenv from &quot;dotenv&quot;              <br>dotenv.config()                            <br>mongoose.connect(process.env.MONGODB_URL, {                            <br>    useNewUrlParser: true,                            <br>    useUnifiedTopology: true,                          <br>});                          </pre><pre>const db = mongoose.connection;                          <br>db.on(&quot;error&quot;, console.error.bind(console, &quot;connection error:&quot;));                          <br>db.once(&quot;open&quot;, () =&gt; console.log(&quot;Connected to database&quot;));            </pre><pre>const tortoise = new Tortoise(process.env.AMQP_SERVER);            <br>tortoise              <br>    .queue(&quot;&quot;, { durable: false })              <br>    .exchange(&quot;parcel-tracking&quot;, &quot;topic&quot;, &quot;*.onroad&quot;, { durable: false })              <br>    .prefetch(1)              <br>    .json()              <br>    .subscribe(async (msg, ack, nack) =&gt; {                <br>        const onroadParcel = await Track.updateOne(                  <br>            { name: msg.name },                  <br>            { status: msg.status },                  <br>            (err, parcel) =&gt; {                    <br>                if (err) throw err;                    <br>                else return parcel;                  <br>            }                <br>        );                <br>        console.log(&quot;parcel is on road:&quot;, onroadParcel);                <br>        ack();              <br>    });</pre><pre>//deliveredConsumer.js</pre><pre>import Tortoise from &quot;tortoise&quot;;              <br>import mongoose from &quot;mongoose&quot;              <br>import Track from &quot;../model/Tracking&quot;;              <br>import dotenv from &quot;dotenv&quot;              <br>dotenv.config()                            <br>mongoose.connect(process.env.MONGODB_URL, {                            <br>    useNewUrlParser: true,                            <br>    useUnifiedTopology: true,                          <br>});                          </pre><pre>const db = mongoose.connection;                          <br>db.on(&quot;error&quot;, console.error.bind(console, &quot;connection error:&quot;));                          <br>db.once(&quot;open&quot;, () =&gt; console.log(&quot;Connected to database&quot;));              </pre><pre>const tortoise = new Tortoise(process.env.AMQP_SERVER);            <br>tortoise              <br>    .queue(&quot;&quot;, { durable: false })              <br>    .exchange(&quot;parcel-tracking&quot;, &quot;topic&quot;, &quot;*.delivered&quot;, { durable: false })              <br>    .prefetch(1)              <br>    .json()              <br>    .subscribe(async (msg, ack, nack) =&gt; {                <br>        const deliveredParcel = await Track.updateOne(                  <br>            { name: msg.name },                  <br>            { status: msg.status },                  <br>            (err, parcel) =&gt; {                    <br>                if (err) throw err;                    <br>                else return parcel;                  <br>            }                <br>        );                <br>        console.log(&quot;parcel was delivered:&quot;, deliveredParcel);                <br>        ack();              <br>    });</pre><p>After these configurations have done, run these commands:</p><pre>nodemon ./server --exec babel-node -e js            <br>nodemon ./consumers/shippingConsumer --exec babel-node -e js            <br>nodemon ./consumers/onroadConsumer --exec babel-node -e js            <br>nodemon ./consumers/deliveredConsumer --exec babel-node -e js</pre><p>If you see Connected to database in all terminals, it means you skipped all steps successfully. Now open the links below up in a browser in order to test all database queries, and check the MongoDB database each time:</p><ul><li><a href="http://localhost:8000/shipping/test">localhost:8000/shipping/test</a></li><li><a href="http://localhost:8000/onroad/test">localhost:8000/onroad/test</a></li><li><a href="http://localhost:8000/delivered/test">localhost:8000/delivered/test</a></li></ul><p>Click the Collections tab in the Cluster page in the MongoDB Cloud. In the page that came up, click the collection named tracks under the parceltracking.</p><p>If our queries are correct, each time when shippingConsumer handles the message, a new record is going to be added to MongoDB, and each time other consumers handle the messages, the record will be updated. To show changes in the record, you will need to click the Refresh button on the Collections page</p><p>Now it is time to use Web Socket in order to render the changes in the records.</p><h3>Rendering Real-time Data With WebSocket</h3><p>To rendering real-time data with WebSocket, we are going to use the <a href="http://socket.io/">Socket.IO</a> library. Each time consumers are making changes in the database, new records will be rendered on the front page of the application without refreshing the page. To do this let’s create folder named socket in the server folder and add a file named trackerSocketç.js in it. Later write these lines down in the file:</p><pre>//trackerSocket.js</pre><pre>import socketIo from &quot;socket.io&quot;;            <br>import express from &quot;express&quot;;            <br>import http from &quot;http&quot;;            <br>import mongoose from &quot;mongoose&quot;;            <br>import Track from &quot;../model/Tracking&quot;;            <br>import dotenv from &quot;dotenv&quot;;            </pre><pre>dotenv.config();            </pre><pre>const port = process.env.WS_PORT || 8001;            </pre><pre>mongoose.connect(process.env.MONGODB_URL, {            <br>      useNewUrlParser: true,              <br>    useUnifiedTopology: true,            <br>});            </pre><pre>const db = mongoose.connection;            <br>db.on(&quot;error&quot;, console.error.bind(console, &quot;connection error:&quot;));            <br>db.once(&quot;open&quot;, () =&gt; console.log(&quot;Connected to database&quot;));            </pre><pre>const app = express();            </pre><pre>const server = http.createServer(app);            </pre><pre>const io = socketIo(server, {              <br>    cors: {                <br>    origin: &quot;*&quot;,                <br>    methods: [&quot;GET&quot;, &quot;POST&quot;],              <br>    },            <br>});            </pre><pre>let interval;            </pre><pre>const findParcel = async (socket) =&gt; {              <br>    const parcel = await Track.find({}, (err, parcel) =&gt; {                <br>        if (err) throw err;                <br>            console.log(parcel);                <br>            return parcel;              <br>    });              <br>    socket.emit(&quot;parcel&quot;, parcel);            <br>};            </pre><pre>io.on(&quot;connection&quot;, (socket) =&gt; {              <br>    console.log(&quot;New client connected&quot;);              <br>    if (interval) {                <br>        clearInterval(interval);              <br>    }              <br>    interval = setInterval(() =&gt; findParcel(socket), 1000);              <br>    socket.on(&quot;disconnect&quot;, () =&gt; {                <br>        console.log(&quot;Client disconnected&quot;);                <br>        clearInterval(interval);                <br>    });                <br>});                </pre><pre>server.listen(port, () =&gt; console.log(`Listening on port ${port}`));</pre><p>After writing the lines, run this command:</p><pre>nodemon ./socket/trackerSocket --exec babel-node -e js</pre><p>If you see the messages Listening on port 8001 and Connected to database output of the command, it means the command is running successfully.</p><p>Now in order to frontend installation, open up a terminal, go to under the folder named parcel-tracking-system where we created at the very first beginning:</p><pre>npx create-react-app client</pre><p>Later on, under the client folder, run this command in order to install <a href="http://socket.io/">socket.io</a>-client library:</p><pre>yarn add socket.io-client</pre><p>After the installation process has ended, go to under the src folder where is in the client folder. Here, create a file named socket.js and write these lines down in it:</p><pre>//socket.js</pre><pre>import socketIOClient from &quot;socket.io-client&quot;;            <br>const ENDPOINT = &quot;http://127.0.0.1:8001&quot;;            </pre><pre>const socket = socketIOClient(ENDPOINT);            </pre><pre>export default socket;</pre><p>After creating sokcet.js, open App.js in the same directory and modify it like that:</p><pre>//App.js</pre><pre>import React from &quot;react&quot;;            <br>import socket from &quot;./socket&quot;;            </pre><pre>function App() {              <br>    const [parcels, setParcel] = React.useState([{}]);              <br>    React.useEffect(() =&gt; {                <br>        socket.on(&quot;parcel&quot;, (data) =&gt; setParcel(data));                <br>    });                <br>    return (                  <br>        &lt;div&gt;                  <br>            {parcels.map((parcel) =&gt; (                    <br>            &lt;&gt;                    <br>                &lt;div&gt;ID: {parcel._id}&lt;/div&gt;                    <br>                &lt;div&gt;Name: {parcel.name}&lt;/div&gt;                    <br>                &lt;div&gt;Status: {parcel.status}&lt;/div&gt;                    <br>                &lt;br&gt;&lt;/br&gt;                    <br>            &lt;/&gt;                    <br>        ))}                    <br>        &lt;/div&gt;                    <br>    );                    <br>}            </pre><pre>export default App;</pre><p>To run React application run this command under the client directory in a terminal:</p><pre>yarn start</pre><p>In the page automatically opened up, you should see the record in MongoDB. To add a new record ve update it, open up these links below respectively:</p><ul><li><a href="http://localhost:8000/shipping/mycargo">localhost:8000/shipping/mycargo</a></li><li><a href="http://localhost:8000/onroad/mycargo">localhost:8000/onroad/mycargo</a></li><li><a href="http://localhost:8000/delivered/mycargo">localhost:8000/delivered/mycargo</a></li></ul><p>If you can see the changes in MongoDB with every click, congratulations, you have a little service!</p><h3>Conclusion</h3><p>Microservice structures are becoming more and more preferred structures in new applications. Software teams are working to migrate existing monolith structures to microservice architectures. In addition, AMQP stands out as a highly preferred communication protocol and provides solutions to some problems experienced with HTTP. On the end-user side, the interest and demand for real-time applications are also increasing and here web sockets provide great convenience to the software developer. It is a pleasure to master these tools, which are used to respond to new demands and new technologies, and it contributes a lot to the developer. Throughout this article, I wrote a small service and tried to provide a general understanding by using these structures and technologies in summary. I hope it has contributed to those who read, follow, and apply.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e022b2ff190" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RabbitMQ ile Kargo Takip Uygulaması]]></title>
            <link>https://ardaorkin.medium.com/rabbitmq-ile-kargo-takip-uygulamas%C4%B1-3d891a4cbcb5?source=rss-4ac7b9d750f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d891a4cbcb5</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[socketio]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Arda Örkin]]></dc:creator>
            <pubDate>Wed, 14 Apr 2021 17:25:10 GMT</pubDate>
            <atom:updated>2021-05-03T19:59:40.902Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j-T3fET2B1bZ0rr7Kdw2NA.png" /></figure><p><em>Bu makale ilk olarak 11/04/2021 tarihinde </em><a href="https://ardaorkin.com/blog/parcel-tracking"><em>https://ardaorkin.com/blog</em></a><em> adresinde yayınlanmıştır.</em></p><h3>Genel Bakış</h3><p>Yazılım geliştirme süreçlerinde geliştirilecek uygulamada kullanılacak olan teknolojileri belirlemenin yanı sıra uygulamanın mimarisini de belirlemek çok önemlidir. Bugünlerde en yaygın kullanılan mimari yapı <a href="https://martinfowler.com/articles/microservices.html">micro servis</a> yapısıdır. Micro servis yapılarının temel özelliklerinden birisi her bir servisin ayrı ayrı deploy edilebilir olmasıdır. Bu özellikleri yoluyla her servis uygulama içerisinde ayrı bir bağlantı protokolü kullanabilir. Yani bir uygulamada hem HTTP, hem AMQP hem de WS kullanılabilir.</p><p>Bugün burada hem HTTP hem AMQP hem WS kullanan küçük bir kargo takip uygulaması yapacağız. Bu uygulamda şu teknolojileri kullanacağız:</p><ul><li>Express.js</li><li>MongoDB</li><li>Socket.IO</li><li>RabbitMQ</li><li>ReactJS</li></ul><p>Express.js kütüphanesini HTTP isteklerini karşılamak için kullanacağız. HTTP istekleri geldiğinde RabbitMQ message broker’a bir mesaj yollayan <em>publisher</em>’lar kullanacağız. Bu <em>publisher</em>’ların RabbitMQ message broker’a yolladığı mesajları dinleyip MongoDB veri tabanınına kaydeden <em>consumer</em>’lar yazacağız. Son olarak veritabanındaki her bir değişkliğin, sayfa yenilenmeksizin ReactJS ile kodlayacağımız önyüzde görüntülenmesini sağlamak adına da Socket.IO kullanacağız.</p><p>İsteyen projenin bitmiş halini Github reposundan <a href="https://github.com/ardaorkin/rabbitmq-parcel-tracking.git">klonlayabilir</a>.</p><h3>Gereklikler</h3><ul><li>NodeJS ~12v</li></ul><h3>Geliştirme Ortamı Kurulumu</h3><h4>Sunucu</h4><p>Öncelikle <em>kargo-takip-sistemi</em> diye bir klasör oluşturalım. Bu klasörün içinde de bir adet daha klasör oluşturalım. Bu klasöre de sunucu adını verelim. Sonra bir terminal açıp sunucu adlı klasörün olduğu dizine gidelim ve npm init -y komutunu çalıştıralım. Daha sonra ana klasörümüzü bir metin editöründe açalım ve şöyle göründüğünden emin olalım:</p><p>Preview</p><p>Tekrar terminalimize dönelim ve proje bağımlılıklarını yüklemek için sunucu klasörünün altında şu komutu çalıştıralım:</p><pre>npm i express dotenv tortoise mongoose socket.io nodemon</pre><p>Komutun sorunsuz çalıştığından ve paketlerin yüklendiğinden emin olmak için hem terminalde dönen mesajlara bakalım hem package.json adlı dosyanın dependecies bölümüne bakalım:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/0*TCNmDN26m24-CJ1n.png" /></figure><p>Ayrıca geliştirme ortamı bağımlılıklarımızı da yükleyelim:</p><pre>npm i --save-dev @babel/core @babel/preset-env babel-loader</pre><p>Bu komutu çalıştırdıktan sonra package.json dosyamızın içi resimdeki gibi görünmeli:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/0*w9qIZnJWheju-x0L.png" /></figure><p>Daha sonra .babelrc diye bir dosya oluşturalım ve içerisine şu kodu yazalım:</p><pre>{                                        <br>	&quot;presets&quot;: [&quot;@babel/env&quot;]                                        <br>}</pre><p>Şimdi de server.js adlı bir dosya oluşturalım ve dosyanın içerisine şu kodu yazalım:</p><pre><em>//server.js</em></pre><pre>import express from &quot;express&quot;              </pre><pre>const app = express()              </pre><pre>app.use(&quot;/&quot;, (req, res) =&gt; {                </pre><pre>res.send(&quot;Kargo takip sistemi&quot;)              </pre><pre>})              </pre><pre>app.listen(8000, () =&gt; console.log(`Server listening on 8000`))</pre><p>server.js adlı dosyayı nodemon ./server --exec babel -e jsterminalde çalıştıralım. Tarayıcımızda <a href="http://localhost:8000/">http://localhost:8000</a> adresini açalım ve karşımıza çıkan sayfada &quot;Kargo takip sistemi&quot; yazıyorsa Express.js kurulumumuz tamamlanmış demektir.</p><h4>Publisher ve Consumer Oluşturma</h4><p>Şimdiki adımımızda ilk publisher’ımızı ve ilk consumer’ımızı oluşturacağız. Publisher bir mesaj yayınlayıp, bunu exchange’e gönderecek. RabbitMQ message broker’da bulunan exchange’imiz bu mesajı kuyruğa yollayacak ve exchange’te kendisini ilgilendiren mesajları dinleyen consumer’ımız da bu mesaj alacak ve istediğimiz işlemi yapacak.</p><p>Şimdilik consumer üzerinden edindiğimiz mesajımızı konsola basacağız. Bunun için öncelikle sunucu dizini altında bir publishers bir de consumers adında iki adet dizin oluşturalım. publishers dizinimizin içerisinde shippingPublihser.js diye bir dosya oluşturalım. consumers dizinimizin içerisine de shippingConsumer.js diye bir dosya oluşturalım. shippingPublihser.js adlı dosyamızın içerisine şu kodu yazalım:</p><pre><em>//shippingPublisher.js</em><br><em>          </em><br>import Tortoise from &quot;tortoise&quot;          <br>import dotenv from &quot;dotenv&quot;;          <br>dotenv.config()          </pre><pre>const tortoise = new Tortoise(process.env.AMQP_URL)    <br>		tortoise      <br>			.exchange(&quot;parcel-tracking&quot;, &quot;topic&quot;, { durable: false })      <br>			.publish(&quot;parcel.shipping&quot;, { name: &quot;test&quot;, status: &quot;shipping&quot; });</pre><p>Şimdi de publisher’dan message broker’a giden mesajı alacak olan consumer’ı yazalım. Bunun için oluşturduğumuz shippingConsumer.js dosyasını açalım ve içine şu kodu yazalım:</p><pre><em>//shippingConsumer.js</em><br><em>                            </em><br>import Tortoise from &quot;tortoise&quot;                            <br>import dotenv from &quot;dotenv&quot;;                            <br>dotenv.config()                            </pre><pre>const tortoise = new Tortoise(process.env.AMQP_URL)                            </pre><pre>tortoise  <br>	.queue(&quot;&quot;, { durable: false })  <br>	.exchange(&quot;parcel-tracking&quot;, &quot;topic&quot;, &quot;*.shipping&quot;, { durable: false })  <br>	.prefetch(1)  <br>	.json()  <br>	.subscribe((msg, ack, nack) =&gt; {    <br>		console.log(msg)    <br>		ack();  <br>	});</pre><p>Bu iki dosyayı oluşturduktan sonra publihser’ımızı ve consumer’ımızı hazırlamış olduk. Şimdi sırada message broker işlevi görecek RabbitMQ sunucumuzu ayaklandırmak var. Bunun için RabbitMQ’yu yerel makinamıza kurmayı da tercih edebiliriz ama bu yol hem uzun süreceğinden hem de işletim sistemine göre kurulum adımları değişeceğinden.<a href="http://cloudamqp.com/">http://cloudamqp.com</a>üzerinden bir sunucu açarak devam edeceğiz. <a href="http://cloudamqp.com/">http://cloudamqp.com</a> adresinde bir hesap olutşuruyoruz. Daha sonra Create New Instance yazan düğmeye basıp yeni bir message broker oluşturuyoruz. Mesaj broker’ı istediğiniz şekilde isimlendirebilirsiniz. Ücretsiz plan için Little Lemur’u seçmeniz gerekecektir. Sonra Select Region &gt; Review &gt; Create Instance düğmelerine basıp örnek message broker’ımızı oluşturuyoruz. Message broker’larımızın listelendiği <a href="https://customer.cloudamqp.com/instance">sayfaya</a> gidip, yeni oluşturduğumuz message broker’ın adına tıklıyoruz. Karşımıza çıkan Details bölümündeki AMQP URL değerini kopyalıyoruz. Projemizin olduğu dizine dönüyoruz ve sunucu adlı dizinimizde .env diye bir dosya oluşturuyoruz. Bu .env dosyasının içerisine şu satırları yazıyoruz:</p><pre>AMQP_URL=&quot;kopyaladığımız_amqp_urlsi&quot;</pre><p>Yani AMQP_URL değişkeninin değeri az evvel kopyaladığımız AMQP URL’si olmalı.</p><p>Bu işlemden sonra basit bir amqp servisi kurmuş olduk. Şimdi bu servisi çalıştırmak için iki ayrı terminalde, sunucu klasörümüzün bulundupu konuma gidip sırasıyla şu komutları çalıştırıyoruz:</p><pre>nodemon ./consumers/shippingConsumer --exec babel-node -e js          <br>nodemon ./publishers/shippingPublisher --exec babel-node -e js</pre><p>Bu adımları uyguladıktan sonra shippingConsumer.js dosyasını çalıştırdığımız terminalde şu JSON biçimindeki çıktıyı göreceğiz:</p><pre>{ name: &#39;test&#39;, status: &#39;shipping&#39; }</pre><p>Şu an elimizde çalışan bir servis var. Bu servis haberleşme protokolü olarak AMQP kullanıyor. Serviste iki uç nokta var, biri publihser, diğeri consumer. Publisher mesajı mesaj broker’a yolluyor, bu işlemden sonra publisher’ın işi bitiyor ve herhangi bir geri dönüş beklemiyor. Consumer da mesaj borker’daki mesajı alıp konsola basıyor. Consumer için tek önemli olan mesaj başlığının ne içerdiği. Buradaki örnek senaryoda consumer “shipping” ifadesi ile biten başlıklara sahip mesajlarla ilgileniyor. Mesaj başlığı bilgisi dışında consumer’ın ihtiyaç duyduğu hiçbir şey bulunmuyor.</p><p>Sıradaki adımda HTTP üzerinden gelen isteklerle mesaj yayınlayacağız.</p><h4>HTTP İsteklerini Değerlendirme</h4><p>Bu adım için öncelikle ikişer adet daha publisher ve consumer oluşturalım.</p><p>Yine sunucu adlı dizinimize gidelim. Burada publishers ve consumers adlı dizinlerimizin altında şu dosyaları oluşturalım:</p><ul><li>onroadPublisher.js</li><li>deliveredPublisher.js</li><li>onroadConsumer.js</li><li>deliveredConsumer.js</li></ul><p>Bu işlem sonucuda dosya-dizin yapımız şöyle görünmeli:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/0*KTfRkQ2w51lThliE.png" /></figure><p>Bütün publihser dosyalarımızı <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a> döndürecek şekilde yazıyoruz:</p><pre><em>//shippingPublisher.js</em><br><em>            </em><br>import Tortoise from &quot;tortoise&quot;;            <br>import dotenv from &quot;dotenv&quot;;            <br>dotenv.config();            <br>            <br>const tortoise = new Tortoise(process.env.AMQP_SERVER);            <br>            <br>const shippingPublisher = (name) =&gt;              <br>	new Promise((resolve, reject) =&gt; {                <br>		tortoise                  <br>			.exchange(&quot;parcel-tracking&quot;, &quot;topic&quot;, { durable: false })                  <br>			.publish(&quot;parcel.shipping&quot;, { name, status: &quot;shipping&quot; });                  <br>		resolve({ name, status: &quot;shipping&quot; });              <br>});            <br>            <br>export default shippingPublisher;</pre><pre><em>//onroadPublisher.js</em><br><em>            </em><br>import Tortoise from &quot;tortoise&quot;;            <br>import dotenv from &quot;dotenv&quot;;            <br>dotenv.config();            <br>            <br>const tortoise = new Tortoise(process.env.AMQP_SERVER);            <br>            <br>const onroadPublisher = (name) =&gt;              <br>	new Promise((resolve, reject) =&gt; {                <br>		tortoise                  <br>			.exchange(&quot;parcel-tracking&quot;, &quot;topic&quot;, { durable: false })                  <br>			.publish(&quot;parcel.onroad&quot;, { name, status: &quot;onroad&quot; });                  <br>		resolve({ name, status: &quot;onroad&quot; });              <br>});            <br>            <br>export default onroadPublisher;</pre><pre><em>//deliveredPublisher.js</em><br><em>            </em><br>import Tortoise from &quot;tortoise&quot;;            <br>import dotenv from &quot;dotenv&quot;;            <br>dotenv.config();            <br>            <br>const tortoise = new Tortoise(process.env.AMQP_SERVER);            <br>            <br>const deliveredPublisher = (name) =&gt;              <br>	new Promise((resolve, reject) =&gt; {                <br>		tortoise                  <br>			.exchange(&quot;parcel-tracking&quot;, &quot;topic&quot;, { durable: false })                  <br>			.publish(&quot;parcel.delivered&quot;, { name, status: &quot;delivered&quot; });                  <br>		resolve({ name, status: &quot;delivered&quot; });              <br>});            <br>            <br>export default deliveredPublisher;</pre><p>Daha sonra consumer dosyalarımıza geçiyoruz. Bütün consumer dosyalarımızı aşağıdaki gibi yazıyoruz:</p><pre><em>//shippingConsumer.js</em><br><em>            </em><br>import Tortoise from &quot;tortoise&quot;;            <br>import dotenv from &quot;dotenv&quot;;            <br>dotenv.config();            <br>            <br>const tortoise = new Tortoise(process.env.AMQP_SERVER);            <br>tortoise              <br>	.queue(&quot;&quot;, { durable: false })              <br>	.exchange(&quot;parcel-tracking&quot;, &quot;topic&quot;, &quot;*.shipping&quot;, { durable: false })              <br>	.prefetch(1)              <br>	.json()              <br>	.subscribe((msg, ack, nack) =&gt; {                <br>		console.log(msg)                <br>	ack();              <br>	});</pre><pre><em>//onroadConsumer.js</em><br><em>            </em><br>import Tortoise from &quot;tortoise&quot;;            <br>import dotenv from &quot;dotenv&quot;;            <br>dotenv.config();            <br>            <br>const tortoise = new Tortoise(process.env.AMQP_SERVER);            <br>tortoise              <br>	.queue(&quot;&quot;, { durable: false })              <br>	.exchange(&quot;parcel-tracking&quot;, &quot;topic&quot;, &quot;*.onroad&quot;, { durable: false })              <br>	.prefetch(1)              <br>	.json()              <br>	.subscribe((msg, ack, nack) =&gt; {                <br>		console.log(msg)                <br>	ack();              <br>	});</pre><pre><em>//deliveredConsumer.js</em><br><em>            </em><br>import Tortoise from &quot;tortoise&quot;;            <br>import dotenv from &quot;dotenv&quot;;            <br>dotenv.config();            <br>            <br>const tortoise = new Tortoise(process.env.AMQP_SERVER);            <br>tortoise              <br>	.queue(&quot;&quot;, { durable: false })              <br>	.exchange(&quot;parcel-tracking&quot;, &quot;topic&quot;, &quot;*.delivered&quot;, { durable: false })              <br>	.prefetch(1)              <br>	.json()              <br>	.subscribe((msg, ack, nack) =&gt; {                <br>		console.log(msg)                <br>	ack();              <br>	});</pre><p>Bu ayarlamalardan sonra HTTP istekleri geldikçe çalıştıracağımız publisher’larımızı ve bu publisher’lar message broker’a mesaj yolladıkça bu mesajları işleyecek olan consumer’ları oluşturmuş olduk. Şimdi de HTTP route’larımızı oluşturacağız. Daha okunaklı ve yönetilebilir bir uygulama yapısı oluşturmak adına sunucu dizini altında routes diye bir dizin oluşturalım ve bu dizinin içerisinde de index.js diye bir dosya oluşturalım. index.js dosyamızın içerisine şu kodu yazalım:</p><pre><em>//index.js</em><br><em>            </em><br>import { Router } from &quot;express&quot;;            <br>import shippingPublishers from &quot;../publishers/shippingPublisher&quot;;            <br>import onroadPublisher from &quot;../publishers/onroadPublisher&quot;;            <br>import deliveredPublisher from &quot;../publishers/deliveredPublisher&quot;;            <br>            <br>const router = Router();            <br>            <br>router.get(&quot;/&quot;, (req, res) =&gt; {              <br>	res.send(&quot;Kargo takip sistemine hoş geldiniz&quot;);            <br>});            <br>            <br>router.get(&quot;/shipping/:name&quot;, async (req, res, next) =&gt; {              <br>	const name = req.params.name;              <br>	await shippingPublishers(name).then((message) =&gt; res.json(message));            <br>});            <br>            <br>router.get(&quot;/onroad/:name&quot;, async (req, res, next) =&gt; {              <br>	const name = req.params.name;              <br>	await onroadPublisher(name).then((message) =&gt; res.json(message));            <br>});            <br>            <br>router.get(&quot;/delivered/:name&quot;, async (req, res, next) =&gt; {              <br>	const name = req.params.name;              <br>	await deliveredPublisher(name).then((message) =&gt; res.json(message));            <br>});            <br>            <br>export default router;</pre><p>HTTP route’larımızı oluşturduktan sonra server.js dosyamıza gidelim ve dosyamızı şöyle değiştirelim:</p><pre><em>//server.js</em></pre><pre>import express from &quot;express&quot;;<br>import router from &quot;./routes&quot;;            </pre><pre>const app = express();<br>const port = process.env.PORT || 8000;</pre><pre>app.use(router);</pre><pre>app.listen(port, () =&gt; console.log(`Server listening on port ${port}`));</pre><p>HTTP route’larımızı uygulamanın geneline bağladıktan sonra ayrı ayrı terminallerde, sunucu dizinimizin altına giderek şu komutları çalıştıralım:</p><pre>nodemon ./server --exec babel-node -e js            <br>nodemon ./consumers/shippingConsumer --exec babel-node -e js            <br>nodemon ./consumers/onroadConsumer --exec babel-node -e js            <br>nodemon ./consumers/deliveredConsumer --exec babel-node -e js</pre><p>Bütün consumer’larımız ve uygulamamız çalıştıktan sonra sırasıyla şu adresleri tarayıcımızda açalım ve her adresi açtığımızda consumer’larımızın çalıştığı terminallerdeki çıktılara bakalım; terminal çıktılarında, message broker’a giden mesajları JSON biçiminde göreceğiz:</p><ul><li><a href="http://localhost:8000/shipping/test">http://localhost:8000/shipping/test</a></li><li><a href="http://localhost:8000/onroad/test">http://localhost:8000/onroad/test</a></li><li><a href="http://localhost:8000/delivered/test">http://localhost:8000/delivered/test</a></li></ul><p>Hem consumer’ların çalıştığı konsoldaki çıktıyı hem de tarayıcıdaki JSON formatındaki mesajı gördükten sonra HTTP üzerinden gelen isteklerle publisher’larımızın çalıştığını ve consumer’larımızın da bu publisher’ların message broker’a gönderdiği mesajları işlediğini görmüş oluruz. Şimdi de sırada consumer’ların MongoDB veritabanına, message broker’dan aldıkları mesajı kaydedeceğiz.</p><h4>MongoDB Yapılandırması</h4><p>MongoDB için öncelikle <a href="https://www.mongodb.com/cloud">https://www.mongodb.com/cloud</a> adresinde bir hesap oluşturalım. Sonrasında bir organizasyon, bu organizasyon içerisinde bir proje, projenin içerisinde bir cluster oluşturalım. Cluster oluşturduktan sonra, cluster’ın olduğu sayfada, sol panelde yer alan Database Access bağlantısına tıklayalım. Burada ADD NEW DATABASE USER düğmesine tıklayalım ve veritabanı kullanıcımızı oluşturalım. Daha sonra yine sol panelde yer alan Clusters bağlantısını tıklayalım. Açılan sayfada Connect düğmesine tıklayalım, Setup connection security adımında Allow anywhere seçeneğini seçelim ve sağ alttaki Choose a connection method düğmesine tıklayalım. Burada Connect your application seçeneğine tıklayalım ve Add your connection string into your application code başlığı altındaki bağlantı bilgisini kopayalayalım. Uygulamamızda, sunucu dizini altında yer alan .env dosyamızın içerisinde MONGODB_URL adlı bir değişken oluşturalım ve kopyaladığımız bağlantı bilgisini bu değişkene değer olarak verelim, &lt;password&gt; kısmını az evvel Database Access bölümünde oluşturduğumuz parola ile değiştirelim. myFirstDatabase kısmını da kargotakip olarak değiştirelim:</p><pre>MONGODB_URL=&quot;mongodb+srv://username:12345@cluster0.mjh9d.mongodb.net/kargotakip?retryWrites=true&amp;w=majority&quot;</pre><p>Bu işlemleri yaptıktan sonra server.js dosyamıza gelelim, ve routes dizinini import ettiğimiz satırdan hemen sonra şu satırları yazalım:</p><pre><em>//server.js</em></pre><pre>import mongoose from &quot;mongoose&quot;<br>import dotenv from &quot;dotenv&quot;<br>dotenv.config()              <br>mongoose.connect(process.env.MONGODB_URL, {              <br>	useNewUrlParser: true,              <br>	useUnifiedTopology: true,            <br>});            <br>            <br>const db = mongoose.connection;            <br>db.on(&quot;error&quot;, console.error.bind(console, &quot;connection error:&quot;));            <br>db.once(&quot;open&quot;, () =&gt; console.log(&quot;Connected to database&quot;));</pre><p>Bu satırlar yoluyla bir MongoDB bağlantısı açmış olduk. Her şeyin doğru olduğundan emin olmak için server.js dosyamızı şu komutla çalıştıralım:</p><pre>nodemon ./server --exec babel-node -e js</pre><p>Eğer terminal konsolunda Connected to database mesajını görüyorsanız bütün adımları başarılı bir şekilde geçmişsiniz demektir. Bundan sonraki adımda da ilk MongoDB şemamızı ve modelimizi oluşturacağız. Bu adım için de öncelikle sunucu dizini altında model diye bir dizin oluşturalım. Bu dizin içerisinde de Tracking.js diye bir dosya oluşturalım ve dosyanın içerisine şu kodu yazalım:</p><pre><em>//Tracking.js</em><br><em>            </em><br>import mongoose from &quot;mongoose&quot;;<br>   <br>const trackingSchema = new mongoose.Schema({              <br>	name: String,              <br>	status: String,            <br>});            <br>            <br>const Track = mongoose.model(&quot;Track&quot;, trackingSchema);            <br>            <br>export default Track;</pre><p>Modelimizi olutşurduktan sonra consumer’larımızda bu modeli kullanacağız. Fakat shippingConsumer’da mongoose kütüphanesindeki save() metodunu kullanırken, diğer consumerlarda da updateOne() metodunu kullanacağız. Öncelikle shippinConsumer.js dosyamızı şöyle değiştirelim:</p><pre><em>//shippingConsumer.js</em><br><em>            </em><br>import Tortoise from &quot;tortoise&quot;;            <br>import mongoose from &quot;mongoose&quot;            <br>import Track from &quot;../model/Tracking&quot;;            <br>import dotenv from &quot;dotenv&quot;            <br>dotenv.config()                          <br>mongoose.connect(process.env.MONGODB_URL, {                          <br>	useNewUrlParser: true,                          <br>	useUnifiedTopology: true,                        <br>});                        <br>                        <br>const db = mongoose.connection;                        <br>db.on(&quot;error&quot;, console.error.bind(console, &quot;connection error:&quot;));                        <br>db.once(&quot;open&quot;, () =&gt; console.log(&quot;Connected to database&quot;));            <br>            <br>const tortoise = new Tortoise(process.env.AMQP_SERVER);            <br>tortoise              <br>	.queue(&quot;&quot;, { durable: false })              <br>	.exchange(&quot;parcel-tracking&quot;, &quot;topic&quot;, &quot;*.shipping&quot;, { durable: false })              <br>	.prefetch(1)              <br>	.json()              <br>	.subscribe((msg, ack, nack) =&gt; {                <br>		const newParcel = new Track(msg);                <br>		newParcel.save((err, parcel) =&gt; {                  <br>			if (err) throw err;                  <br>			console.log(&quot;shipped parcel:&quot;, parcel);                  <br>			return parcel;                  <br>		});                <br>		ack();              <br>	});</pre><p>Bu sayede shippingConsumer, MongoDB içerisinde yeni bir kayıt oluşturacak. Şimdi de bu kaydı güncellemek için onroadConsumer ve deliveredConsumer dosyalarımızı değiştirelim</p><pre><em>//onroadConsumer.js</em><br><em>              </em><br>import Tortoise from &quot;tortoise&quot;;              <br>import mongoose from &quot;mongoose&quot;              <br>import Track from &quot;../model/Tracking&quot;;              <br>import dotenv from &quot;dotenv&quot;              <br>dotenv.config()                            <br>mongoose.connect(process.env.MONGODB_URL, {                            <br>	useNewUrlParser: true,                            <br>	useUnifiedTopology: true,                          <br>});                          <br>                          <br>const db = mongoose.connection;                          <br>db.on(&quot;error&quot;, console.error.bind(console, &quot;connection error:&quot;));                          <br>db.once(&quot;open&quot;, () =&gt; console.log(&quot;Connected to database&quot;));            <br>            <br>const tortoise = new Tortoise(process.env.AMQP_SERVER);            <br>tortoise              <br>	.queue(&quot;&quot;, { durable: false })              <br>	.exchange(&quot;parcel-tracking&quot;, &quot;topic&quot;, &quot;*.onroad&quot;, { durable: false })              <br>	.prefetch(1)              <br>	.json()              <br>	.subscribe(async (msg, ack, nack) =&gt; {                <br>		const onroadParcel = await Track.updateOne(                  <br>			{ name: msg.name },                  <br>			{ status: msg.status },                  <br>			(err, parcel) =&gt; {                    <br>				if (err) throw err;                    <br>				else return parcel;                  <br>			}                <br>		);                <br>		console.log(&quot;parcel is on road:&quot;, onroadParcel);                <br>		ack();              <br>	});</pre><pre><em>//deliveredConsumer.js</em><br><em>              </em><br>import Tortoise from &quot;tortoise&quot;;              <br>import mongoose from &quot;mongoose&quot;              <br>import Track from &quot;../model/Tracking&quot;;              <br>import dotenv from &quot;dotenv&quot;              <br>dotenv.config()                            <br>mongoose.connect(process.env.MONGODB_URL, {                            <br>	useNewUrlParser: true,                            <br>	useUnifiedTopology: true,                          <br>});                          <br>                          <br>const db = mongoose.connection;                          <br>db.on(&quot;error&quot;, console.error.bind(console, &quot;connection error:&quot;));                          <br>db.once(&quot;open&quot;, () =&gt; console.log(&quot;Connected to database&quot;));              <br>            <br>const tortoise = new Tortoise(process.env.AMQP_SERVER);            <br>tortoise              <br>	.queue(&quot;&quot;, { durable: false })              <br>	.exchange(&quot;parcel-tracking&quot;, &quot;topic&quot;, &quot;*.delivered&quot;, { durable: false })              <br>	.prefetch(1)              <br>	.json()              <br>	.subscribe(async (msg, ack, nack) =&gt; {                <br>		const deliveredParcel = await Track.updateOne(                  <br>			{ name: msg.name },                  <br>			{ status: msg.status },                  <br>			(err, parcel) =&gt; {                    <br>				if (err) throw err;                    <br>				else return parcel;                  <br>			}                <br>		);                <br>		console.log(&quot;parcel was delivered:&quot;, deliveredParcel);                <br>		ack();              <br>	});</pre><p>Dosyalarımızın içerisini değiştirdikten sonra yine şu komutları sunucu dizinimizin altında çalıştırıyoruz:</p><pre>nodemon ./server --exec babel-node -e js            <br>nodemon ./consumers/shippingConsumer --exec babel-node -e js            <br>nodemon ./consumers/onroadConsumer --exec babel-node -e js            <br>nodemon ./consumers/deliveredConsumer --exec babel-node -e js</pre><p>Bütün consumer’larımızın ve server.js dosyamızın çalıştığı terminallerdeki çıktılarda Connected to database mesajını görüyorsanız bütün adımları başarılı bir şekilde uygulamışsınız demektir. Bundan sonra veritabanı sorgularının doğruluğunu test etmek için sırasıyla aşağıdaki bağlantıları tarayıcıda açalım ve her bağlantıyı açtığımızda MongoDB veritabanımızı kontrol edelim.</p><p>MongoDB Cloud’da Clusters sayfasındak Collections sekmesine tıklayalım. Karşımıza çıkan sayfada kargotakip veritabanı altındaki tracks adlı collection’a tıklayalım.</p><p>Eğer sorgularımız doğruysa, shippingConsumer mesajı işlediğinde MongoDB’ye bir kayıt eklenecek, diğer consumer’lar da mesajı işledeğinde MongoDB’deki kaydın status değeri değişecektir. Kaydın değiştiğini görüntülemek için Collections sayfasındaki Refresh butonuna tıklamamız gerekecektir.</p><ul><li><a href="http://localhost:8000/shipping/test">http://localhost:8000/shipping/test</a></li><li><a href="http://localhost:8000/onroad/test">http://localhost:8000/onroad/test</a></li><li><a href="http://localhost:8000/delivered/test">http://localhost:8000/delivered/test</a></li></ul><p>Her şey düzgün çalışıyorsa consumer’larımız kendilerine gelen mesajı veritabanına başarılı bir şekilde işliyor demektir. Bundan sonraki adımda bu verileri önyüzde göstermek için Web Socket kullanacağız.</p><h4>Web Socket İle Gerçek Zamanlı Verileri Gösterme</h4><p>Web socket ile gerçek zamanlı verileri göstermek için Socket.IO kütüphanesini kullanacağız. Consumer’lar veritabanında her işlem yaptığında bu işlemle, sayfa yenileme gerek kalmaksızın önyüzde kulanıcıya görünecek. Bunun için öncelikleserver dizini altında socket diye bir dizin oluşturalım ve içerisine trackerSocket.js diye bir dosya ekleyelim. trackerSocket.js dosyasının içerisine şu satırları yazalım:</p><pre><em>//trackerSocket.js</em><br><em>            </em><br>import socketIo from &quot;socket.io&quot;;            <br>import express from &quot;express&quot;;            <br>import http from &quot;http&quot;;            <br>import mongoose from &quot;mongoose&quot;;            <br>import Track from &quot;../model/Tracking&quot;;            <br>import dotenv from &quot;dotenv&quot;;            <br>            <br>dotenv.config();            <br>            <br>const port = process.env.WS_PORT || 8001;            <br>            <br>mongoose.connect(process.env.MONGODB_URL, {            <br>	  useNewUrlParser: true,              <br>	useUnifiedTopology: true,            <br>});            <br>            <br>const db = mongoose.connection;            <br>db.on(&quot;error&quot;, console.error.bind(console, &quot;connection error:&quot;));            <br>db.once(&quot;open&quot;, () =&gt; console.log(&quot;Connected to database&quot;));            <br>            <br>const app = express();            <br>            <br>const server = http.createServer(app);            <br>            <br>const io = socketIo(server, {              <br>	cors: {                <br>	origin: &quot;*&quot;,                <br>	methods: [&quot;GET&quot;, &quot;POST&quot;],              <br>	},            <br>});            <br>            <br>let interval;            <br>            <br>const findParcel = async (socket) =&gt; {              <br>	const parcel = await Track.find({}, (err, parcel) =&gt; {                <br>		if (err) throw err;                <br>			console.log(parcel);                <br>			return parcel;              <br>	});              <br>	socket.emit(&quot;parcel&quot;, parcel);            <br>};            <br>            <br>io.on(&quot;connection&quot;, (socket) =&gt; {              <br>	console.log(&quot;New client connected&quot;);              <br>	if (interval) {                <br>		clearInterval(interval);              <br>	}              <br>	interval = setInterval(() =&gt; findParcel(socket), 1000);              <br>	socket.on(&quot;disconnect&quot;, () =&gt; {                <br>		console.log(&quot;Client disconnected&quot;);                <br>		clearInterval(interval);                <br>	});                <br>});                <br>                <br>server.listen(port, () =&gt; console.log(`Listening on port ${port}`));</pre><p>Dosyamızı yazdıktan sonra şu komutu çalıştırıyoruz:</p><pre>nodemon ./socket/trackerSocket --exec babel-node -e js</pre><p>Komutun çıktısında Listening on port 8001 ve Connected to database mesajlarını görüyorsak socketimiz çalıştı demektir.</p><p>Şimdide önyüz kurulumu için, bir terminal açalım, en başta oluşturduğumuz kargo-takip-sistemi adlı dizinimize gidelim ve şu komutu çalıştıralım</p><pre>npx create-react-app client</pre><p>Bu komut sonrasında hazır bir React uygulama yapısı, client adlı bir dizin altında kurulmuş olacak. Daha sonra terminalde client dizininin altında şu komutu çalıştırarak socket.io-client kütüphanesini yükleyelim:</p><pre>yarn add socket.io-client</pre><p>Kütüphane yükleme işlemi bittikten sonra client dizini altında bulunan src dizinine gidelim. Burada socket.js adlı bir dosya oluşturalım ve içerisine şu satırları yazalım:</p><pre><em>//socket.js</em><br><em>            </em><br>import socketIOClient from &quot;socket.io-client&quot;;            <br>const ENDPOINT = &quot;http://127.0.0.1:8001&quot;;            <br>            <br>const socket = socketIOClient(ENDPOINT);            <br>            <br>export default socket;</pre><p>socket.js içerisini oluşturduktan sonra src dizini altındaki App.js dosyamızı açalım ve içerisini şöyle düzenleyelim:</p><pre><em>//App.js</em><br>            <br>import React from &quot;react&quot;;            <br>import socket from &quot;./socket&quot;;            <br>            <br>function App() {              <br>	const [parcels, setParcel] = React.useState([{}]);              <br>	React.useEffect(() =&gt; {                <br>		socket.on(&quot;parcel&quot;, (data) =&gt; setParcel(data));                <br>	});                <br>	return (                  <br>		&lt;div&gt;                  <br>			{parcels.map((parcel) =&gt; (                    <br>			&lt;&gt;                    <br>				&lt;div&gt;ID: {parcel._id}&lt;/div&gt;                    <br>				&lt;div&gt;Name: {parcel.name}&lt;/div&gt;                    <br>				&lt;div&gt;Status: {parcel.status}&lt;/div&gt;                    <br>				&lt;br&gt;&lt;/br&gt;                    <br>			&lt;/&gt;                    <br>		))}                    <br>		&lt;/div&gt;                    <br>	);                    <br>}            <br>            <br>export default App;</pre><p>React uygulamayı çalıştırmak için terminalde client dizini altına gidin ve şu komutu çalıştırın:</p><pre>yarn start</pre><p>Karşınıza çıkan sayfada MongoDB’deki kaydın bilgisi bulunacaktır. Yeni kayıt eklemek ve bu kaydı güncelleyp, her güncellemenin gerçek zamanlı olarak React uygulamaya yansıdığından emin olmak için sırasıyla şu bağlantıları tarayıcınızda açın:</p><ul><li><a href="http://localhost:8000/shipping/kargom">http://localhost:8000/shipping/kargom</a></li><li><a href="http://localhost:8000/onroad/kargom">http://localhost:8000/onroad/kargom</a></li><li><a href="http://localhost:8000/delivered/kargom">http://localhost:8000/delivered/kargom</a></li></ul><p>Eğer her bağlantıya tıkladığınızda React uygulamada veritabanındaki değişikliği görüntüleyebiliyorsanız, tebrikler, küçük bir kargo takip servisiniz oldu.</p><h3>Sonuç</h3><p>Microservis yapıları her geçen gün yeni uygulamalarda daha çok tercih edilen yapılar olmakta. Yazılım ekipleri var olan monotlith yapılarını microservis mimarilere göç ettirmek içi çalışmalar yapmakta. Bunun yanısıra AMQP de çok fazla tercih edilen bir haberleşme protokolü olarak ön çıkmakta ve HTTP ile yaşanan bir takım sorunlara çözüm sağlamakta. Son kullanıcı tarafında ise gerçek zamanlı uygulamalara olan ilgi ve talep de gittikçe artmakta ve burada web socket’ler yazılım geliştiriciye büyük kolaylıklar sağlamakta. Yeni taleplere ve yeni teknolojilere cevap vermek için kullanılan bu araçlarda ustalaşmak hem çok zevkli hem de geliştiriciye çok fazla katkı sağlıyor. Bu makale boyunca da ufak bir servis yazıp, sözkonusu yapıları ve teknolojileri özet halinde kullanıp genel bir kavrayış sağlamaya çalıştım. Umarım okuyana, takip edene, uygulayana bir katkısı olmuştur.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d891a4cbcb5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>