<?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 Rafael Ferreira on Medium]]></title>
        <description><![CDATA[Stories by Rafael Ferreira on Medium]]></description>
        <link>https://medium.com/@rafaelferreiram?source=rss-874233b13d96------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*pppNPjg_bzY8wnGrbZ4aeA.png</url>
            <title>Stories by Rafael Ferreira on Medium</title>
            <link>https://medium.com/@rafaelferreiram?source=rss-874233b13d96------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 13:40:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rafaelferreiram/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[Dockerizing a Java RESTfulAPI]]></title>
            <link>https://medium.com/@rafaelferreiram/dockerizing-a-java-restfulapi-e685d20bf47?source=rss-874233b13d96------2</link>
            <guid isPermaLink="false">https://medium.com/p/e685d20bf47</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Rafael Ferreira]]></dc:creator>
            <pubDate>Thu, 14 May 2020 20:52:48 GMT</pubDate>
            <atom:updated>2020-05-14T20:52:48.971Z</atom:updated>
            <content:encoded><![CDATA[<p>Generating docker image and dockerizing Springboot API</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XYfUl8KT9SGPo4EiaZsf3w.png" /></figure><p>Containers, can you imagine that this representation would mean such a life saving in software engineering? The principle of container in IT world means that ‘<em>Containers are isolated from one another and bundle their own software</em>’ and it helps our application ecosystem and scalability.</p><p>In this article I’m going to show you how to Dockerize a Java API, presuming you already understand the principles of Docker and API Development.</p><p>The API we’ll be using was developed with the following technologies:</p><ul><li>Java</li><li>Springboot</li><li>Maven</li><li>MongoDB</li><li>Docker</li></ul><blockquote>Here’s the link for the project <a href="https://github.com/rafaelferreiram/quick-api.git"><em>https://github.com/rafaelferreiram/quick-api.git</em></a></blockquote><h4>Dockerfile Maven</h4><p>To generate a docker image using maven we’re going to need to use a frameworks that helps to do so, and this guys is the <em>dockerfile-maven a </em>plugin created by Spotify to make the generation and the communication of a docker image easier.</p><h4>Dockerfile</h4><p>Before we get started creating our docker image we have to create a Dockerfile file, responsible for for exposing our jar and configurations to Docker.<br>This dockerfile must be generate in the project root just like the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*QyfXyUwBl-_4FU-qqmQMYw.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58e5e7b8a4b3dc8400115cea0415870e/href">https://medium.com/media/58e5e7b8a4b3dc8400115cea0415870e/href</a></iframe><h4>Pom.xml</h4><p>After setting up our Dockerfile configs, we have to add the <em>dockerfile-maven </em>plugin to the project`s pom.xml under the tag &lt;plugins&gt;looking something like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b4e2f86e2046ae24e4b8936899fb9f2/href">https://medium.com/media/9b4e2f86e2046ae24e4b8936899fb9f2/href</a></iframe><p>Note that inside the plugin tag we have another tag ‘configuration’ where we can set our docker configs to our project such as</p><ul><li><em>useMavenSettingsForAuth (</em>we set true to set the Authentication by the Maven Settings<em>)</em></li><li><em>repository (</em>we have to informe our DockerID and the name of the image that we want, so {dockerID}/{imageName}, this is used to send our image to the docker hub.<em>)</em></li><li><em>tag </em>(<em>version/imageTag.</em>)</li><li><em>JAR_FILE (our .jar file generated by our project).</em></li></ul><h4>Docker image</h4><p>Once we have our Dockerfile set up and our pom.xml configured, we can go onto the next step to generate a docker image.<br>To do so we have to go to our project root and run the following command, which will generate a .jar file inside the Target folder.</p><pre>mvn package</pre><p>After running the ‘mvn package’ we can check for our local docker images and see if its there. We can do it by running</p><pre>docker images</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a0ZICJmw-cw6RtnSMpemAg.png" /></figure><blockquote>Notice that we have our docker image generated with the same name as we did set in the tag ‘repository’ in our pom.xml</blockquote><h4>Running Docker Image</h4><p>What better way to test an application than to run it ? So let’s do it .</p><p>We have two ways of running a docker image, the first one will run and show us the application log and the second one will run in background mode.</p><pre>docker run -p 8080:8080 {dockerID}/brand-api:0.0.1-SNAPSHOT</pre><p>To run it in background mode we just have to add a property in the command. <em>‘-d’.</em></p><pre>docker run -d -p 8080:8080 {dockerID}/brand-api:0.0.1-SNAPSHOT</pre><p>After starting up our RESTful API application we can check if it’s running by accessing this URL:</p><blockquote>localhost:8080/brand/brands</blockquote><p>As this URL represents a GET HTTP method, you can call it from a browser, i called if from Postman, but it won’t change the response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wT73WoUGPZzTaxCcVS5vWQ.png" /></figure><blockquote>There you go !! You’re applications has been Dockerized !!</blockquote><h4>What comes next ?</h4><p>Well, we have dockerized our application, but if you want to go even further and send this image to the Docker Hub, you’ll have to a few more things, let me show you how.</p><h4>Maven settings.xml</h4><p>To send our docker image to the Docker Hub, first we have to configurate the maven settings.xml, so it will be able to communicate with docker hub.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bdb9125a33d03764d0aa710524d32e00/href">https://medium.com/media/bdb9125a33d03764d0aa710524d32e00/href</a></iframe><p>With the ‘server’ tag configured, we should be good to publish it by running :</p><pre>mvn dockerfile:push</pre><p>Now if you access your account on the docker hub website you will se your docker image published there !</p><h4>That’s all folks</h4><p>Hopefully, I could help you understand a little bit about how to dockerize your Java Springboot application. Stay tuned for future articles that will be coming up soon.</p><p>If you have any comments or questions, I’d love to hear what you think.<br>You can also check my previous articles about <a href="https://medium.com/@rafaelferreiram/multithreaded-programming-in-java-627f9d314c2c">Multithreaded Programming in Java</a>, <a href="https://medium.com/@rafaelferreiram/criando-uma-cli-application-com-node-js-4b94125544d4">developing a CLI Application with Node.Js</a> and <a href="https://medium.com/@rafaelferreiram/applying-single-responsability-principle-srp-645ebf6d68a8">Applying Single Responsibility Principle (SRP)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e685d20bf47" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multithreaded Programming in Java]]></title>
            <link>https://medium.com/@rafaelferreiram/multithreaded-programming-in-java-627f9d314c2c?source=rss-874233b13d96------2</link>
            <guid isPermaLink="false">https://medium.com/p/627f9d314c2c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[parallel-processing]]></category>
            <dc:creator><![CDATA[Rafael Ferreira]]></dc:creator>
            <pubDate>Tue, 11 Feb 2020 19:42:04 GMT</pubDate>
            <atom:updated>2020-02-11T20:28:39.677Z</atom:updated>
            <content:encoded><![CDATA[<p>Writing a high-performance multithread program with ThreadPoolExecutor</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WgJKNUobbh8IQKjU-ETtMQ.jpeg" /></figure><p>I used to get chills whenever someone asked me to write a <em>Multithreaded Application, </em>I tried searching for simple tutorials on the internet but there was always a fear of concurrency and not making it work in a simple and effective way. Then I finally decided to start applying its techniques and making sure I was secure on what I was coding.</p><p>As a backend developer, I’ve had faced some challenges throughout my career and those that I like the most are refactoring and improving application performance (besides developing new functionalities and building APIs), because they’re not easy at first but it will for sure teach you lessons and once you have done it and you’ll also get confidence for the next one.</p><p>In this article, I’m going to take you through simple steps with hands-on to make a <em>Multithreaded Application </em>using the <a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/concurrent/ThreadPoolTaskExecutor.html">ThreadPoolTaskExecutor </a>from Spring 2.0 and further versions that help us manipulate threads and thus writing a high-performance code.</p><h3>But, whats ‘s a Multithread Application?</h3><p>Multi is an abbreviation for ‘Multiple’ which means more than one. So as we say ‘Multithread’ we can associate that we have more than one thread ready to do some work. So basically a multithreaded application is nothing more than a software application that can do more than a single thing at the same time with multiple threads, handling different scenarios.</p><p>Before we get started doing all the coding, I’d like to give you a quick heads up, in this article I’m presuming that you have previous knowledge on Spring Framework and MVC architecture, so all the basics on starting a Springboot project and the understanding of its layers won’t be explained on details. But if you have any questions on the topic, feel free to contact me or leave comments below.</p><h3>Let’s start coding!</h3><h4>Step One</h4><p>As I said, I’m going to take you through basic steps to write Multithreaded and the first one to it is to configure our Application class, the one responsible for starting up our Spring Application.</p><p>We are going to use some annotation such as :</p><p><em>‘@EnableAsync’, this annotations allows us to work Asynchronous.</em></p><p><em>‘@Bean’ A bean is an object that is instantiated, assembled, and otherwise managed by a Spring itself.</em></p><p><em>‘@Scope(“prototype”)’ makes this bean a singleton, invalidating it to have the same instance for more than one thread. This annotation is very important to a multithreaded application because it makes it thread-safe.</em></p><p>Notice that we have another annotation called ‘@EnableScheduling’, which allows our application to have a schedule, thus running by a specific time interval</p><p>In the same class, we’re going to write the following code, which does the initial configuration for the ThreadPoolTaskExecutor, such as setting minimum and maximum pool size and also we can tell our thread pool if we want it to wait for a task to be completed to shut down or not.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f466cd6df57c501a61696214a23dd373/href">https://medium.com/media/f466cd6df57c501a61696214a23dd373/href</a></iframe><h4>Step Two</h4><p>We’re going to create a class that will be responsible for receiving values and returning them when the TaskPoolExecutor calls it multiple times by multiple threads. To make this class able to be called by multithread and work asynchronously we’re going to implement Callable.</p><p>Some of you might be questioning why Callable and not Runnable. Well, we could use Runnable, but in this example, I want to make our thread return a value and we cannot do so using Runnable, because it’s run’ method is void.<br>And using Callable we can set a type of its return, in this case, we set an Integer as a return.</p><p>Our class will be named NumberExec, and when called it will return the sum of the number received plus one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54f07b9d0ce04b0820c43392404b0aa8/href">https://medium.com/media/54f07b9d0ce04b0820c43392404b0aa8/href</a></iframe><h4>Step Three</h4><p>Here is where all the magic happens, where we can manipulate our threads, initialize it, kill it, get its return. So let’s understand what the following code will do.</p><p>I named this class AsyncExecutor, and our first step is to get the ThreadPoolTaskExecutor configuration that we did on the Application class exposing it using the annotation ‘<a href="http://twitter.com/Bean">@Bean</a>’, and in the AsyncExecutor class we can get its value by the ApplicationContext using the getBean method passing the name of our method as a String parameter, then we use the ‘Future’ to get the return of our threads once they’re done.</p><p>Our application will have a list of numbers to call our class above, the ‘NumberExec’ and then it’ll do its own work.</p><p>I used the annotation ‘<a href="http://twitter.com/Scheduled">@Scheduled</a>(cron= “*/10 * * * * *”)’ just so we can see it running every 10 seconds.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40690a0bad3aa6e6937dbd9f0f9f8aba/href">https://medium.com/media/40690a0bad3aa6e6937dbd9f0f9f8aba/href</a></iframe><p>I also used the System.out.println to print out some info such as the number of threads in the pool to check if our configuration was being used successfully and the result of the thread.</p><p>It’s valid to understand that a multithreaded application does not follow a sequence, so the result may come in a different order every time you run it, that’s what makes the high performance.</p><p>So, if you run your Spring Application startup class you should get something like this in your console display</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*gqZFPY1q0l27e72WrTD3gQ.png" /></figure><p>With the knowledge acquired in this article, you are ready to go into the multithreaded programming world and start doing some pretty cool stuff!</p><p>That’s all folks, hopefully, I could help you understand a little bit about Multithreading and it’s importance to a high-performance application. Stay tuned for future articles that will be coming up soon.</p><p>If you have any comments or questions, I’d love to hear what you think.<br>You can also check my previous articles about <a href="https://medium.com/@rafaelferreiram/criando-uma-cli-application-com-node-js-4b94125544d4">developing a CLI Application with Node.Js</a> and <a href="https://medium.com/@rafaelferreiram/applying-single-responsability-principle-srp-645ebf6d68a8">Applying Single Responsibility Principle (SRP)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=627f9d314c2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Applying Single Responsability Principle (SRP)]]></title>
            <link>https://medium.com/@rafaelferreiram/applying-single-responsability-principle-srp-645ebf6d68a8?source=rss-874233b13d96------2</link>
            <guid isPermaLink="false">https://medium.com/p/645ebf6d68a8</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[rp]]></category>
            <category><![CDATA[solid]]></category>
            <dc:creator><![CDATA[Rafael Ferreira]]></dc:creator>
            <pubDate>Fri, 10 Jan 2020 18:18:10 GMT</pubDate>
            <atom:updated>2020-01-10T21:47:04.770Z</atom:updated>
            <content:encoded><![CDATA[<h3>Applying Single Responsibility Principle (SRP)</h3><p>SOLID Principles</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*_qjSuVrvnnBJ2Upe1aP-GA.png" /></figure><p>If you’ve been in the Software Development world for a while you might’ve heard about Clean Code Principles, which defines habits for writing good quality code, and in this article I’m going to take you through some steps that I currtently apply while coding using SRP.</p><p>But before we get started with all the technical part and the hands on, let’s understand how the Single Responsibility Principle (SRP) works and it’s importance to our code.</p><h4><strong>Single Responsibility Principle</strong></h4><p>Is one of the core SOLID principles introduced by <a href="https://pt.wikipedia.org/wiki/Robert_Cecil_Martin">Robert C. Martin</a> in one of his books “<a href="https://www.amazon.com.br/dp/B001GSTOAM/ref=dp-kindle-redirect?_encoding=UTF8&amp;btkr=1">Clean Code</a>”.</p><p>As its name already says, it stands for only one responsibility, which translating to developer’s language means that classes, functions or methods should be responsible for only one thing.</p><p>It could give you small and focused methods that combined together could achieve a larger goal and help us to reuse code instead of writing the same business rule or logic in differente places, leading us to write duplicated code.</p><h4>And why would that be a good habit to adopt while coding ?</h4><p>Because when you divide responsibilities into separeted methods and functions, our code becomes better to read, easier to understand, cleanner and last but not least, it becomes easier to maintain.</p><h4>SRP principles to our code.</h4><p>Let’s get started by applying SRP to classes, in the example down below you’ll see two models, one for Client and another one for Email before and after applying SRP ,thus we’ll be able to see the difference between a ‘Dirty Code’ and a ‘Clean Code’.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ccb7febcc9767d8a4349f8cb22b2dfda/href">https://medium.com/media/ccb7febcc9767d8a4349f8cb22b2dfda/href</a></iframe><p>We can improve our Client class by removing its responsibility of email validation, creating a new Email class that will have that responsibility.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a6d75d5e071461118c92acc98f77bf4/href">https://medium.com/media/6a6d75d5e071461118c92acc98f77bf4/href</a></iframe><p>Making sure that a class has a single responsibility makes it easier to understand what it does.</p><p>Now that we’ve wrote our Email class using SRP, let’s check how that will reflact on our Client class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de43ef95462514708b0828d2da6cc640/href">https://medium.com/media/de43ef95462514708b0828d2da6cc640/href</a></iframe><p>It’s notable that by applying SRP we can see clearly our code’s responsibility, which becomes very helpful when you’re debbuging a code like this and even when you developing new features using it as a model to keep applying SRP on further developments in the project.</p><p>That’s all folks, hopefully I could help you understand a little bit about SRP and it’s importance to our code. Stay tuned for future articles that will be coming up soon about SOLID principles and Multithreaded programming.</p><p>If you have any comments or questions, I’d love to hear what you think.<br>You can also check my previous article about <a href="https://medium.com/@rafaelferreiram/criando-uma-cli-application-com-node-js-4b94125544d4">developing a CLI Application with Node.Js</a>.</p><h4>References</h4><ul><li><a href="https://www.amazon.com.br/Clean-Code-Handbook-Software-Craftsmanship-ebook/dp/B001GSTOAM">Clean Code | A Handbook of Agile Software Craftsmanship</a></li><li><a href="https://www.amazon.com.br/Clean-Coder-Conduct-Professional-Programmers-ebook/dp/B0050JLC9Y/ref=sr_1_1?gclid=EAIaIQobChMIgffriLj55gIVDQ6RCh3eYwIsEAAYASAAEgIMj_D_BwE&amp;hvadid=326886216207&amp;hvdev=c&amp;hvlocphy=1001773&amp;hvnetw=g&amp;hvpos=1t1&amp;hvqmt=e&amp;hvrand=15117119002240747865&amp;hvtargid=kwd-298869535822&amp;keywords=the+clean+coder&amp;qid=1578673232&amp;sr=8-1">The Clean Coder | A Code of Conduct fot Professional Programmers</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=645ebf6d68a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Criando uma CLI Application com Node.js]]></title>
            <link>https://medium.com/@rafaelferreiram/criando-uma-cli-application-com-node-js-4b94125544d4?source=rss-874233b13d96------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b94125544d4</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[node-for-begginners]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Rafael Ferreira]]></dc:creator>
            <pubDate>Tue, 29 Jan 2019 00:34:01 GMT</pubDate>
            <atom:updated>2019-01-29T12:18:22.149Z</atom:updated>
            <content:encoded><![CDATA[<h4>O objetivo do artigo é desenvolver uma simples Command-Line Interface Application com Node.Js que irá consumir seriços de uma API.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*4EhLxFdy4-Hpv1I9M_bOag.jpeg" /></figure><p>As aplicações que utilizam a linha de comando de um sistema operacional são chamadas de ‘CLI Applications’ ou ‘Command-Line Interface Applications’. E eu vou mostrar pra vocês como podemos desenvolver a nossa própria CLI Application com Node.Js.</p><blockquote><strong>Criando um repostitório local</strong></blockquote><p>Para fazer isso vamos precisar criar um projeto node, e para fazermos isso criei um repositório local, qual dei o nome de CLI-Application, mas pode ser qualquer outro nome. Vamos abrir esse repositório pelo cmd e darmos o comando</p><pre>npm init -y</pre><p>para assim podermos inicializar nosso projeto Node.Js. O comando “npm init” é responsavel por fazer a inicialização de um projeto node, já o parâmetro “-y” iniciliza o projeto com as configurações do package.json default, mas caso queira inicializar com alguma configuração própria como, nome, descrição, autor, github bastar dar o comando “npm init” e ir colocando as configurações conforme aparecem no cmd.</p><blockquote><strong>Dependências do projeto</strong></blockquote><p>Bom, já temos nosso projeto Node.Js criado, agora começa a parte legal de darmos “vida” a ele. Mas para que nossa CLI Application funcione da maneira que esperamos, ela depende de algumas ferramentas, e com o <a href="https://www.npmjs.com/">NPM </a>(gerenciador de pacotes do Node) conseguimos baixar essas dependências apenas com o comando “npm install NomeDaDependencia”, podemos usar tanto o comando “npm install” como o “npm i “. <br>Para desenvolvermos nossa aplicação vamos precisar baixar 2 dependências, são elas o <a href="https://www.npmjs.com/package/axios">axios </a>e o <a href="https://www.npmjs.com/package/commander">commander</a></p><pre>npm i axios commander</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*8alrW4sOhucFlymQ6-0Tug.png" /></figure><p>Podemos ver que o npm consegue entender as duas dependências mesmo passando tudo em apenas uma linha de comando. E essas dependências ficam visíveis no arquivo package.json que foi criado no nosso repositório quando iniciamos o nosso projeto.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*5hMCU1a5Uj5fna1sRtV6jg.png" /></figure><blockquote><strong>Vamos Codar ! </strong>💻</blockquote><p>Agora que temos nosso repositório criado, nossas dependências baixadas, vamos começar a desenvolver nossa CLI Application, e para isso irei criar 3 arquivos.</p><blockquote>Service.js</blockquote><p>O primeiro irei chamar de “Service.js”, qual vai ser responsável por se comunicar com a API, no caso irei usar a <a href="https://swapi.co/">SWAPI</a> , uma API que nos retorna personagens do Star Wars. E nesse arquivo teremos o seguite código :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a42aced3632d4a43334e128c436a032/href">https://medium.com/media/8a42aced3632d4a43334e128c436a032/href</a></iframe><p>Na linha 1 estamos usando a function embutida require que é a maneira mais fácil de incluir módulos existentes em arquivos separados. O funcionamento básico do require é que ele lê o arquivo JavaScript, interpreta o script e em seguida retorna o conteúdo do objeto exports. Então nesse caso estamos buscando os módulos do axios para assim usarmos no nosso arquivo Service.Js. E na linha 2 estamos apontando a URL da API do Star Wars qual vamos consumir.</p><p>A function getPersonagens é uma function responsável por fazer uma pesquisa na API com base em um nome informado, ou seja, quando essa function for chamada será passado um nome para ela e com esse nome ela irá buscar na API do Star Wars se há algum dado lá com o nome informado.</p><p>Na linha 5 estamos pegando o valor da URL declarada na linha 2 e adicionando os parâmetros de busca, como o “/?search=” e logo após a variavél que irá conter o nome informado pelo usuário. Seguido de “&amp;formart=json”, que fala qual o formato de busca, para sabermos qual o formato correto é necessário lermos a documentação.</p><p>Note que a nossa function possui a palavra “ASYNC” na frente, o que nos informa que essa function automaticamente irá nos retornar uma <a href="https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promisse</a>, e através disso podemos manipular esse retorno, pegando o dado que queremos.</p><p>Quando dizemos para o javascript que nossa função é ASYNC, assíncrona, podemos pedir para ela esperar o retorno da execução de alguma function que iremos executar, como estamos fazendo na linha 6. Onde uso o AWAIT para dizer para o nosso código esperar pois daquela execução haverá um retorno. Assim retornando o dado com o result.data, resultado obtido através da execução da function get() do axios.</p><p>E para finalizar estamos exportando nossa function, para que ela possa ser visível em outros arquivos quando der o require desse arquivo.</p><blockquote>Personagens.js</blockquote><p>O segundo arquivo que vamos trabalhar é o Personagens.js, que será responsável por extrair apenas o nome que será inserido pelo usuario para assim fazermos a busca através desse nome, esse nosso arquivo é bem simples :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7df5ccf0efa71e6ae50539af894346ba/href">https://medium.com/media/7df5ccf0efa71e6ae50539af894346ba/href</a></iframe><p>Temos um construtor para abstrairmos o nome para dentro do nosso “Personagem” e logo após exportamos essa classe para que seja visível em outros aquivos dentro do nosso projeto.</p><p>Note que o parâmetro do nosso contrutor é um JSON, ou seja, estamos dizendo para o metodo contrutor que iremos passar um JSON para ele e dentro dele terá um parâmetro ‘nome’, qual ira ser atribuido à Personagens, através do<strong> <em>this.nome = nome</em></strong><em>.</em></p><blockquote>Index.js</blockquote><p>Depois de desenvolvermos esses dois arquivos, vamos desenvolver o arquivo principal da nossa aplicação, qual irá chamar as functions desenvolvidas e executá-las. Devido à isso o arquivo será um pouco mais extenso que os outros. Eu dei o nome de index.js para ele, e nele temos o seguinte código :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea915071b2c1427d2e4225e06c15c6d0/href">https://medium.com/media/ea915071b2c1427d2e4225e06c15c6d0/href</a></iframe><p>Na linha 5 começamos a desenvolver nossa function main, qual podemos remeter ao ‘ <strong>public</strong> <strong>static</strong> <strong>void</strong> <strong>main</strong>’ do Java. Note que na declaração do nosso main, temos o nome ‘ASYNC’ e como dito anteriormente ela é retornará uma promisse.</p><p>Iniciamos o desenvolvimento do main executando umas functions do comander, qual será responsável pela interação com a linha de comando, buscando os valores, e passando os parâmetros de chamada da nossa aplicação. Com o commander.version(), podemos colocar a versão da nossa aplicação, assim quando executarmos a chamada do nosso arquivo e passar o parâmetro ‘-V ‘ ele nos retornará a versão que setamos :</p><pre>node index.js -V</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*gqXhB4ocukU-vJdr8uRtyQ.png" /></figure><p>Agora setamos a function option do commander, qual irá nos permitir setar os parâmetros esperados, possíveis valores e uma “legenda” para os parâmetros. Como vemos na linha 7 estamos setando o parâmetro –n ou –nome, qual espera um valor onde dizemos isso por [value], e como segundo parâmetro dessa function do commander passamos a legenda, onde estou dizendo que é o “Nome do Personagem”. <br>Agora na linha 9 temos a execução do parser(), qual passamos o <strong><em>process.argv </em></strong>como parâmetro que representa o conteúdo “invocado” através da linha de comando, para assim processar os parâmetros setados e passados para a nossa aplicação.</p><p>Temos a classe Personagens.js qual tem um construtor para extrair apenas o nome contido em um JSON. E na linha 11 estamos fazendo exatamente isso, instaciando nossa classe e passando o valor que pegamos através do commander, para abstrairmos o nome. Logo em seguida dou um ‘console.log(personagem.nome)‘ para vermos se o nosso construtor está funcionando corretamente.</p><p>Com base no nome abstraido podemos realizar a busca através da function getPersonagens da Service.js qual espera um nome como parâmetro, para assim consultarmos a SWAPI e trazer os dados do personagem informado. E claro, tudo isso é realizado dentro de um trycatch justamente para tratarmos as exeções que possam acontecer.</p><p>E para que o tudo que desenvolvemos dentro do main funcione, precisamos chamar ele, o que estamos fazendo no fim do nosso arquivo na linha 23. Agora basta executarmos nosso programa, qual irei fazer buscando o personagem Darth Vader, buscando como pelo nome “<strong><em>Vader</em></strong>” e podemos fazer isso com o seguinte comando :</p><pre>node index.js -n Vader -b</pre><p>E esse foi o retorno que tivemos da SWAPI com a execução desse comando na nossa aplicação :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*3uNZi0Kz3YvCp4D0vQmoDg.png" /></figure><p>Mesmo passando apenas o sobrenome do personagem, a busca foi realizada com sucesso !</p><p>Deixarei o link para o código fonte da nossa aplicação abaixo caso necessário para consulta.</p><p><a href="https://github.com/rafaelferreiram/CLI-Application">rafaelferreiram/CLI-Application</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b94125544d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>