<?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 Enrique Rubio on Medium]]></title>
        <description><![CDATA[Stories by Enrique Rubio on Medium]]></description>
        <link>https://medium.com/@wooltar?source=rss-795cb62c3648------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CtOPBKJxFwqmQvrCPsW_sQ.jpeg</url>
            <title>Stories by Enrique Rubio on Medium</title>
            <link>https://medium.com/@wooltar?source=rss-795cb62c3648------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 17:39:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wooltar/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[How create a multidocker Redis inside an AWS EC2 (cheaper than ElasticCache)]]></title>
            <link>https://medium.com/@wooltar/how-create-a-multidocker-redis-inside-an-aws-ec2-cheaper-than-elasticcache-c329ef628d81?source=rss-795cb62c3648------2</link>
            <guid isPermaLink="false">https://medium.com/p/c329ef628d81</guid>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[elasticca]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Enrique Rubio]]></dc:creator>
            <pubDate>Sun, 24 May 2020 09:33:45 GMT</pubDate>
            <atom:updated>2020-05-25T07:17:07.154Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*IGNtIaTAVStmelFKFquIKw.png" /></figure><p>AWS ElastiCache is cool, but is expensive. Here I will explain how you can create a ec2 machine with a dockerize Redis inside. Let’s do it.</p><p>In this case, we put ec2 machine into a private subnet, because we want our servers to use it. These servers are in private subnet too.</p><p>To be able to connect to these servers you need a bastion that is on the public subnet of your vlc</p><h3>Creating a bastion</h3><p>To create a bastion you just have to launch this template in your vlc.</p><p><a href="https://aws-quickstart.s3.amazonaws.com/quickstart-linux-bastion/templates/linux-bastion.template">https://aws-quickstart.s3.amazonaws.com/quickstart-linux-bastion/templates/linux-bastion.template</a></p><p>Creating docker Redis</p><p>We create some redis machine, one for each environment we have. You can create the redis environment you need, the unique rules is that each redis service have a different port</p><p>docker-compose-yml:</p><pre>version: &quot;3&quot;<br>services:<br>  redis-dev:<br>    image: bitnami/redis:latest<br>    restart: always<br>    sysctls:<br>      net.core.somaxconn: 4096<br>    ulimits:<br>      nproc: 65535<br>      nofile:<br>        soft: 20000<br>        hard: 40000<br>    volumes:<br>      - ./redis-data:/bitnami/redis/data<br>      - ./redis.conf:/usr/local/etc/redis/redis.conf<br>    ports:<br>      - <strong>6311</strong>:6379<br>    environment:<br>      - ALLOW_EMPTY_PASSWORD=yes</pre><pre>redis-sta:<br>    image: bitnami/redis:latest<br>    restart: always<br>    sysctls:<br>      net.core.somaxconn: 4096<br>    ulimits:<br>      nproc: 65535<br>      nofile:<br>        soft: 20000<br>        hard: 40000<br>    volumes:<br>      - ./redis-data:/bitnami/redis/data<br>      - ./redis.conf:/usr/local/etc/redis/redis.conf<br>    ports:<br>      - <strong>6312</strong>:6379<br>    environment:<br>      - ALLOW_EMPTY_PASSWORD=yes</pre><pre>redis-pro:<br>    image: bitnami/redis:latest<br>    restart: always<br>    sysctls:<br>      net.core.somaxconn: 4096<br>    ulimits:<br>      nproc: 65535<br>      nofile:<br>        soft: 20000<br>        hard: 40000<br>    volumes:<br>      - ./redis-data:/bitnami/redis/data<br>      - ./redis.conf:/usr/local/etc/redis/redis.conf<br>    ports:<br>      - <strong>6313</strong>:6379<br>    environment:<br>      - ALLOW_EMPTY_PASSWORD=yes</pre><p>How you can see, we need crete redis-data directory and redis.conf file. You can create redis.conf with this content</p><p><a href="http://download.redis.io/redis-stable/redis.conf">“http://download.redis.io/redis-stable/redis.conf</a></p><p>In order to activate backup you have to search “appendonly” and change to “yes”</p><p>Now, you have to change the owner:group so that the container can access these.</p><pre>chown -R 1001:1001 redis-data<br>chown 1001:1001 redis.conf</pre><p>Its time to check, execute</p><pre>docker-compose up</pre><h3>Resolving Warning</h3><p>WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. master f72e77f</p><pre>echo never &gt; /sys/kernel/mm/transparent_hugepage/enabled<br>echo never &gt; /sys/kernel/mm/transparent_hugepage/defrag</pre><p>To do this persistent put these two lines in /etc/rc.local</p><p>Restart docker to see everything is ok</p><pre>docker-compose down &amp;&amp; docker-compose up</pre><p>note: this solution is for linux machine</p><h3>Creating EC2 machine</h3><p>Now it’s time to create ec2. Go to AWS console.</p><p>Select EC2 service and launch instance</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*wFogZWcefdxeW1POCmdQBw.png" /><figcaption>click on launch instance</figcaption></figure><p>We have to configure a couple options.</p><p>First at all, we select this ami.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w2_kTvnUTL0dSlx1Ebi_ZA.png" /><figcaption>Step 1: Choose a AIM Type</figcaption></figure><p>Here you have to take into account how many environments you are going to have and the use you are going to give to each environment. For 2 or 3 environments I think a <strong>t3.small</strong> is enough. If you have more, select <strong>t3.medium</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EupviBvK6XhdzRzX-inz-A.png" /><figcaption>Step 2: Choose an Instance Type</figcaption></figure><p>Click “Configure Instance Details”</p><p>Now you have to choose your vpc and assign the ec2 to private subnet. This is important because we protect the machine from access from the Internet.</p><p>Enable termination protection so that the machine cannot be accidentally terminated</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*6m7yQNOICO8QptZfadXr0w.png" /></figure><p>Click next, and click next again, storage is not needed change it</p><p>You can add tag to identify it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Q1589ea_de6MhVfWR8H3A.png" /><figcaption>Step 5: Add Tags</figcaption></figure><p>click on next to configure security group.</p><p>Create a new security group, allowing access to ssh and redis services.</p><p>Open 22, 6311, 6312, 6313 TCP port</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*izTU9zKyTB92BabXq6zE7Q.png" /><figcaption>Step 6: Configure Security Group</figcaption></figure><p>Click on launch and select your private key (if you haven’t, create one)</p><h3>Accessing redis ec2</h3><p>In order to access this ec2, you need to configure a ssh tunnel.</p><p>Add this to your .ssh/config</p><pre>Host bastion<br>  Hostname      YOUR_BASTION_IP<br>  IdentityFile  ~/.ssh/your_bastion_key.pem<br>  IdentitiesOnly yes<br>  Port 22<br>  User ec2-user</pre><pre>Host redis<br> Hostname     YOUR_REDIS_IP<br> IdentityFile  ~/.ssh/your_redis_key.pem<br> Port 22<br> ProxyJump bastion<br> User ec2-user</pre><p>Now, just execute</p><pre>ssh redis</pre><p>You are in!!!</p><h3>Creating app directory in ec2</h3><pre>sudo mkdir /opt/app &amp;&amp; sudo chown ec2_user:ec2_user /opt/app</pre><h3>Configuring Redis in EC2</h3><p>First, we have to copy all files to redis ec2.</p><pre>scp -r /path/to/project/ redis:/opt/app</pre><p>Make sure redis.conf and redis-data has the owner and group they need(1001)</p><pre>ssh redis<br>ls -la /opt/app</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*mxql9m93wSfVsas56w3YAA.png" /></figure><h3>Resolving Warnings in EC2</h3><p>Apply the solution to the warnings we already saw in the point “Resolving Warning”</p><h3>Installing Docker CE</h3><pre>yum install -y docker</pre><p>Make docker auto-start</p><pre>sudo chkconfig docker on</pre><p>Reboot to verify it all loads fine on its own.</p><pre>sudo reboot</pre><h3>Installing Docker-compose</h3><pre>sudo curl -L https://github.com/docker/compose/releases/download/1.22.0/docker-compose-$(uname -s)-$(uname -m) -o /usr/local/bin/docker-compose</pre><p>Fix permissions after download:</p><pre>sudo chmod +x /usr/local/bin/docker-compose</pre><p>Verify success:</p><pre>docker-compose version</pre><h3>Running Redis</h3><pre>cd path/to/project<br>docker-compose up</pre><p>That is!!!</p><p>I hope this tutorial has helped you and you can save some money, which is never wrong</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c329ef628d81" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Codecommit push from Bitbucket pipeline]]></title>
            <link>https://medium.com/@wooltar/aws-codecommit-push-from-bitbucket-pipeline-2f5e08fe3629?source=rss-795cb62c3648------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f5e08fe3629</guid>
            <category><![CDATA[ci]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[push]]></category>
            <category><![CDATA[aws-codecommit]]></category>
            <category><![CDATA[bitbucket]]></category>
            <dc:creator><![CDATA[Enrique Rubio]]></dc:creator>
            <pubDate>Sat, 23 May 2020 10:15:05 GMT</pubDate>
            <atom:updated>2020-05-23T16:06:49.680Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/310/0*Ge9UM9OZnvtapriL" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/0*p7Btc5X0oOv-MALH.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*vuhWrVs_ArANrnX_" /></figure><p>I needed to do this because I spent a whole day setting it up, due to lack of documentation. Other tutorials I have visited echo this problem, but they seem to be outdated. As of today, this works 100%. Let’s go!</p><h3>Configure Bitbucket Pipelines</h3><p>In order to use Bitbucket Pipelines, it needs to be enabled for the repository first. Under your repository settings, choose Pipelines and enable pipelines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/0*lM5uiutEsies8UXl.png" /></figure><h3>Ssh Keys</h3><p>The first at all, you need to create a ssh keys in pipelines section</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*4mQdzTDLfBccp0fXv1R4kA.png" /><figcaption>ssh keys section</figcaption></figure><h4><strong>Important!!! Don’t upload a key pair, create one</strong></h4><p>Bitbucket keeps the ssh private key in<strong> /opt/atlassian/pipelines/agent/ssh/id_rsa</strong></p><p>keep this path for later…</p><h3>AWS configuration</h3><p>We need create a AWS user and give him codecommit git push permissions. Let’s do it:</p><ol><li>Go to IAM service, select policies.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*0TXtK_TWWswm7PdzMDiAnQ.png" /></figure><p>2. Click on Create Policy and paste this in JSON section</p><pre>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [<br>    {<br>      &quot;Sid&quot;: &quot;VisualEditor0&quot;,<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Action&quot;: [<br>        &quot;codecommit:GitPush&quot;<br>      ],<br>      &quot;Resource&quot;: &quot;*&quot;<br>    }<br>  ]<br>}</pre><p>saved it as “aws-codecommit-gitpush”.</p><p>3. Create a new IAM CodeCommit-Contributor group.</p><p>4 . Assign “aws-codecommit-gitpush” policy to CodeCommit-Contributor group.</p><p>5. Create a new IAM user BitbucketUser and aggregate toCodeCommit-Contributor group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*UP7gYhBCBTC6vdCZWLydZw.png" /></figure><p>6. Upload ssh public key in aws user credential section</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RBpx9pIYMHmnYQ6ghDlXLA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*UKQJjUw9oSpEaVQ-ggqo6A.png" /></figure><p>Go to Bitbucket ssh key section and copy your public key.</p><p>Comeback to aws console and click on “Upload SSH public key”. Paste, accept.</p><p>Now, copy <strong>SSH key ID.</strong></p><h3>Create config file</h3><pre>nano ~/.ssh/configBitbucket.</pre><p>Note that you have to paste the <strong>ssh key id</strong> generate in AWS IAM console, here</p><pre>Host git-codecommit.*.amazonaws.com<br> Hostname git-codecommit.eu-central-1.amazonaws.com<br> User <strong>YOUR_USER_SSH_KEY</strong><br> IdentityFile /opt/atlassian/pipelines/agent/ssh/id_rsa</pre><p>encode to base64, execute:</p><pre><em>base64 ~/.ssh/configBitbucket</em></pre><h3>Environment Variables</h3><p>Let’s configure bitbucket environment variables. Under your repository settings, choose Environment Variables under Pipelines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/195/1*s1tmVqQUmy144ohrtJBBmw.png" /></figure><p>We’re going to create 4 environment variables as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wNviXsvsIb7FC0vELSPQRQ.png" /><figcaption>bitbucket repository variables</figcaption></figure><p>Here’s the high-level of what these are, and we’ll cover them in more detail below:</p><ol><li>CodeCommitConfig: The base64 encoded version of the SSH config we added to our ~/.ssh/configBitbucket earlier that specifies the Host, User and IdentityFile.</li><li>CodeCommitHost: The host and region of your CodeCommit instance</li><li>CodeCommitRepo: The host, region and repository path of your repository.</li><li>CodeCommitUser: The SSH key ID associated with the public key on your AWS IAM user.</li></ol><p>The CodeCommitConfig variable is base64 encoded to make sure that all characters are encoded in a way that we can refer to them later on. Since each variable is only a single line of text, multiline variables won’t persist correctly if you try to paste them in without encoding them first.</p><p>Now, let’s create that bitbucket-pipelines.yml file, either add it using your favourite editor, or click “Configure bitbucket-pipelines.yml” and edit it directly on bitbucket.org. At the moment just write a command in order to know the private key content</p><pre>pipelines:<br>  default:<br>    - step:<br>        script:<br>          - echo $CodeCommitConfig &gt; ~/.ssh/config.tmp<br>          - base64 -d  ~/.ssh/config.tmp &gt; ~/.ssh/config<br>          - cat ~/.ssh/config<br>          - set +e<br>          - ssh -o StrictHostKeyChecking=no $CodeCommitHost<br>          - set -e<br>          - git remote add codecommit ssh://$CodeCommitRepo<br>          - git push codecommit $BITBUCKET_BRANCH</pre><p>Now, whenever you push to bitbucket, it will also push to codecommit</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/0*zLpwIgTOiSnP1lhf.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f5e08fe3629" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Consensos en blockchain]]></title>
            <link>https://medium.com/@wooltar/consensos-en-blockchain-2ab9ad7b3737?source=rss-795cb62c3648------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ab9ad7b3737</guid>
            <category><![CDATA[blockchain-development]]></category>
            <category><![CDATA[consenso]]></category>
            <category><![CDATA[consensus]]></category>
            <category><![CDATA[blockchain-technology]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Enrique Rubio]]></dc:creator>
            <pubDate>Fri, 17 Aug 2018 13:50:09 GMT</pubDate>
            <atom:updated>2018-08-18T08:59:55.621Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*qZSwctLqSLVGTh8DIn6dzg.jpeg" /></figure><p>Para poder añadir bloques a una blockchain los nodos deben regirse por un consenso, en definitiva, deben hablar el mismo idioma para poder ponerse de acuerdo y que todos sepan cómo se debe trabajar en dicho blockchain.</p><p>Existen varios consensos, cada uno con sus pros y sus contras. En este articulo voy a intentar explicar el funcionamiento de cada uno de ellos.</p><h4>Proof of wook (PoS)</h4><p>El consenso PoW, usado en bitcoin, es eficaz para resolver el clásico problema de generales bizantinos y prevenir los ataques de Sybil al tiempo que proporciona seguridad a la red, pero está destinado a desaparecer debido a los altos recursos necesarios para minar a medida que avanza la dificultad del hash, actualmente ya solo sale rentable minar en paises donde el las tarifa eléctricas son bajas. Aqui los nodos tratan de resolver un hash por el método de fuerza bruta. El primer nodo que consiga resolverlo, se lleva la recompensa.</p><h4>Proof of Stack (PoS)</h4><p>Una alternativa es el consenso PoS (prueba de estaca) donde cada nodo (nodo validador) hace una apuesta (estaca) con las monedas que posee. Lo malo de este consenso es que los que mas monedas tienen, mas pueden apostar, por lo que tendrán mayor probabilidad de ganar el derecho a generar el bloque. El PoS necesita menos energía, pero en su contra esta el problema de “nada en juego”. Esta teoría establece básicamente que si hubo un fracaso de consenso, los falsificadores no tienen nada que perder si votan por múltiples historias de cadena de bloques, lo que significa que el consenso nunca se resolvería.<br>Ethereum , el segundo blockchain público más popular después de Bitcoin, planea pasar del mecanismo de consenso PoW a PoS.</p><h4>Proof of Deposit (PoD)</h4><p>Es el mecanismo de consenso en Ethereum, que es una versión mejorada de la idea original de prueba de estaca. Aquí, cada nodo validador tiene que pagar un depósito de seguridad para obtener el derecho de crear nuevos bloques. Si un nodo de validación produce un bloque no válido, se penaliza. Su depósito de seguridad puede perderse y el derecho de crear bloques reducidos.</p><h4>Delegate Proof of Stack (DPoS)</h4><p>DPoS usa un sistema de reputación y votación en tiempo real para lograr el consenso. Los miembros de la comunidad votan para seleccionar a los testigos para que estos protejan su red. Despues estos serán recompensados ​​validando las transacciones para el siguiente bloque.</p><p>DPoS aprovecha el poder de votación de aprobación de las partes interesadas para resolver los problemas de consenso de una manera justa y democrática, pero si un testigo no se comporta correctamente, la comunidad puede despedirlo. El testigo siempre debe esforzarse para obedecer todas las reglas mantener el tiempo de actividad de la red lo más alto.</p><h4>Conclusión</h4><p>Hasta aquí llegamos con los consensos, que solo es una pequeña parte de todo lo que es la blockchain. Seguiremos investigando y ampliando este artículo con los diferentes consensos que vayan surgiendo.</p><p>En UXSmobile estamos integrando blockchain en nuestro producto Canarypay que estará disponible en Septiembre. No os lo perdáis. Seguiremos informando.</p><p>Si te ha gustado, no olvides 👏🏼</p><p>Saludos</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ab9ad7b3737" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I learned Kotlin]]></title>
            <link>https://medium.com/@wooltar/how-i-learned-kotlin-e9fcc65ff78e?source=rss-795cb62c3648------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9fcc65ff78e</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin-beginners]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Enrique Rubio]]></dc:creator>
            <pubDate>Sat, 09 Dec 2017 12:22:16 GMT</pubDate>
            <atom:updated>2017-12-09T12:42:43.233Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*JsOUSnX3NMaY5Y3C3DsQNg.jpeg" /></figure><p>I am a crazy developer, that always try to learn new things. I am in love of coding and I like applying diferent methods to coding</p><h3>Why I wanted to learn Kotlin</h3><p>I started to learn kotling the same day that google support it. I think when google support something it’s worth looking at why</p><h3>Where I started</h3><p>I started reading, what was about kotlin. I saw it was java, but short way. Mmm, I told myself: ok, I know java, let’s try it. I looking for the new features and compare them with those of java. Kotlin is pretty compact. You can do the same but writing less code lines. Also I saw how visual studio code, change the old java code in kotlin code.</p><p>I have to say I am use kotlin in Android. I think, this is the best languaje to app android develop, currently.</p><p>Everythings are advantage, but the main problems that I had at the begining was how hander the diferent components. I was one by one. I did a app that connect with a API, then I looking for how I can show the info in a simply way. After that I learned how to show the info in a reciclerview. With all this I had my first app in kotlin, of course, it was a superhero app.</p><p><strong>The main key to learn is go from easy to hard</strong>. You always have to understand one thing before go to the next. I like to develop in kotlin-android because is easy, and with some lines you can have a app, install it in your phone and play with</p><blockquote><em>You do not be hurry, be pacient and enjoy the process</em></blockquote><h3>Conclusion</h3><p>I think the most important thing when you are coding, you must enjoy with, and the hours go fast. Now I looking for new features to learn and apply it.<br> Read, learn and apply, that’s my kata.</p><p><em>Originally published at </em><a href="https://www.codementor.io/enriquerubiosanchez/how-i-learned-kotlin-emfe3f8xw"><em>www.codementor.io</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9fcc65ff78e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Control de estados con Redux en Angular.]]></title>
            <link>https://medium.com/@wooltar/control-de-estados-con-redux-en-angular-fbd49dd4899c?source=rss-795cb62c3648------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbd49dd4899c</guid>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[store]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular-4]]></category>
            <dc:creator><![CDATA[Enrique Rubio]]></dc:creator>
            <pubDate>Sat, 02 Dec 2017 17:41:40 GMT</pubDate>
            <atom:updated>2017-12-02T18:38:04.292Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bCfqNvdC7EwsvdXxw96XsA.png" /></figure><p>Cuando creamos proyectos en Angular podemos controlar los estados fácilmente, por ejemplo, con un bus de observable, donde te puedes subscribir y conocer el estado de la aplicación. Desgraciadamente, esto solo sirve cuando el proyecto es pequeño, cuando el proyecto es grande y se necesitan controlar estados de muchos objetos, no podemos hacer un observable para cada objeto a controlar, eso seria un caos y muy costoso de mantener. Aquí es donde entra Redux en acción.</p><p>Redux dispone de un “store” donde podemos guardar los estados de los objetos de la aplicación, estos se guardaran en un solo objeto.</p><p>Primero vamos a comentar las partes de Redux que nos hace falta conocer y después aplicaremos lo aprendido a un proyecto sencillo de Angular mediante el uso de la librería redux.</p><h3>Redux</h3><p>Redux es un contenedor de estado predecible para aplicaciones en JavaScript. El estado completo de su aplicación se almacena en un árbol de objetos dentro de una sola <em>tienda</em> . Se caracteriza por:</p><ul><li>Un único almacén de datos inmutables.</li><li>Flujo de datos unidireccional</li><li>Basado en funciones puras y un flujo de acciones.</li></ul><p>La unica forma de cambiar un estado es a través de la emisión de una acción. Para realizar esto, necesitamos los reductores.</p><h3>Reductores</h3><p>Los reductores son funciones puras que deciden como cambian el estado en función de la acción de entrada. Cogen el estado anterior y una acción, y devuelve el siguiente estado.</p><p>Es muy importante que el reductor se mantenga puro. Nunca puedes hacer que tu reductor mute sus argumentos, realice efectos secundarios (llamadas a servicios, APIS…), ni realizar llamadas a funciones no puras.</p><p>El reductor al ser una función pura, siempre devolverá el mismo estado para los mismo argumentos de entrada, sin sorpresas.</p><h3>Store</h3><p>Es el objeto que une las acciones y los reductores. El store debe mantener el estado de la aplicación, también debe permitir conocer el estado actual, para ello dispone del método getstate(). El estado únicamente se puede actualizar mediante la llamada al método dispatch(action). Por otro lado, para registrar a los oyentes hay que usar método subcribe(listener).</p><p>import { createStore } from &#39;redux&#39;<br> import todoApp from &#39;./reducers&#39;<br><br> this.store = createStore(todoApp)</p><p>Una vez que conocemos, un poco la teoría, vamos a integrar esto en una aplicación Angular.</p><h3>Coding</h3><p>Vamos a hacer una pequeña aplicación de lista de compra, donde el store guarde los items a comprar y un check con su estado, también guardaremos el filtro, que podrá ser: “Todos” , “Activos” o “ Completados”.</p><p>Podéis descargar el proyecto desde <a href="https://github.com/wooltar/StoreReduxAngular">mi repo en github</a> o seguir los siguientes pasos.</p><p>Lo primero que vamos a hacer es generar un proyecto con angular-cli</p><p>ng new mystore</p><p>Entramos en el proyecto e instalamos redux</p><p>npm install -s redux</p><p>Creamos las interfaces necesarias para nuestra app</p><pre>export interface Action {<br>   type: string; <br>   payload?: any;<br>}</pre><pre>export interface Todo {<br>   id: number;<br>   text: string;<br>   completed: Boolean;<br>}</pre><pre>export interface AppState {<br>   todos: Todo[];<br>}</pre><p>Tenemos una interface “Item”, donde guardaremos la información de cada item de la compra. AppState guardará un array de los items.</p><p>La otra interface, es la acción que debe tener un tipo y un payload, opcional.</p><p>Ahora vamos con los reducer. Tenemos dos, como ya dijimos, uno para el filtro de visibilidad y otro para los items.</p><p>El primero únicamente settea el filtro que le pasamos. Y el segundo en ADD_ITEM, añade el item que lo pasamos a través de la acción a los estados</p><pre>export const visibilityFilter = (state = &#39;SHOW_ALL&#39;, action) =&gt; {</pre><pre>  switch (action.type) {</pre><pre>    case SET_VISIBILITY_FILTER:</pre><pre>      return action.filter;</pre><pre>    default:</pre><pre>      return state;</pre><pre>  }</pre><pre>};</pre><pre>export const items = (state = [], action) =&gt; {</pre><pre>  switch (action.type) {</pre><pre>    case ADD_ITEM:</pre><pre>      return [</pre><pre>        ...state,</pre><pre>        {</pre><pre>         id: action.id,</pre><pre>         text: action.text,</pre><pre>         completed: false</pre><pre>        }</pre><pre>      ];</pre><pre>    case &#39;TOGGLE_ITEM&#39;:</pre><pre>      return state.map(item =&gt;</pre><pre>        (item.id === action.id)</pre><pre>          ? {...item, completed: !item.completed}</pre><pre>       : item</pre><pre>     );</pre><pre>    default:</pre><pre>      return state;</pre><pre>  }</pre><pre>};</pre><p>Finalmente declaramos el reducer combinando estos dos reducer con “combineReducers” , función disponible en la librería redux.</p><pre>export const reducer: Reducer&lt;AppState&gt; = combineReducers({ visibilityFilter, items });</pre><p>Esto es todo lo que tendriamos que hacer en nuestro fichero reduce.ts</p><p>No olvidemos el fichero actions.ts, aqui es donde declaramos las acciones posibles.</p><pre>// acción añadir item</pre><pre>export const addItem = text =&gt; {<br>  return {<br>    type: &#39;ADD_ITEM&#39;,<br>    id: nextItemId++, <br>    text<br>  };<br>};</pre><p>Ahora vamos a declarar nuestro store en el componente, en este caso, app.component.ts.</p><pre>store: Store&lt;AppState&gt;;</pre><p>También declaramos un array de items que será informado por el store.</p><pre>items: Item[];</pre><p>Iniciamos el store en el método ngOnInit, para que arranque al iniciar la aplicación.</p><pre>ngOnInit() {</pre><pre>  this.store = createStore&lt;AppState&gt;(reducer);<br>  <br> ...</pre><p>Para poder añadir items a nuestra lista de la compra, usamos el método dispatch, pasándole la acción addItem, lo que nos permite añadir un nuevo item a la lista de la compra.</p><pre>addTodo(task: string) {</pre><pre>  this.store.dispatch(addItem(task));</pre><pre>}</pre><p>Para poder pasar a completado el item tendremos otra función que será invocada cuando se pulse el checkbox del item.</p><pre>complete(item: Item) {</pre><pre>  this.store.dispatch(toggleItem(item.id));</pre><pre>}</pre><h3>Filtros</h3><p>Para manejar los filtros, tenemos que hacer:</p><p>1.- Añadir los link para poder seleccionar un filtro u otro.</p><p>2.- Añadir la funcion que llama al store y cambia el estado del filtro.</p><p>3.- Filtrar la respuesta del store para que segun el filtro que seleccionemos rellene el array con los items que deben mostrarse.</p><pre>...</pre><pre>const unsubscribe = this.store.subscribe(() =&gt; {</pre><pre>  const filter = this.store.getState().visibilityFilter;</pre><pre>  if (filter === VisibilityFilters.SHOW_COMPLETED) {</pre><pre>    this.items = this.store.getState().items.filter(t =&gt; t.completed);</pre><pre>    }else {</pre><pre>      if (filter === VisibilityFilters.SHOW_ACTIVE) {</pre><pre>        this.items = this.store.getState().items.filter(t =&gt; !t.completed);</pre><pre>      }else {</pre><pre>        this.items = this.store.getState().items;</pre><pre>     }</pre><pre>   }</pre><pre>this.filter = filter;</pre><pre>});</pre><p>Cuando se haga click en uno de los filtros llamara a esta funcion</p><pre>changeFilter(id: number) {</pre><pre>  this.store.dispatch(setVisibilityFilter(this.filters[id]));</pre><pre>}</pre><p>Que activa, en el store, el filtro que hayamos seleccionado.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*BeHLyAw1z7HYn6EV4yB9GQ.gif" /><figcaption>Para arrancar la aplicación: npm start</figcaption></figure><h3>Acabando</h3><p>Después de haber aprendido a usar el store de Redux en Angular, puedo decir, que el manejo de estados es cosa de niños. Es facil de implentar y ademas nos proporciona un control total sobre el estado del store, por tanto, de la aplicación.</p><p>Creo que no me dejo nada. Si tenéis dudas, algo no esta claro o si veis algún error, no dudéis en dejar un comentario.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*zJsbSLTqC5Mn7qvshwTKBw.png" /></figure><blockquote>Se mejor que tu yo de ayer</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbd49dd4899c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>