<?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 J. M. Rodrigues on Medium]]></title>
        <description><![CDATA[Stories by J. M. Rodrigues on Medium]]></description>
        <link>https://medium.com/@jm_rodrigues?source=rss-3a1bfa949d97------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xJfELX5a2Udd3XVewtHQ6A.jpeg</url>
            <title>Stories by J. M. Rodrigues on Medium</title>
            <link>https://medium.com/@jm_rodrigues?source=rss-3a1bfa949d97------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 12:02:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jm_rodrigues/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[Payment Gateway Integration: Ezzebank]]></title>
            <link>https://medium.com/@jm_rodrigues/payment-gateway-integration-ezzebank-f3b7a6af279e?source=rss-3a1bfa949d97------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3b7a6af279e</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[payment-gateway]]></category>
            <category><![CDATA[integration]]></category>
            <dc:creator><![CDATA[J. M. Rodrigues]]></dc:creator>
            <pubDate>Tue, 05 Mar 2024 14:10:25 GMT</pubDate>
            <atom:updated>2024-03-05T14:10:25.098Z</atom:updated>
            <content:encoded><![CDATA[<p>At this post, I&#39;m going to tell the challenges I faced integrating with another payment gateway and document the process for myself (mainly). The gateway in question here is <a href="https://dev.ezzebank.com/">Ezzebank</a>, which isn&#39;t very popular, and it&#39;s only for brazilian PIX I guess.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/0*XIYYFHF_abTcFnOM.png" /><figcaption>Generic Gateway Image 😃</figcaption></figure><p>First of all, this integration was difficulty 06/10. Specially because I only had to integrate PIX, which is a brazilian free money transfer method. This API doens&#39;t even offer the option to credit card I think, so, it&#39;s very specific.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KSBKtmigSOiq0YmI2aqbEA.png" /></figure><p>The API offers sandbox for testing environment and production endpoints. I wrongly decided to go straight to production, that I regret… just a little bit.</p><h3>Authentication</h3><p>Before making any real request to generate payment QRCode or check for payment status, you have to request the authentication endpoint, passing your client_idand client_secretwhich you receive when registering for the API usage. After that, you can use the brand new generated token response to make the API requests.</p><h3>Integration</h3><p>The integration itself was pretty much:</p><ol><li><a href="https://dev.ezzebank.com/#qrCodePix">Generate a </a><a href="https://dev.ezzebank.com/#qrCodePix">PIXQRCode</a>;</li><li><a href="https://dev.ezzebank.com/#PixPayment">Make a </a><a href="https://dev.ezzebank.com/#PixPayment">PIXPIX payment</a>;</li><li><a href="https://dev.ezzebank.com/#webhook">Receive the webhook</a> confirming the QRCode of the first step was paid;</li></ol><p>To generate the code it was pretty much requesting the appropriate endpoint passing the Authentication credentials, the value, the payer name and other related information. Then I received a Base64 image representing the QRCode, that I displayed at the screen using a simple &lt;img&gt; tag. I was using <a href="https://react.dev/"><strong>React</strong></a> at the interface, so I used the Image component of <a href="https://chakra-ui.com/"><strong>ChakraUI</strong></a> which we all know it&#39;s an img tag at the end of the day.</p><p>At the interface, I had to keep doing short-polling to check for the payment status of the QRCode. My API was in <a href="https://docs.nestjs.com/"><strong>Nest.js</strong></a>, at the API level I was storing the information of the paid status, I didn&#39;t have to request the payment gateway endpoint to check the status. As soon as I received the webhook confirming the payment, the status at my database would be updated, and therefore I would know at the interface due to the shot-polling request I was making over and over at every 2 seconds.</p><p>To make a payment (step 3) it was even easier. Just passing correct PIX information was enough, also the value. The only problem here were financial limits, but it&#39;s much more related to the account configuration.</p><h3>Webhooks</h3><p>This part of the API I found really smart. They&#39;re really extra safe about the webhooks. When you&#39;re setting up your API credentials, you define a <strong>username</strong> and <strong>password</strong>, that are used to be sent as encoded headers to your webhook endpoint. So every time you receive a webhook they have these credentials encrypted in BASE64 at the <strong>Authorization</strong> header</p><p>The second part of the validity checking of the webhook was really more interesting. At the header <strong>Verify-Signature, </strong>you receive a timestamp and a HMAC. Long story short: You have to hash the payload with the timestamp and your secret API key and afterward compare with the HMAC you received at the Verify-Signature. Kind of complex, but it&#39;s comprehensible since it&#39;s a sensible webhook.</p><p>Doing all that verification part, I can pretty much trust the payload I receive at the webhook. It&#39;s truly the payment information saying it&#39;s confirmed, and you can update your system database \o/</p><h3>Challenges</h3><p>The biggest challenge I faced was the IP restrictions of this API. The API itself doesn&#39;t segment your requests to the production endpoint and your request to the doc website: <a href="https://dev.ezzebank.com/#qrCodePix">dev.ezzebank.com</a>. When I was first making the <a href="https://dictionary.cambridge.org/dictionary/english/wip#:~:text=Meaning%20of%20WIP%20in%20English&amp;text=abbreviation%20for%20work%20in%20progress,16%2C667%20dozen%20shirts%20as%20WIP.">WIP</a> requests I got an IP restriction, and when I tried to access the API documentation page I saw a Cloudflare message saying I was blocked 🤣</p><p>Besides this fact. The IP was a true bottleneck. I was deploying my API at Heroku, doesn&#39;t have and cannot have a fixed IP. Every time <a href="https://www.heroku.com/">Heroku</a> restart it&#39;s dyno you get a brand-new address. So I had to either move to <a href="http://aws.amazon.com/">AWS</a> and use an Elastic IP or use some kind of reverse-proxy. Of course, I choose AWS 😊</p><p>So I had to change the architecture of my system just to make this integration possible. It was a hard decision, but it ended up paying great dividends, AWS was a really better option when the system scaled.</p><p>Quite some learnings, I would rate this api 07/10, specially because the Webhook endpoint has to be fixed, I would rather say the webhook when requesting the payment QRCode… anyway, it was a good experience, quite some learning. Hopefully you also learned something, since you got that far 😁</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3b7a6af279e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Desenvolvendo um Quadro Kanban para Gestão de Conversas: Uma Jornada de Inovação]]></title>
            <link>https://medium.com/@jm_rodrigues/desenvolvendo-um-quadro-kanban-para-gest%C3%A3o-de-conversas-uma-jornada-de-inova%C3%A7%C3%A3o-caed0d1fb196?source=rss-3a1bfa949d97------2</link>
            <guid isPermaLink="false">https://medium.com/p/caed0d1fb196</guid>
            <category><![CDATA[project-management]]></category>
            <category><![CDATA[mvp]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[kanban]]></category>
            <dc:creator><![CDATA[J. M. Rodrigues]]></dc:creator>
            <pubDate>Tue, 13 Feb 2024 12:07:26 GMT</pubDate>
            <atom:updated>2024-02-13T12:07:26.541Z</atom:updated>
            <content:encoded><![CDATA[<p>Na busca por eficiência e produtividade, as empresas enfrentam o desafio de gerenciar conversas e contatos maneira cada vez mais ágil e colaborativa. Nesse cenário dinâmico, ferramentas de gestão visual como <a href="https://www.atlassian.com/br/agile/kanban/boards"><strong>quadros Kanban</strong></a> emergem como aliados, proporcionando uma visão clara e organizada do fluxo de trabalho.</p><p>Nesse post pretendo abordar minha perspectiva e aprendizados ao desenvolver um <strong>software de quadros Kanban</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_IBb2oY97I_Vvpuw.jpg" /><figcaption>Exemplo de quadro Kanban</figcaption></figure><h4>Tecnologias e Tradeoffs</h4><p>Desenvolver e integrar o quadro Kanban ao nosso fork do Chatwoot para mim não chegou a ser um desafio, mas ainda assim foi estimulante. Precisei combinar uma conexão <a href="https://pt.wikipedia.org/wiki/WebSocket#:~:text=WebSocket%20%C3%A9%20uma%20tecnologia%20que,cliente%20ou%20servidor%20de%20aplicativos.">WebSocket</a> para funcionalidades em tempo real e aproveitei uma API construída em Ruby on Rails, utilizando uma API de Integração em Laravel, fiz uma solução eficiente em um curto período.</p><p>Precisei fazer um estudo a respeito do <a href="https://pt.wikipedia.org/wiki/WebSocket#:~:text=WebSocket%20%C3%A9%20uma%20tecnologia%20que,cliente%20ou%20servidor%20de%20aplicativos.">WebSocket</a> do Chatwoot, já que o cenário ideal da nossa aplicação seria rodar em cima deste <a href="https://pt.wikipedia.org/wiki/WebSocket#:~:text=WebSocket%20%C3%A9%20uma%20tecnologia%20que,cliente%20ou%20servidor%20de%20aplicativos.">WebSocket</a>, alterando e movendo as conversas do Chatwoot de coluna em tempo-real, sem a necessidade de utilizar padrões como <a href="https://www.geeksforgeeks.org/what-is-long-polling-and-short-polling/">short-polling</a>, por exemplo.</p><h4>Stack</h4><p>Eu escolhi utilizar o Vue.js para desenvolver esta aplicação porque a nossa estratégia era ter a aplicação rodando em <strong>isolamento</strong>, rodando dentro de outra aplicação como <strong>iframe</strong> e até mesmo rodando numa aplicação Vue.js como <strong>componente</strong>. Tendo em vista essa versatilidade e a minha biblioteca de Draggable preferida (<a href="https://www.npmjs.com/package/vuedraggable">vue-draggable</a>), não tive nenhuma outra opção à altura além do <a href="https://vuejs.org/">Vue.js</a> 😁.</p><p>Talvez a parte mais desafiadora do projeto foi exportar e importar como componente numa aplicação <a href="https://vuejs.org/">Vue.js</a>, mas no fim das contas bastou algumas alterações no arquivo de vue.config.js e a alteração do <strong>id</strong> do componente raiz que renderiza o <a href="https://vuejs.org/">Vue.js</a>:</p><pre>// Arquivo main.js:<br>new Vue({<br>    render: (h) =&gt; h(App),<br>}).$mount(&quot;#kanban-app&quot;);</pre><h4>Visual e Inspirações</h4><p>As melhores aplicações Kanban hoje em dia na minha opinião são: Trello e Jira, ao menos as melhores dentre as que tive contato. Sendo assim, o meu benchmarking visual foi baseado nelas. A versão final do nosso produto não ficou similar, até porque não era a ideia, mas serviu de ótimo ponto de partida para que eu pudesse implementar as funcionalidades da aplicação.</p><p>Atualmente temos uma Designer UX/UI muito competente na nossa equipe, ela foi a responsável por toda parte visual e de usabilidade do projeto.</p><blockquote>Inicialmente, João concebeu o design do primeiro MVP (Minimum Viable Product) para avaliar a viabilidade e os requisitos essenciais do projeto. Com o MVP inicial validado, iniciei meu trabalho como UX/UI Designer, primeiramente interagindo com os stakeholders para compreender quais informações seriam pertinentes em cada card do quadro de gerenciamento de conversas. Após essa etapa, busquei referências em quadros kanban mais conhecidos pelos usuários, como o Trello e o Jira, e priorizei, por meio do design, as informações mais relevantes, tais como o nome do setor correspondente, a foto do atendente, foto do cliente, tags e outras informações. <br>- <a href="https://www.linkedin.com/in/daniellecaires/">Danielle Caires</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZGCeJcYXKLwxR9vGbbkTBA.png" /><figcaption>Nosso Quadro Kanban 😃 (MVP)</figcaption></figure><h4>Benefícios da Aplicação</h4><p>Os nossos usuários agora vão podem visualizar as conversas da nossa aplicação numa perspectiva de quadro, separando e movimentando as conversas entre as colunas, customizando de maneira adaptável as colunas e a automação do direcionamento pelo nosso chatbot 🤖.</p><p>Bem, no fim das contas, o que espero é facilitar a maneira que nossos usuários gerenciam conversas hoje em dia 😅🙏🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=caed0d1fb196" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Integrate WooCommerce With Saipos (external API)]]></title>
            <link>https://medium.com/@jm_rodrigues/how-to-integrate-woocommerce-with-saipos-external-api-29dd53d1979c?source=rss-3a1bfa949d97------2</link>
            <guid isPermaLink="false">https://medium.com/p/29dd53d1979c</guid>
            <category><![CDATA[api-integration]]></category>
            <category><![CDATA[wordpress]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[woocommerce]]></category>
            <dc:creator><![CDATA[J. M. Rodrigues]]></dc:creator>
            <pubDate>Wed, 23 Aug 2023 18:16:13 GMT</pubDate>
            <atom:updated>2023-08-23T18:16:13.607Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, we’re diving into the dynamic world of WooCommerce integrations, particularly with <a href="https://saipos.com/">Saipos</a>. Whether you’re a developer looking for a hands-on guide or simply curious about how WooCommerce can work with Saipos or some external API, you’re in the right place. I’ll break down the steps I&#39;ve followed in order to make this integration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ntZOOHNFpQ0Zei3EqpNhSg.jpeg" /><figcaption>Woo is the open-source ecommerce platform that helps merchants and developers build successful businesses for the long term.</figcaption></figure><p>First off, let’s briefly introduce <a href="https://saipos.com/">Saipos</a> for those unfamiliar. <a href="https://saipos.com/">Saipos</a> is a solution for the restaurant business, it offers diverse service modules that adapt to various restaurant styles — whether it’s table service, ticket-based, or counter service. If you&#39;re working with some ecommerce that is restaurant like, Saipos can be a way to go.</p><p>To start, we’ll use the functions.php file to test our integration. This allows us to experiment and ensure the integration works smoothly. Once we’ve got everything running smoothly, we’ll transition to creating a dedicated WordPress plugin for a permanent solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fRj_Tx4X46pA2khMvmk8Kg.png" /><figcaption>Appearance → Theme File Editor</figcaption></figure><p>In the world of WooCommerce, hooks are your best friend for integrating external systems. For our integration, we’ll be utilizing hooks to make POST requests to the Saipos API at specific points in the order process. These hooks are pivotal in orchestrating a seamless connection between WooCommerce and Saipos. Check out this Stack Overflow post for guidance: <a href="https://stackoverflow.com/questions/37868183/woocommerce-new-order-action-get-order-information">stackoverflow.com/questions/37868183/woocommerce-new-order-action-get-order-information</a>.</p><p>During our journey, I discovered an essential insight. I initially used the woocommerce_new_order hook to access order items, only to realize that it didn&#39;t grant us the desired access. Thankfully, I&#39;ve found a solution in the form of the woocommerce_checkout_order_processed hook. This change proved vital in successfully accessing and handling order items. Find more details here: <a href="https://stackoverflow.com/a/71456129">stackoverflow.com/a/71456129</a>.</p><pre>&lt;?php<br>add_action(&#39;woocommerce_checkout_order_processed&#39;, &#39;saipos_api_integration&#39;, 10, 10);<br>function saipos_api_integration($order_id) { }</pre><p>In order to Saipos accept our items we need to parse them to a specific object format, here&#39;s the method I created to create a simple item reference and insert to the array of items expected by Saipos:</p><pre>function getOrderItems($total_order_items)<br>{<br>    $items_to_return = [];<br>    foreach ($total_order_items as $item_key =&gt; $item) {<br>        $item_data    = $item-&gt;get_data();<br>        $product_name = $item_data[&#39;name&#39;];<br>        $quantity     = $item_data[&#39;quantity&#39;];<br>        $product      = $item-&gt;get_product();<br>        $item_object  = [<br>            &#39;integration_code&#39; =&gt; &#39;1234&#39;,<br>            &#39;desc_item&#39; =&gt; $product_name,<br>            &#39;quantity&#39; =&gt; $quantity,<br>            &#39;unit_price&#39; =&gt; floatval($product-&gt;get_price()),<br>            &#39;notes&#39; =&gt; &#39;&#39;,<br>            &#39;choice_items&#39; =&gt; [],<br>        ];<br>        $items_to_return[] = $item_object;<br>    }<br>    return $items_to_return;<br>}</pre><blockquote>You could indeed explore this code further and find the fields that fits you the best, I didn&#39;t need the &#39;notes&#39; or &#39;choice_items&#39;, therefore I left those empty. To dig a little deeper on the possible fields I recommend you to <strong><em>var_dump </em></strong><em>the produt and/or item_data.</em></blockquote><p>Saipos API reference to create an order: <a href="https://saipos-docs-order-api.readme.io/reference/create-order">link here</a>.</p><p>With our order items in hand, we crafted the necessary payload and started sending requests to the Saipos API. This phase marks a turning point, where we bring our integration to life by interacting with the API. The Saipos API documentation and details can be found <a href="http://saipos-docs-order-api.readme.io/reference/autentica%C3%A7%C3%A3o"><strong>here</strong></a><strong>.</strong></p><p>For obtaining the API token, we encapsulated the process in a function named getTokenSaipos. This function handles the authentication by making a secure POST request to the Saipos API. The Brazilian character quirks you may encounter are due to Saipos&#39; origin.</p><pre>function getTokenSaipos()<br>{<br>    $api_url = &#39;https://homolog-order-api.saipos.com/auth&#39;;<br>    $request_args = array(<br>        &#39;headers&#39; =&gt; array(<br>            &#39;accept&#39; =&gt; &#39;application/json&#39;,<br>            &#39;content-type&#39; =&gt; &#39;application/json&#39;,<br>        ),<br>        &#39;body&#39; =&gt; json_encode(array(<br>            &#39;idPartner&#39; =&gt; &#39;id_partner_here&#39;,<br>            &#39;secret&#39; =&gt; &#39;secret_here&#39;,<br>        )),<br>    );<br><br>    $response = wp_safe_remote_post($api_url, $request_args);<br><br>    if (is_wp_error($response)) {<br>        error_log(&#39;Error: &#39; . $response-&gt;get_error_message());<br>        return &#39;Response body: &#39; . wp_remote_retrieve_body($response);<br>    } else {<br>        $response_body = wp_remote_retrieve_body($response);<br>        return $response_body;<br>    }<br>}</pre><p>After acquiring the token, we proceeded to make the POST request to the Saipos API. If any issues arise during this process, error messages are logged so you can debug.</p><p>After acquiring the token, we proceeded to make the POST request to the Saipos API to create the order. The complete code for this step can be found on my <a href="https://github.com/matheus-rodrigues00/saipos_woocommerce_integration_plugin">GitHub repository here</a>. Keep in mind that you might need to make adjustments to the code to suit your specific requirements and ensure the integration remains stable and reliable.</p><p>Once I was confident that my integration was working seamlessly, Idecided to create a dedicated WordPress plugin for it. To start, I created a new folder with the name of my plugin, as well as a PHP file with the same name, &quot;saipos_integration&quot;.</p><p>In the “saipos_integration.php” file, it’s essential to include the following headers at the beginning of the file. These headers provide crucial information about the plugin to WordPress and ensure its proper functioning:</p><pre>/**<br> * Plugin Name: Saipos Integration<br> * Description: Integrates WooCommerce with Saipos API<br> * Version: 1.0.0<br> * Author: Your Name<br> * Author URI: Your Author URI<br> * Text Domain: saipos-integration<br> */</pre><p>Feel free to make the necessary adjustments to the plugin name, description, version, and other details according to your preferences.</p><p>With the headers in place, your integration plugin is good to go. Now place your PHP code below the header, zip the folder and publish at the WordPress page.</p><p>As a final step, remember to remove any references to the integration code from the functions.php file before activating the plugin, this avoids conflicts.</p><p>I hope this article has provided you with valuable insights into integrating WooCommerce with the Saipos API. Remember, you can find the complete code for this integration on my GitHub repository <a href="https://github.com/matheus-rodrigues00/saipos_woocommerce_integration_plugin">here</a>. If you have any questions or need further assistance, feel free to reach out to me on Telegram (<a href="https://t.me/joao_rodrigues1">@joao_rodrigues1</a>). Happy coding!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/0*5Cxq8GMJoZmgHtyd.jpg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29dd53d1979c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing PHP Application: Efficient JSON Compression for Enhanced Performance]]></title>
            <link>https://medium.com/@jm_rodrigues/optimizing-php-application-efficient-json-compression-for-enhanced-performance-8e6ba6e5e7e5?source=rss-3a1bfa949d97------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e6ba6e5e7e5</guid>
            <category><![CDATA[compression]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[J. M. Rodrigues]]></dc:creator>
            <pubDate>Mon, 24 Jul 2023 12:03:09 GMT</pubDate>
            <atom:updated>2023-07-24T12:03:09.641Z</atom:updated>
            <content:encoded><![CDATA[<p>As web applications grow, handling large datasets efficiently becomes crucial to maintain optimal performance. In this article, I’ll discuss the challenge I faced with a table storing large JSON datasets for selects in my PHP application and how I devised a solution for better storage and data transfer by compressing the JSON data and storing it in the database as base64-encoded strings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*SH_q32qUhd3Y-nl5DEYQWg.png" /><figcaption>JSON Compression Optimization</figcaption></figure><p>Before the optimization, JSON datasets occupied significant storage space and caused slow data transfer, hampering the application’s performance. To tackle this, I decided to compress the JSON data. Leveraging PHP’s built-in gzcompress() function, I compressed the JSON string, significantly reducing its size.</p><pre>$compressed_json = gzcompress($my_json), 9);</pre><p>gzcompress() is a built-in PHP function that enables data compression using the Zlib library. It takes a string as input and compresses it using the DEFLATE compression algorithm. This algorithm effectively reduces the size of the input string, making it ideal for minimizing data storage requirements and optimizing data transfer over networks. The function allows developers to specify an optional compression level ranging from 0 (no compression) to 9 (maximum compression). Higher compression levels result in smaller output at the cost of increased processing time.</p><p>To effectively store the compressed data in the database, I couldn’t directly save it as-is due to database limitations. Instead, I encoded the compressed data into base64 format, as it only contains utf-8 characters. This clever approach allowed me to store the compressed data efficiently in the database without any data loss.</p><pre>$encoded_compression = base64_encode($compressed_json),</pre><p>When it comes to retrieving the data, I needed to reverse the process to get the original JSON format. To achieve this, It&#39;s pretty much decoding the base64 string with base64_decode()and then decompress it using the gzuncompress() function.</p><pre>$decoded_compression = base64_decode($encoded_compression);<br>$uncompressed_json = gzuncompress($decoded_compression);</pre><p>The results of this optimization were considerable. On average, the JSON data size reduced from 110 KBs to around 16 KBs. This reduction in data size not only saved substantial database storage space but also improved the time it took for the API to answer calls for this specific endpoint.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e6ba6e5e7e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[04. TLDR Communication Design Patterns in the Backend [Node.js] — Push]]></title>
            <link>https://medium.com/@jm_rodrigues/04-tldr-communication-design-patterns-in-the-backend-node-js-push-fe109837a43e?source=rss-3a1bfa949d97------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe109837a43e</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[protocol]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[J. M. Rodrigues]]></dc:creator>
            <pubDate>Mon, 22 May 2023 15:20:57 GMT</pubDate>
            <atom:updated>2023-05-22T15:20:57.695Z</atom:updated>
            <content:encoded><![CDATA[<h3>04. TLDR Communication Design Patterns in the Backend [Node.js] — Push</h3><p>Did you ever wonder how do you get notifications in your phone without having to request that information? How does that happen? How is that even possible? Welcome to the <strong>Push</strong> Communication Pattern. Where information can be sent without the client request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yb88njBxgWimg6zsNCahiQ.jpeg" /><figcaption>You just got new messages. But how does you get notified?</figcaption></figure><p>So, how do you get notified? The answer is simple. When you first start your application as a <strong>client</strong>, you establish a certain connection to the <strong>server, </strong>and this connection pretty much never closes. Whenever WhatsApp or Messenger notices that there is a new message to you, they simply <strong>push </strong>you this notification.</p><p>So, what do you need to implement the beautiful pattern in your chat application or any other that needs to send users non-requested information?</p><ul><li>You need to implement the unidirectional connection using some bidirectional protocol (it can be a Web Socket);</li><li>You need to establish from the client-side this connection and make sure it keeps open as long as the client is connected to the internet;</li></ul><h4>Pros</h4><p>What are the pros of this pattern? Pretty straight, as the <strong>server </strong>you can send the information that you want, by the time you want to your clients. You don&#39;t need to somehow force that request or be passive 100% of the time.</p><h4>Cons</h4><p>What are the cons of this pattern? The client needs to be connected to the internet 100% of the time, otherwise how can you send them notifications? Well, you can actually send, but they&#39;re not going to receive it. The other con is that the client might not be able to handle all the data you&#39;re sending.</p><h4>Take care!</h4><p>Did you ever wonder if YouTube sent you all the new videos upload notifications from the 1000 channels you might be subscribed to? You as the client might not be able to handle that much of information. This is the biggest downside of this pattern, the one that you as the server needs to take care of.</p><h3>Implementation in Node.</h3><ol><li>Initialize an index.js file like that, or just pick the code from <a href="https://github.com/matheus-rodrigues00/backend-communication-patterns/tree/main/Push">this repository.</a></li></ol><pre>const http = require(&quot;http&quot;);<br>const WebSocketServer = require(&quot;websocket&quot;).server;<br><br>const httpserver = http.createServer();<br>const websocket = new WebSocketServer({ httpServer: httpserver });<br><br>httpserver.listen(8080, () =&gt;<br>  console.log(&quot;Server started! Listening on port 8080&quot;)<br>);<br><br>let connections = [];<br><br>websocket.on(&quot;request&quot;, (request) =&gt; {<br>  const connection = request.accept(null, request.origin);<br>  connection.on(&quot;message&quot;, (message) =&gt; {<br>    connections.forEach((c) =&gt;<br>      c.send(`User-${connection.socket.remotePort} says: ${message.utf8Data}`)<br>    );<br>  });<br><br>  connections.push(connection);<br>  connections.forEach((c) =&gt;<br>    c.send(`User-${connection.socket.remotePort} just connected.`)<br>  );<br>});</pre><p>2. Open a couple of browser tabs and run the following code:</p><pre>let ws = new WebSocket(&quot;ws://localhost:8080&quot;);<br>ws.onmessage = message =&gt; console.log(`Received: ${message.data}`);</pre><p>3. Pick some tab and run the following line to say hello</p><pre>ws.send(&quot;Hello! I&#39;m client&quot;);</pre><p>That&#39;s it. You just ran your Push message 😃. You should be able to see in all the other consoles the message you sent, like:</p><blockquote>Received: User-58206 says: Hi other users</blockquote><p>One code improvement you could make in the code is to filter the message from the own user 😉. I&#39;d appreciate your claps if you liked 😌.</p><figure><img alt="A board on top of a tble saying goodbye friends" src="https://cdn-images-1.medium.com/max/1000/0*tscxjnfjbKQgphst" /><figcaption>See you soon 🤗</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe109837a43e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[03. Communication Design Patterns in the Backend [Node.js] — Syncronous vs. Asyncronous]]></title>
            <link>https://medium.com/@jm_rodrigues/03-communication-design-patterns-in-the-backend-node-js-syncronous-vs-asyncronous-77f71b430bb4?source=rss-3a1bfa949d97------2</link>
            <guid isPermaLink="false">https://medium.com/p/77f71b430bb4</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[protocol]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[J. M. Rodrigues]]></dc:creator>
            <pubDate>Fri, 19 May 2023 18:41:00 GMT</pubDate>
            <atom:updated>2023-05-22T15:04:25.170Z</atom:updated>
            <content:encoded><![CDATA[<h3>03. TLDR Communication Design Patterns in the Backend [Node.js] — Syncronous vs. Asyncronous</h3><p>So, you know how we communicate with our backend, right? It’s like this epic battle between synchronous and asynchronous communication. It’s like having a dilemma between <strong>wanting things right</strong> now or <strong>moving on</strong> like we don&#39;t care. Briefly, <strong>synchronous</strong> communication is all like, &quot;Hey server, I’m sending you this request, and I demand an immediate response!&quot; But <strong>asynchronous</strong> communication is more like, &quot;Chill out, man! I’m sending you this request, and I’ll go on with my business while you take your time to send me the response&quot;.</p><figure><img alt="Demonstration of syncronous versus asyncronous with arrows indicating the difference. Asyncronous some arrows goes out and then goes in at the appropriate time. Syncronous the arrows go straight down." src="https://cdn-images-1.medium.com/max/1024/1*xDaiMh3IuWt1cpF-n15xjw.png" /><figcaption>The dilemma, should I do it synchronously or asynchronously?</figcaption></figure><p>Just so we be clear about the definitions.</p><blockquote><strong><em>Synchronous Communication:</em></strong><em> </em>It’s like making a phone call and waiting on the line for the other person to answer and have a conversation in real-time.</blockquote><blockquote><strong><em>Asynchronous Communication:</em></strong><em> </em>It’s like sending a text message to someone and going about your day while waiting for their response to come in at their convenience.</blockquote><h4>Syncronous</h4><p>Bringing to our software development world. When your machine is doing a syncronous <a href="https://en.wikipedia.org/wiki/Input/output">I/O</a> operation it&#39;s blocked. There is no code it can execute in the meanwhile, it just waits. The machine only unblocks when the operation is finished. One example is trying to open a file syncronously in Node.js like below. The Node.js protagonist (Event Loop) only moves on when the file is finally open. It&#39;s completely in <strong>sync</strong>.</p><pre>// Here&#39;s an example of opening a file syncronously<br>const fs = require(&#39;fs&#39;);<br><br>try {<br>  // Open the file synchronously<br>  const data = fs.readFileSync(&#39;myfile.txt&#39;, &#39;utf8&#39;);<br>  console.log(data);<br>} catch (err) {<br>  console.error(err);<br>}</pre><p><a href="https://github.com/matheus-rodrigues00/backend-communication-patterns/tree/main/AsynSync"><strong>source_code</strong></a></p><h4>Asyncronous</h4><p>In other hand, <strong>asyncronous</strong>, the machine keeps doing everything else. The thread that asks for an asyncronous operation doesn&#39;t stop and wait until the operation is finished, if there is other code to execute, it does. When the operation is finally finished, it resumes where it once stopped on the code block.</p><pre><br>const fs = require(&#39;fs&#39;);<br>// by simply reading the file like that it&#39;s asyncronous. The event loop will<br>// not stop until the file is completely loaded<br>fs.readFile(&#39;myfile.txt&#39;, &#39;utf8&#39;, (err, data) =&gt; {<br>  if (err) {<br>    console.error(err);<br>  } else {<br>    console.log(data);<br>  }<br>});<br>console.log(&quot;Moving on, carring about my own business :D&quot;);</pre><p><a href="https://github.com/matheus-rodrigues00/backend-communication-patterns/tree/main/AsynSync"><strong>source_code</strong></a></p><p>The question that arises is, how the fridge it knows when the <strong>async</strong> operation is finished? There are two main strategies:</p><ul><li><a href="https://en.wikipedia.org/wiki/Epoll"><strong>epoll</strong></a>: It keeps checking if the operation is finished;</li><li><a href="https://en.wikipedia.org/wiki/Io_uring"><strong>io_uring</strong></a>: It receives a callback when the operation is finished;</li><li><a href="https://en.wikipedia.org/wiki/Kqueue"><strong>k_queue</strong></a>: It monitors file descriptions;</li><li><a href="https://en.wikipedia.org/wiki/Input/output_completion_port"><strong>IOCP</strong></a>: A port is notified when the operation is finished;</li></ul><p>It&#39;s not much of a criteria of the <strong>language</strong> or the <strong>runtime</strong> to choose which one of those to pick. The <strong>OS</strong> is the one who chooses. Node.js for example works differently depending on the <strong>OS</strong> it&#39;s running.</p><blockquote>Node.js on Linux uses <a href="https://en.wikipedia.org/wiki/Epoll"><strong>epoll</strong></a><br>Node.js on MacOS uses <a href="https://en.wikipedia.org/wiki/Kqueue"><strong>k_queue</strong></a><strong><br></strong>Node.js on Windows uses<strong> </strong><a href="https://en.wikipedia.org/wiki/Input/output_completion_port"><strong>IOCP</strong></a></blockquote><p>If you want to dive a little deeper on these concepts, just follow the corresponding links on the short descriptions above.</p><h4>Where Else?</h4><p><strong>Sync - Async </strong>paradigm is everywhere on backend development. Here are some places you will find it:</p><ul><li>Asynchronous Programming (promises/futures)</li><li>Asynchronous backend processing</li><li>Asynchronous commits in Postgres</li><li>Asynchronous replication</li><li>Asynchronous OS fsync (fs cache)</li></ul><p>If you want more examples of sync-async operations, just check the <a href="https://github.com/matheus-rodrigues00/backend-communication-patterns/tree/main/AsynSync"><strong>GitHub Source Code Repository</strong></a>. Also connect with me on GitHub, I&#39;d be happy to see your projects and talk about it. Here is my profile, <a href="https://github.com/matheus-rodrigues00">matheus-rodrigues00</a> 🤗🫡. Any questions or improvements, don&#39;t hesitate to comment, I&#39;d be happy to hear.</p><figure><img alt="A board on top of a tble saying goodbye friends" src="https://cdn-images-1.medium.com/max/1000/0*tscxjnfjbKQgphst" /><figcaption>See you soon 🤗</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77f71b430bb4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[02. TLDR Communication Design Patterns in the Backend [Node.js] — Request-Response]]></title>
            <link>https://medium.com/@jm_rodrigues/02-tldr-communication-design-patterns-in-the-backend-node-js-request-response-e36f3e4f3afa?source=rss-3a1bfa949d97------2</link>
            <guid isPermaLink="false">https://medium.com/p/e36f3e4f3afa</guid>
            <category><![CDATA[protocol]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[J. M. Rodrigues]]></dc:creator>
            <pubDate>Fri, 19 May 2023 12:13:46 GMT</pubDate>
            <atom:updated>2023-05-19T12:13:46.024Z</atom:updated>
            <content:encoded><![CDATA[<h3>02. TLDR Communication Design Patterns in the Backend [Node.js] — Request-Response</h3><p>The more classic, the simplest and the one that is everywhere. Lo and behold, Request-Response. The one that is by far the most used communication pattern, not only in the backend. Let’s understand overall how it works and dive a little deeper, in case you already know the big picture of this pattern.</p><figure><img alt="A request response simple image, there are two yellow squares on the side of one another. There are two arrows, one going out from the Requestor representing the Request and going into the Provider. Also other arrow going out of the Provider representing the Reponse, that is going into the Requestor." src="https://cdn-images-1.medium.com/max/372/0*tuDdCJAM1iBYWK60.png" /><figcaption>As simple as appears to be.</figcaption></figure><h4>What is this pattern about?</h4><p>Let’s define a few things. First of all, what is this (Requestor/Client) and (Provider/Server)? It’s the one that holds the initiative in this protocol. Suppose that you’re accessing google.com, your browser is the Requestor/Client. On the other hand the Provider/Server is the receptor of the request, in the google.com example is the google.com application.</p><h4>Workflow Example</h4><p>You’re accessing this Medium article by your phone. Your phone request to thebrowser, which then makes a request to Meddium server when you enter on the endpoint of this article, the Medium interface then makes a request for the Medium backend, which can and probably makes a request to a database. The events bounces back, Medium database responds Medium backend with the content of this article, which responds to Medium interface that shows to you on the screen this Medium article. Just to be clear, this doesn’t happen that syncronous as it appears. The Medium interface may be available to you on the browser before the backend request the database for example.</p><figure><img alt="A request chain example. There are circles representing the entities like your phone, browser and medium backend. Also there are arrows connecting them representing the requests being made." src="https://cdn-images-1.medium.com/max/545/1*LklmI8mciAwhxqnckVLjkg.png" /><figcaption>Request chain</figcaption></figure><figure><img alt="A response chain example. There are circles representing the entities like your phone, browser and medium backend. Also there are arrows connecting them representing the response being made. It’s going backwards as opposed to the requests." src="https://cdn-images-1.medium.com/max/577/1*7wV_76M8Z4R0CNt-zvrOjQ.png" /><figcaption>Response chain</figcaption></figure><h4>Which Protocols Uses It?</h4><p>As we saw, pretty much all of the most common protocols.</p><ul><li>HTTP, DNS, SSH, Web</li><li>APIs (REST/ GraphQL / SOAP)</li><li>SQL and Database Protocols</li><li>Much more…</li></ul><blockquote>When your phone is accessing the browser which is acessing Medium Domain, you’re using HTTP and DNS, which are normally used in HTTP.</blockquote><blockquote>When Meddium backend is querying the database they’re using SQL or some other protocol which is using the request-response pattern.</blockquote><h4>Anatomy of a Request-Response on HTTP</h4><p>The client and the server makes an agreement about the structure of the request, in case of HTTP it’s like that:</p><blockquote>GET / HTTP/1.1<br>Headers<br>&lt;CRLF&gt;<br>BODY</blockquote><ol><li>The first line you define the verb and the <strong>HTTP</strong> version you’re using;</li><li>Headers provide additional info, like the user-agent which in the case of your cellphone will be, guess what, your cellphone device type and <strong>OS</strong>;</li><li><strong>&lt;CLRF&gt;</strong> just represents a blank like for separation purposes;</li><li>The <strong>BODY</strong> can contain data that you may use in a <strong>POST </strong>or <strong>PUT </strong>request;</li></ol><h4>Unfortunatelly… it doesn’t work anywhere</h4><p>There are situations that you may and will find in your development journey that the simple Request-Response protocol isn’t well suited, like the follwing examples:</p><ul><li>Chatting applications</li><li>Notifications service</li><li>Long requests applications</li></ul><p>You may even arguee with some topic, but be open minded to understand this communication patterns as tools, for chat applications for example, don’t just make it using Request-Responses in the simplest form, pick a WebSocket (which will be in some manner be using Request-Response).</p><h4>Node.js Request-Response example</h4><p>If you want to see a simple Node.js example here is the repository: <a href="https://github.com/matheus-rodrigues00/backend-communication-patterns/tree/main/RequestResponse"><strong>GitHub RequestResponse Repository</strong></a></p><p>If you have any question or observation feel free to comment, I’m constantly learning and would be really happy to understand better some misconception that I may have.</p><p>I would really appreciate if you connect with me on <a href="https://github.com/matheus-rodrigues00"><strong>GitHub (matheus-rodrigues00)</strong></a>, feel free to reach me to talk about your <strong>Node.js</strong> open-source or personal project, I’d be happy to give you some advice or to learn something new.</p><figure><img alt="A board on top of a tble saying goodbye friends" src="https://cdn-images-1.medium.com/max/1000/0*tscxjnfjbKQgphst" /><figcaption>See you soon 🤗</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e36f3e4f3afa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[01. Communication Design Patterns in the Backend [Node.js] — Overview]]></title>
            <link>https://medium.com/@jm_rodrigues/01-communication-design-patterns-in-the-backend-node-js-overview-b079be0c61a7?source=rss-3a1bfa949d97------2</link>
            <guid isPermaLink="false">https://medium.com/p/b079be0c61a7</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[protocol]]></category>
            <dc:creator><![CDATA[J. M. Rodrigues]]></dc:creator>
            <pubDate>Fri, 19 May 2023 12:11:24 GMT</pubDate>
            <atom:updated>2023-05-19T12:14:07.783Z</atom:updated>
            <content:encoded><![CDATA[<h3>01. TLDR Communication Design Patterns in the Backend [Node.js] — Overview</h3><p>This is a series related to communication design patterns in the backend. I&#39;ve picked Node.js to exemplify because it&#39;s my favorite backend choice any day of the week, but you can easily abstract the Node.js code to your favorite flavour of backend, since we’re going to be talking at an abstract level. Java developers, please don&#39;t hate me :D.</p><figure><img alt="A bunch of code in a screen, merely representative" src="https://cdn-images-1.medium.com/max/1000/0*efEjlqM1aD0XBPYr" /><figcaption>A bunch of code. We’re developers after all.</figcaption></figure><p>Let’s dive a litlte in the reasons why it would be great to have this knowledge.</p><h4>Development Proeficiency</h4><p>Learning this patterns can improve drastically your proeficiency as a whole in software development, even if your main focus isn&#39;t backend itself. Organizing the code based protocols best practices will for sure improve the mantainability of your codebase for your and for your peers developers. You will be at the very least able to talk about this in a developer conversation 😉.</p><h4>Performance and Scalability</h4><p>Understanding how things work under the hood allow you to squeeze and improve the performance of your applications almost ad infinitum. Understaning more deeply how the request-response pattern or the difference between long polling and short polling (yes, there is different types of polling) will allow you to pick the better choice and better scale your applications, also making them more performant by picking the best-suited HTTP version for example.</p><h4>Problem-Solving Skills</h4><p>Studying communication design patterns can drastically expand your problem-solving skills, it exposes you to various architectural challenges and their solutions, by that you can build your repertoir. Think of your knowledge as a tool box, when the opportunity appears for you to apply this patterns, it will be there if you know them well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*FB4xAkdfRLP58Xzt" /><figcaption>This will be you, happily coding after learning all of these patterns.</figcaption></figure><p>The patterns we&#39;re going to be studying are the following:</p><ol><li>Request-Response</li><li>Syncronous workloads vs. Asynchronous worloads</li><li>Push</li><li>Short Polling</li><li>Long Polling</li><li>Sever Sent Events (SSE)</li><li>Publish Subscribe (Pub/Sub)</li><li>Multiplexing vs. Demultiplexing</li><li>Stateful vs. Stateless</li><li>Sidecar Pattern</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*Doyzc36_efwR7Xsz" /><figcaption>See You Later my friend 🫡</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b079be0c61a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create Custom Base64 Upload CKEditor]]></title>
            <link>https://medium.com/@jm_rodrigues/how-to-create-custom-base64uploadadapter-ckeditor-e91332b89b0d?source=rss-3a1bfa949d97------2</link>
            <guid isPermaLink="false">https://medium.com/p/e91332b89b0d</guid>
            <category><![CDATA[rich-text-editor]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[upload]]></category>
            <category><![CDATA[ckeditor]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[J. M. Rodrigues]]></dc:creator>
            <pubDate>Fri, 14 Apr 2023 12:27:26 GMT</pubDate>
            <atom:updated>2023-04-14T12:27:51.672Z</atom:updated>
            <content:encoded><![CDATA[<p>CKEditor is one of the greatest rich text editors. I personally have used a lot in most of my projects. However some things aren&#39;t as intuitive as it should be in my opinion. When you want to add image upload you have to add a Plugin, so you can either upload the image to your s3 bucket or transform it in base 64. But it isn&#39;t so trivial, so let&#39;s tackle how to do it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KS9huWlfUv_ePWM63zTsLA.jpeg" /><figcaption>CKEditor, the rich text editor for every use case</figcaption></figure><p>I&#39;m gonna cover how can you create the simplest base64 UploadAdapter to CKEditor. If you are using the builded version of the CKEditor as your default CKEditor you might encounter the following error when trying to install the Base64UploadAdapter of <a href="https://medium.com/u/77cdb572240d">CKEditor Ecosystem</a> like that:</p><pre>import ClassicEditor from &quot;@ckeditor/ckeditor5-build-classic&quot;;<br>import Base64UploadAdapter from &quot;@ckeditor/ckeditor5-upload/src/adapters/base64uploadadapter&quot;;</pre><p>Error message:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QProqXDnVRqC2jiP7Yz-yQ.png" /><figcaption>CKEditor error of duplicated modules</figcaption></figure><p>If you troubleshoot this error and go to the ckeditor referencing page of the error message you will find:</p><blockquote>This error is thrown when due to a mistake in how CKEditor 5 was installed or initialized, some of its modules were duplicated (evaluated and executed twice). Module duplication leads to inevitable runtime errors.</blockquote><p>The &quot;answer&quot; they give to how to solve this error is basically, instead of using the build version of CKEditor use the normal version. But if you&#39;re using ckeditor in Vue.js for instance you might not be able to use something different than the builded version, on the instructions of how to use in Vue.js they use the builded version. Referece: <a href="https://ckeditor.com/docs/ckeditor5/latest/installation/frameworks/vuejs-v2.html">How To Use CKEditor in Vue.js</a></p><p>Some other possible solution to this problem is to generate your own build of extra packages or editors, other than the builded CKEditor, as they also suggest. But this leads to over addition of files to your project, hence not a good option. Reference: <a href="https://ckeditor.com/docs/ckeditor5/latest/installation/advanced/using-two-editors.html">How To Use Two CKEditors</a></p><p>Therefore I&#39;m gonna cover a way that you can easily insert a base64 uploader without <strong>too much trouble</strong>.</p><ol><li>Create <strong>upload_adapter.js</strong> file and paste the following code:</li></ol><pre>export default class MyUploadAdapter {<br>  constructor(loader) {<br>    this.loader = loader;<br>  }<br><br>  upload() {<br>    return this.loader.file.then(<br>      (file) =&gt;<br>        new Promise((resolve, reject) =&gt; {<br>          const toBase64 = (file) =&gt;<br>            new Promise((resolve, reject) =&gt; {<br>              const reader = new FileReader();<br>              reader.readAsDataURL(file);<br>              reader.onload = () =&gt; resolve(reader.result);<br>              reader.onerror = (error) =&gt; reject(error);<br>            });<br>          const base64_image = toBase64(file).then((data) =&gt; {<br>            return resolve({<br>              default: data<br>            });<br>          });<br>          this.loader.uploaded = true;<br>          return base64_image;<br>        })<br>    );<br>  }<br>}</pre><p>2. Import it inside your component or page application: Now just add it to your component or page and add it as a configPlugin</p><pre>import UploadAdapter from &quot;./upload_adapter&quot;;<br>import ClassicEditor from &quot;@ckeditor/ckeditor5-build-classic&quot;;<br><br>data() {<br>  return {<br>    editor: ClassicEditor,<br>    editor_data: &quot;&quot;<br>  }<br>}<br><br>&lt;ckeditor<br>  :editor=&quot;editor&quot;<br>  v-model=&quot;editor_data&quot;<br>  config={{extraPlugins:[UploadAdapter]}} //use<br>&gt;&lt;/ckeditor&gt;</pre><p>You might want to adapt it if you&#39;re not using Vue.js and instead you&#39;re using plain Vanilla JS. But that&#39;s pretty much it. If you have any doubt or suggestion about improvements on this tutorial just let me know 😃.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e91332b89b0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Marketplace (PHP Only Project)]]></title>
            <link>https://medium.com/@jm_rodrigues/marketplace-php-only-project-aea415664f56?source=rss-3a1bfa949d97------2</link>
            <guid isPermaLink="false">https://medium.com/p/aea415664f56</guid>
            <dc:creator><![CDATA[J. M. Rodrigues]]></dc:creator>
            <pubDate>Tue, 04 Apr 2023 11:41:51 GMT</pubDate>
            <atom:updated>2023-04-04T11:41:51.764Z</atom:updated>
            <content:encoded><![CDATA[<p>If you want to gain insights related to do a pure <strong>PHP</strong> project I think this article can be come in handy. Every time I’ve developed stuff using modern <strong>PHP</strong> frameworks like <strong>Laravel</strong> I always wondered the amount of work it would take to do something trivial using <strong>PHP</strong> only. During this project I could realize the amount of work. Not as much as I thought but still more than expected.</p><p>Briefly the goal of this project wasjust to have a simple marketplace where the user has a <strong>cart</strong> and could add products, each <strong>product</strong> has a <strong>product_type</strong> which is used to calculate the taxes values incident over the product. You can add and subtract products from the cart and change their quantities. That’s pretty much the system requirements, but what about doing it <strong>only</strong> using <strong>PHP</strong>? One thing we know for sure. We cannot scape so easily from the MVC pattern, so here is the project strucutre I&#39;ve picked:</p><figure><img alt="Project structure" src="https://cdn-images-1.medium.com/max/263/1*3clO8sZL_D-jBl26G9nd3w.png" /><figcaption>MVC All Day Long</figcaption></figure><p>As you have also noticed I&#39;m using <a href="https://www.php-fig.org/psr/psr-4/#:~:text=This%20PSR%20describes%20a%20specification,autoloaded%20according%20to%20the%20specification.">PSR-4 compliant</a>, meaning that the namespace of the classes is structured according to <a href="https://www.php-fig.org/psr/psr-4/#:~:text=This%20PSR%20describes%20a%20specification,autoloaded%20according%20to%20the%20specification.">PSR-4 standards</a>. This allows us to easily autoload our classes using Composer’s autoloader.</p><p>Next thing was to implement some <a href="https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping">ORM</a> to interact with my database. Imagine always have to stablish database connections and write all that messy code? No way José. The abstraction and reusability <a href="https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping">ORMs</a> gives to us are just amazing. Here is the example of how to do the simplest ORM in PHP ever:</p><pre>&lt;?php<br><br>class Database<br>{<br>    private $pdo;<br><br>    public function __construct()<br>    {<br>        $host = &#39;localhost&#39;;<br>        $port = &#39;5432&#39;; // default port for PostgreSQL<br>        $dbname = &#39;marketplace&#39;;<br>        $user = &#39;postgres&#39;;<br>        $password = &#39;postgres&#39;;<br>        $dsn = &quot;pgsql:host=$host;port=$port;dbname=$dbname;user=$user;password=$password&quot;;<br><br>        $this-&gt;pdo = new PDO($dsn);<br>        $this-&gt;pdo-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);<br>        $this-&gt;pdo-&gt;setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);<br>    }<br><br>    private function query($sql, $params = [])<br>    {<br>        $stmt = $this-&gt;pdo-&gt;prepare($sql);<br>        $stmt-&gt;execute($params);<br>        return $stmt;<br>    }<br><br>    public function select($sql, $params = [])<br>    {<br>        $stmt = $this-&gt;query($sql, $params);<br>        return $stmt-&gt;fetchAll();<br>    }<br><br>    public function insert($sql, $params = [])<br>    {<br>        $stmt = $this-&gt;query($sql, $params);<br>        return $this-&gt;pdo-&gt;lastInsertId();<br>    }<br><br>    public function update($sql, $params = [])<br>    {<br>        $stmt = $this-&gt;query($sql, $params);<br>        return $stmt-&gt;rowCount();<br>    }<br><br>    public function delete($sql, $params = [])<br>    {<br>        $stmt = $this-&gt;query($sql, $params);<br>        return $stmt-&gt;rowCount();<br>    }<br>}</pre><p>If you want to see the detailed commit: <a href="https://github.com/matheus-rodrigues00/php_marketplace/commit/e24d40a142424e13aff99506483af3d2755bd3f2#diff-cd6f3b5557b150d0db4b52a3a0a19cc3327976a0627781619631d0004f76665f">commit</a></p><p>Now let&#39;s get to what is interesting. The CRUD operations. How are they done? Well, if you&#39;re familiar with the MVC it&#39;s pretty much the same thing, here&#39;s a CRUD example of the project.</p><p>ProductTypes CRUD</p><pre>// Routes: /index.php<br>productTypesController = new ProductTypesController($db);<br><br>$router-&gt;get(&#39;/product_types&#39;, function () use ($productTypesController) {<br>    $productTypes = $productTypesController-&gt;index();<br>    header(&#39;Content-Type: application/json&#39;);<br>    echo json_encode($productTypes);<br>});<br><br>$router-&gt;get(&#39;/product_types/(\d+)&#39;, function ($id) use ($productTypesController) {<br>    $productType = $productTypesController-&gt;show($id);<br>    echo json_encode($productType);<br>});<br><br>$router-&gt;post(&#39;/product_types&#39;, function () use ($productTypesController) {<br>    $request_body = file_get_contents(&#39;php://input&#39;);<br>    $request_data = json_decode($request_body, true);<br><br>    $name = $request_data[&#39;name&#39;];<br>    $tax_rate = $request_data[&#39;tax_rate&#39;];<br><br>    $productType = $productTypesController-&gt;create($name, $tax_rate);<br>    header(&#39;Content-Type: application/json&#39;);<br>    echo json_encode($productType);<br>});<br><br>$router-&gt;put(&#39;/product_types/(\d+)&#39;, function ($id) use ($productTypesController) {<br>    $request_body = json_decode(file_get_contents(&#39;php://input&#39;), true);<br>    $name = $request_body[&#39;name&#39;] ?? null;<br>    $tax_rate = $request_body[&#39;tax_rate&#39;] ?? null;<br>    $productType = $productTypesController-&gt;update($id, $name, $tax_rate);<br>    header(&#39;Content-Type: application/json&#39;);<br>    echo json_encode($productType);<br>});<br><br>$router-&gt;delete(&#39;/product_types/(\d+)&#39;, function ($id) use ($productTypesController) {<br>    $productTypesController-&gt;destroy($id);<br>    header(&#39;Content-Type: application/json&#39;);<br>    echo json_encode([&#39;message&#39; =&gt; &#39;Product type deleted&#39;]);<br>});</pre><pre>// Model ../models/ProductType.php<br>class ProductType {<br>    private $id;<br>    private $name;<br>    private $tax_rate;<br><br>    public function __construct($id, $name, $tax_rate) {<br>        $this-&gt;id = $id;<br>        $this-&gt;name = $name;<br>        $this-&gt;tax_rate = $tax_rate;<br><br>        return $this;<br>    }<br><br>    public function getId() {<br>        return $this-&gt;id;<br>    }<br><br>    public function getName() {<br>        return $this-&gt;name;<br>    }<br><br>    public function getTaxRate() {<br>        return $this-&gt;tax_rate;<br>    }<br><br>    public function getAll() {<br>        return [<br>            &#39;id&#39; =&gt; $this-&gt;id,<br>            &#39;name&#39; =&gt; $this-&gt;name,<br>            &#39;tax_rate&#39; =&gt; $this-&gt;tax_rate<br>        ];<br>    }<br>}</pre><pre>// Controller: ../controllers/ProductTypesController<br>class ProductTypesController {<br>    private $db;<br><br>    public function __construct($db) {<br>        $this-&gt;db = $db;<br>    }<br><br>    public function index() {<br>        $sql = &quot;SELECT * FROM product_types&quot;;<br>        $result = $this-&gt;db-&gt;select($sql);<br>        $product_types = [];<br><br>        foreach ($result as $data) {<br>            $product_type = new ProductType($data[&#39;id&#39;], $data[&#39;name&#39;], $data[&#39;tax_rate&#39;]);<br>            $product_types[] = $product_type-&gt;getAll();<br>        }<br><br>        return $product_types;<br>    }<br><br>    public function create($name, $tax_rate) {<br>        $sql = &quot;INSERT INTO product_types (name, tax_rate) VALUES (?, ?)&quot;;<br>        $params = [$name, $tax_rate];<br>        $product_type_id = $this-&gt;db-&gt;insert($sql, $params);<br>        return $this-&gt;show($product_type_id);<br>    }<br><br>    public function show($id) {<br>        $sql = &quot;SELECT * FROM product_types WHERE id = ?&quot;;<br>        $params = [$id];<br>        $result = $this-&gt;db-&gt;select($sql, $params);<br>        if (count($result) == 0) {<br>            return null;<br>        }<br><br>        $data = $result[0];<br>        $product_type = new ProductType($data[&#39;id&#39;], $data[&#39;name&#39;], $data[&#39;tax_rate&#39;]);<br>        return $product_type-&gt;getAll();<br>    }<br><br>    public function update($id, $name, $price) {<br>        $sql = &quot;UPDATE product_types SET name = ?, tax_rate = ? WHERE id = ?&quot;;<br>        $params = [$name, $price, $id];<br>        $row_count = $this-&gt;db-&gt;update($sql, $params);<br><br>        if ($row_count == 0) {<br>            return null;<br>        }<br><br>        return $this-&gt;show($id);<br>    }<br><br>    public function destroy($id) {<br>        $sql = &quot;DELETE FROM product_types WHERE id = ?&quot;;<br>        $params = [$id];<br>        $row_count = $this-&gt;db-&gt;delete($sql, $params);<br><br>        if ($row_count == 0) {<br>            return null;<br>        }<br><br>        return true;<br>    }<br>}</pre><p>You may be wondering. Why use Models in this project without the advantage of Laravel ORM for example. Pretty much code organization, even tought we&#39;re not going to have huge advantages with it.</p><p>Now let&#39;s talk about tests. Specially in PHP. The lib I&#39;ve picked was phpunit. I&#39;m not an expert in tests in PHP but this one seems to be really fine and gives the reliability that tests are supposed to.</p><p>Taling about the test of <strong>Product</strong> and <strong>ProductType </strong>I&#39;ve only created some test cases to make sure that the CRUD (Create, Read, Update, and Delete) operations were functioning correctly and tested the model&#39;s relationships with the <strong>Product</strong> model, as each product belongs to a <strong>ProductType</strong>. Let&#39;s see some example of the tests.</p><pre>&lt;?php<br><br>require_once __DIR__ . &#39;/../src/config.php&#39;;<br>require_once __DIR__ . &#39;/../vendor/autoload.php&#39;;<br>require_once __DIR__ . &#39;/../src/database.php&#39;;<br><br>use PHPUnit\Framework\TestCase;<br><br>class ProductTypeTest extends TestCase<br>{<br>    private $db;<br>    private $controller;<br><br>    protected function setUp(): void<br>    {<br>        $this-&gt;db = new Database();<br>        $this-&gt;controller = new ProductTypesController($this-&gt;db);<br>    }<br><br>    public function testIndex()<br>    {<br>        // Define the test data<br>        $testData = [        [&#39;id&#39; =&gt; 1, &#39;name&#39; =&gt; &#39;Type A&#39;, &#39;tax_rate&#39; =&gt; 10],<br>            [&#39;id&#39; =&gt; 2, &#39;name&#39; =&gt; &#39;Type B&#39;, &#39;tax_rate&#39; =&gt; 20],<br>            [&#39;id&#39; =&gt; 3, &#39;name&#39; =&gt; &#39;Type C&#39;, &#39;tax_rate&#39; =&gt; 30],<br>        ];<br><br>        // Mock the database object and set up the expected method call and result<br>        $db = $this-&gt;getMockBuilder(Database::class)<br>                -&gt;disableOriginalConstructor()<br>                -&gt;getMock();<br>        $db-&gt;expects($this-&gt;once())<br>        -&gt;method(&#39;select&#39;)<br>        -&gt;with(&#39;SELECT * FROM product_types&#39;)<br>        -&gt;willReturn($testData);<br><br>        // Create the controller instance with the mocked database<br>        $controller = new ProductTypesController($db);<br><br>        // Call the method being tested<br>        $result = $controller-&gt;index();<br><br>        // Assert that the method returns the expected result<br>        $this-&gt;assertEquals($testData, $result);<br>    }<br><br><br>    public function testIndexReturnsArrayOfProductTypes()<br>    {<br>        $result = $this-&gt;controller-&gt;index();<br>        $this-&gt;assertIsArray($result);<br><br>        foreach ($result as $product_type) {<br>            $this-&gt;assertArrayHasKey(&#39;id&#39;, $product_type);<br>            $this-&gt;assertArrayHasKey(&#39;name&#39;, $product_type);<br>            $this-&gt;assertArrayHasKey(&#39;tax_rate&#39;, $product_type);<br>        }<br>    }<br><br>    public function testCreateAddsProductTypeToDatabase()<br>    {<br>        $name = &#39;Test Product Type&#39;;<br>        $tax_rate = 0.10;<br>        $result = $this-&gt;controller-&gt;create($name, $tax_rate);<br><br>        $this-&gt;assertIsArray($result);<br>        $this-&gt;assertArrayHasKey(&#39;id&#39;, $result);<br>        $this-&gt;assertArrayHasKey(&#39;name&#39;, $result);<br>        $this-&gt;assertArrayHasKey(&#39;tax_rate&#39;, $result);<br>        $this-&gt;assertEquals($name, $result[&#39;name&#39;]);<br>        $this-&gt;assertEquals($tax_rate, $result[&#39;tax_rate&#39;]);<br><br>        $sql = &quot;SELECT * FROM product_types WHERE id = ?&quot;;<br>        $params = [$result[&#39;id&#39;]];<br>        $rows = $this-&gt;db-&gt;select($sql, $params);<br>        $this-&gt;assertEquals(1, count($rows));<br>        $this-&gt;assertEquals($name, $rows[0][&#39;name&#39;]);<br>        $this-&gt;assertEquals($tax_rate, $rows[0][&#39;tax_rate&#39;]);<br>    }<br><br>    public function testShowReturnsNullWhenProductTypeNotFound()<br>    {<br>        $result = $this-&gt;controller-&gt;show(999);<br>        $this-&gt;assertNull($result);<br>    }<br><br>    public function testShowReturnsProductTypeIfExists()<br>    {<br>        $name = &#39;Test Product Type&#39;;<br>        $tax_rate = 0.10;<br>        $created = $this-&gt;controller-&gt;create($name, $tax_rate);<br>        $result = $this-&gt;controller-&gt;show($created[&#39;id&#39;]);<br><br>        $this-&gt;assertIsArray($result);<br>        $this-&gt;assertArrayHasKey(&#39;id&#39;, $result);<br>        $this-&gt;assertArrayHasKey(&#39;name&#39;, $result);<br>        $this-&gt;assertArrayHasKey(&#39;tax_rate&#39;, $result);<br>        $this-&gt;assertEquals($created, $result);<br>    }<br><br>    public function testUpdateReturnsNullWhenNoUpdatesProvided()<br>    {<br>        $result = $this-&gt;controller-&gt;update(1);<br>        $this-&gt;assertNull($result);<br>    }<br><br>    public function testUpdateReturnsNullWhenProductTypeNotFound()<br>    {<br>        $result = $this-&gt;controller-&gt;update(999, &#39;Test Product Type&#39;);<br>        $this-&gt;assertNull($result);<br>    }<br><br>    public function testUpdateReturnsUpdatedProductTypeIfExists()<br>    {<br>        // Create a product type<br>        $name = &#39;Test Product Type&#39;;<br>        $tax_rate = 0.10;<br>        $created = $this-&gt;controller-&gt;create($name, $tax_rate);<br><br>        // Update the product type<br>        $newName = &#39;Updated Product Type&#39;;<br>        $newTaxRate = 0.20;<br>        $updated = $this-&gt;controller-&gt;update($created[&#39;id&#39;], $newName, $newTaxRate);<br><br>        // Assert that the product type was updated correctly<br>        $this-&gt;assertIsArray($updated);<br>        $this-&gt;assertArrayHasKey(&#39;id&#39;, $updated);<br>        $this-&gt;assertArrayHasKey(&#39;name&#39;, $updated);<br>        $this-&gt;assertArrayHasKey(&#39;tax_rate&#39;, $updated);<br>        $this-&gt;assertEquals($created[&#39;id&#39;], $updated[&#39;id&#39;]);<br>        $this-&gt;assertEquals($newName, $updated[&#39;name&#39;]);<br>        $this-&gt;assertEquals($newTaxRate, $updated[&#39;tax_rate&#39;]);<br><br>        // Check that the update was persisted to the database<br>        $sql = &quot;SELECT * FROM product_types WHERE id = ?&quot;;<br>        $params = [$updated[&#39;id&#39;]];<br>        $rows = $this-&gt;db-&gt;select($sql, $params);<br>        $this-&gt;assertEquals(1, count($rows));<br>        $this-&gt;assertEquals($newName, $rows[0][&#39;name&#39;]);<br>        $this-&gt;assertEquals($newTaxRate, $rows[0][&#39;tax_rate&#39;]);<br>    }<br><br>    public function testDestroyRemovesProductTypeIfExists()<br>    {<br>        // Create a product type<br>        $name = &#39;Test Product Type&#39;;<br>        $tax_rate = 0.10;<br>        $created = $this-&gt;controller-&gt;create($name, $tax_rate);<br><br>        // Delete the product type<br>        $this-&gt;controller-&gt;destroy($created[&#39;id&#39;]);<br><br>        // Assert that the product type was deleted<br>        $sql = &quot;SELECT * FROM product_types WHERE id = ?&quot;;<br>        $params = [$created[&#39;id&#39;]];<br>        $rows = $this-&gt;db-&gt;select($sql, $params);<br>        $this-&gt;assertEquals(0, count($rows));<br>    }<br><br>}</pre><p>Also something fundamental that I did later was to isolate the testing database. I like to use the same type of database I use in production (<a href="https://www.postgresql.org/"><strong>Postgres</strong></a>) when doing the test database, some people blindly pick <a href="https://sqlite.org/index.html"><strong>SQLite</strong></a> for testing databases but I think the more you replicate the production behavior the best.</p><p>Write only PHP is no nightmare at all but I&#39;m really thankful for frameworks like Laravel exists nowdays. When I had to implement the users model it was painful to deal with everything related to session, password encryption, tokens validation and invalidation. Things that Laravel or Lumen gives to you out of the box. Thanks for you time reading and I hope it gives you value somehow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aea415664f56" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>