<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://arturojc.dev/feed.xml" rel="self" type="application/atom+xml" /><link href="https://arturojc.dev/" rel="alternate" type="text/html" /><updated>2026-11-26T02:46:50+00:00</updated><id>https://arturojc.dev/feed.xml</id><title type="html">Arturo Javier-Castellanos</title><subtitle>Full-stack TypeScript developer and lead developer at a B2B SaaS company, previously in academic philosophy.</subtitle><author><name>Arturo Javier-Castellanos</name></author><entry><title type="html">I’m a newcomer to DevOps. Here’s how ChatGPT helped me deploy my full stack application to Google Kubernetes Engine over the weekend</title><link href="https://arturojc.dev/devops/2023/11/08/im-a-newcomer-to-devops.html" rel="alternate" type="text/html" title="I’m a newcomer to DevOps. Here’s how ChatGPT helped me deploy my full stack application to Google Kubernetes Engine over the weekend" /><published>2023-11-08T22:04:39+00:00</published><updated>2023-11-08T22:04:39+00:00</updated><id>https://arturojc.dev/devops/2023/11/08/im-a-newcomer-to-devops</id><content type="html" xml:base="https://arturojc.dev/devops/2023/11/08/im-a-newcomer-to-devops.html"><![CDATA[<p>Last week, I deployed an application to Google Kubernetes Engine with the help of ChatGPT–you can find it <a href="https://stepbystepstrength.com/dashboard">here</a>. I was very impressed with the quality of ChatGPT’s assistance, so I decided to write a short post describing my experience in some detail.</p>

<h2 id="prior-devops-experience">Prior DevOps experience</h2>

<p>I said I was a newcomer to DevOps. But how much of a newcomer, exactly? Prior to this, I had deployed three applications to Heroku, and one to Netlify. I was familiar with environment variables. I knew some basic Docker commands, and I had a basic understanding of the core Kubernetes concepts: clusters, nodes, pods, deployments and services. I completed the <a href="https://kubernetes.io/docs/tutorials/hello-minikube/">Hello Minikube tutorial</a>. I have played around the Google Cloud Console. So, while I was not an <em>absolute</em> newcomer, this was well beyond my comfort zone.</p>

<h2 id="overview">Overview</h2>

<p>I would divide the process of deploying my application into the following stages:</p>

<ul>
  <li>Writing build scripts</li>
  <li>Containerizing my applications</li>
  <li>Creating, testing out and debugging deployments and services in Minikube</li>
  <li>Setting up Google Cloud SDK</li>
  <li>Seeding my database</li>
  <li>Securing my application with HTTPS</li>
</ul>

<p>When I talk about “deploying” my application, I am using the word in an overly wide sense–I suppose some of these are not really part of deployment.</p>

<h2 id="writing-build-scripts">Writing build scripts</h2>

<p>My backend is a Node.js server written in TypeScript. Since Node.js cannot execute TypeScript, TypeScript applications generally require a “build step” where all your code is compiled into JavaScript before it can be executed. Usually, this involves running the <code class="language-plaintext highlighter-rouge">tsc</code> command to tell the TypeScript compiler to compile your TypeScript code. This needs to be done any time the source code changes.</p>

<p>As you can imagine, this gets old pretty fast when you are actively developing an application, which is why I use <a href="https://typestrong.org/ts-node/"><code class="language-plaintext highlighter-rouge">ts-node</code></a> for development. Since I cannot use <code class="language-plaintext highlighter-rouge">ts-node</code> in production, that means I needed separate <code class="language-plaintext highlighter-rouge">npm</code> scripts for development and production.</p>

<p>So, my first task before I could deploy my application was to write a <code class="language-plaintext highlighter-rouge">build</code> script.</p>

<p>This is where I encountered my first two problems.</p>

<p>When you compile TypeScript into JavaScript, the resulting JavaScript is placed in a different directory of your choosing. Since the structure of your output directory (typically <code class="language-plaintext highlighter-rouge">/dist</code>) perfectly mirrors the structure of your input directory (typically <code class="language-plaintext highlighter-rouge">/src</code>), this usually causes no issues, <em>except when your code uses relative paths for file imports</em>. Once your code is compiled and placed into the <code class="language-plaintext highlighter-rouge">/dist</code> directory, these paths may still be pointing to the <code class="language-plaintext highlighter-rouge">/src</code> directory. Learned that the hard way!</p>

<p>The second problem happens when your codebase contains files that are not written in TypeScript. Since my backend has a GraphQL API, my codebase contains a number of <code class="language-plaintext highlighter-rouge">.graphql</code> files. The problem is that when you run <code class="language-plaintext highlighter-rouge">tsc</code>, <em>the TypeScript compiler does not copy non-TypeScript files to the output directory</em>. Therefore you need to add another command to your <code class="language-plaintext highlighter-rouge">build</code> script–in my case, <code class="language-plaintext highlighter-rouge">cp src/**/*.graphql dist/</code></p>

<p>While I could have solved both problems on my own, this was nevertheless a place where ChatGPT really shined, successfully diagnosing both problems in one or two prompts, accelerating a process that would have otherwise taken me at least twice as long.</p>

<h2 id="containerizing-my-applications">Containerizing my applications</h2>

<p>The functioning of your application should not depend on the peculiarities of the environment where it’s deployed. When deploying your application to production, therefore, you want to run your application as a <strong>container</strong>. This involves creating a <em>container image</em>, which is a standalone, executable package that contains everything you need to run your application. You need a container image for every part of your application–in my case, my frontend and backend.</p>

<p>To create a container image, you want to write something called a “Dockerfile”, which is a set of instruction that tells the Docker Engine how to build a container image for your application.</p>

<p>This is where I ran into one of the hardest problems I dealt with. I used Angular to build my frontend. Once Angular compiled my application into a bunch of static files, I needed something else to serve those static files. ChatGPT recommended Nginx. However, getting Nginx to work with my frontend as a container was way harder than I was expected.</p>

<p>The difficulty was compounded by two decisions I made: (1) Nginx had to proxy requests to <code class="language-plaintext highlighter-rouge">/api</code> to my backend, (2) when building my Angular application, I used the <code class="language-plaintext highlighter-rouge">--base-href /app</code> flag because I was originally wanted to serve my application from the <code class="language-plaintext highlighter-rouge">/app</code> subpath in order to reserve the root for a static landing page for SEO purposes. The latter ended up being so difficult that I decided to scrap that idea.</p>

<p>This being my first time working with Nginx, ChatGPT’s help proved invaluable. It actually felt like teamwork. It was surreal. We created a configuration file for Nginx, and when that wasn’t working, we simplified our configuration with the goal of expanding on that once we had a working baseline, each of us suggesting various changes.</p>

<p>I say this felt like teamwork partly because I didn’t just blindly follow ChatGPT’s advice. When I first raised the issue that Nginx was not serving my Angular app, ChatGPT suggested that I <code class="language-plaintext highlighter-rouge">exec</code> into the Docker container and make changes to the configuration from there. I thought this was a bad idea, so I pushed back:</p>

<blockquote>
  <p>ChatGPT: […] Once you’ve made these changes to your Nginx configuration inside the Docker container, you should be able to access any Angular route directly and have your API requests proxied correctly to your backend server.</p>

  <p>Arturo: Excellent. However, you said to make these changes to my Nginx configuration inside the Docker container. I do not currently have an Nginx configuration file in my frontend. I understand I can go into the container in interactive mode, but that seems inconvenient. Is there a way I can just add an Ngnix configuration file to my application prior to containerizing?</p>

  <p>ChatGPT: Yes, you can provide a custom Nginx configuration from outside the Docker container, which is a common and recommended practice. This approach ensures that your Nginx configuration is version controlled and can be easily replicated across different environments.</p>

  <p>Here’s a step-by-step guide to doing this: […]</p>
</blockquote>

<h2 id="creating-testing-out-and-debugging-deployments-and-services-in-minikube">Creating, testing out and debugging deployments and services in Minikube</h2>

<p>Once I had container images for all parts of my application, the next step was to create Kubernetes Deployments and Services, which is normally done by writing a Kubernetes manifest for each Service or Deployment.</p>

<p>Each Deployment manifest references an image of some part of your application-for instance the frontend or the backend. When you use the manifest to create the desired Deployment, the container runtime pulls the image from a given registry and creates a container.</p>

<p>ChatGPT pretty much wrote all my manifests for me. It also taught me how to use Minikube to test out the resulting Services and Deployments. While the container runtime normally pulls the specific image from a remote registry, Minikube has a local image registry. You can create and store an image to this registry. When you create a Kubernetes Deployment in Minikube that references that image, Minikube’s container runtime will then fetch the image <em>directly from the local registry</em>.</p>

<p>This makes it super convenient to test out Deployments, as you do not need to push your images to a remote registry before you can use them in your pods.  You can just build them directly on Minikube. To do this, all you have to do is run <code class="language-plaintext highlighter-rouge">eval $(minikube docker-env)</code>. This executes a number of <code class="language-plaintext highlighter-rouge">export</code> commands that point your Docker client to the Docker daemon inside the Minikube virtual machine. Since the docker client is not pointed to Minkube’s Docker daemon, when you later run <code class="language-plaintext highlighter-rouge">docker build -t some-image .</code>, <em>the image will be stored to Minikube’s local registry</em>. Pretty neat!</p>

<p>This was definitely one of the hardest parts of the process of me, and I spent a ton of time <code class="language-plaintext highlighter-rouge">exec</code>-ing into various pods to debug various issues. Again, I was very glad to have ChatGPT by my side for this.</p>

<h2 id="setting-up-google-cloud-sdk">Setting up Google Cloud SDK</h2>

<p>This was a breeze with ChatGPT’s intructions. No difficulties.</p>
<h2 id="seeding-my-database">Seeding my database</h2>

<p>For development purposes, I wrote a <code class="language-plaintext highlighter-rouge">seed</code> script that seeds the database with the initial data that the application needs to function. However, I assumed this approach would not work in production. Since my backend uses TypeORM to query the database, which has support for <a href="https://typeorm.io/migrations">migrations</a>, I asked ChatGPT to help me re-write my seed script into a migration. However, ChatGPT talked me out of this by pointing out that migrations are not intended for seeding, but for schema changes. Instead, it taught me to use Kubernetes Jobs to execute my original <code class="language-plaintext highlighter-rouge">seed</code> scripts (with some modifications suggested by ChatGPT, such as making my script idempotent).</p>

<h2 id="securing-my-application-with-https">Securing my application with HTTPS</h2>

<p>This was <em>by far</em> the most difficult part of the process. Just about everything went wrong the first time around. Not coincidentally, it was also the part of the process ChatGPT was the <em>least</em> useful at.</p>

<p>To secure my application, ChatGPT suggested I install <code class="language-plaintext highlighter-rouge">cert-manager</code>, which is a Kubernetes add-on that manages TLS certificates from various sources. My problems started the moment I tried to install <code class="language-plaintext highlighter-rouge">cert-manager</code>. The first problem was that I deployed my application to a GKE Autopilot cluster. As the “autopilot” name suggests, Google completely manages the cluster, and therefore will not let you create any resources in the <code class="language-plaintext highlighter-rouge">kube-system</code> namespace. If you use <code class="language-plaintext highlighter-rouge">helm</code> to install <code class="language-plaintext highlighter-rouge">cert-manager</code>, however, <code class="language-plaintext highlighter-rouge">helm</code> will, as part of the installation process, try to create a number of resources in the <code class="language-plaintext highlighter-rouge">kube-system</code> namespace. Instead of giving you an error message like–I don’t know, “failed to create resource”–the installation will simply fail a 5-minute startup check with the very helpful message:  “failed post-install: timed out waiting for the condition”.</p>

<p>As detailed in <a href="https://github.com/cert-manager/cert-manager/issues/3713">this issue</a>, the solution is to use the flag <code class="language-plaintext highlighter-rouge">--set global.leaderElection.namespace=cert-manager</code>,  which tells <code class="language-plaintext highlighter-rouge">helm</code> to use the <code class="language-plaintext highlighter-rouge">cert-manager</code> namespace instead of the <code class="language-plaintext highlighter-rouge">kube-system</code> namespace.</p>

<p>The other problem was a boostrapping, or “chicken and egg”-kind of problem where my Ingress controller was not setting my IP correctly because it was missing a valid certificate, but because the IP wasn’t set correctly, requests to the challenge URL that generates a valid certificate never reached the intended service, and the certificate was never generated! As suggested <a href="https://github.com/kubernetes/ingress-gce/issues/733">here</a>, the solution was simply to update to a more recent version of <code class="language-plaintext highlighter-rouge">cert-manager</code>.</p>

<p>This goes to show that as amazing as ChatGPT is, it is still not a full substitute for plain old Google, as otherwise I would not have found the solution to either of these issues.</p>]]></content><author><name>Arturo Javier-Castellanos</name></author><category term="devops" /><summary type="html"><![CDATA[Last week, I deployed an application to Google Kubernetes Engine with the help of ChatGPT-you can find it here. I was very impressed with the quality of ChatGPT's assistance, so I decided to write a short post describing my experience in some detail.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://arturojc.dev/assets/share-card.png" /><media:content medium="image" url="https://arturojc.dev/assets/share-card.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Making my first React app</title><link href="https://arturojc.dev/react/2022/01/06/making-my-first-react-app.html" rel="alternate" type="text/html" title="Making my first React app" /><published>2022-01-06T22:04:39+00:00</published><updated>2022-01-06T22:04:39+00:00</updated><id>https://arturojc.dev/react/2022/01/06/making-my-first-react-app</id><content type="html" xml:base="https://arturojc.dev/react/2022/01/06/making-my-first-react-app.html"><![CDATA[<p>As I mentioned in my previous post, my plan for teaching myself web development is to build a largeish project after each course I complete. The last course I completed was Brad Traversy’s React Front to Back, and so around three weeks or four ago, I set out to build my first React app. Here are the <a href="http://groupreads.herokuapp.com/">results</a>, and here is the <a href="https://github.com/arturo-jc/groupreads">repo</a>.</p>

<p>So, what did I learn making this project? Obviously, I learned the basics of React: how to create a component, how to import one component into another, etc. Too many things to list, to be honest. But the most valuable thing I learned, I think, is I got a big-picture sense of how React works. This is important because while Brad’s course spent a great deal of time on the nuts and bolts, he didn’t really say much about why use React in the first place, how React works, etc. (This is not meant as a criticism. I think Brad just assumes that if you’ve enrolled in his course, you already know why you want to use React.) Anyway, here’s the sense I got from building my own app. And as a disclaimer, what follows is just that: my current sense or understanding of the framework based on my limited experience with it. I’m sure my understanding will evolve as I get more practice.</p>

<h2 id="the-big-picture">The big picture</h2>
<p>One of my first impressions after using React is how long it takes to build an app. I’m sure a lot it can be chalked up to my own inexperience, but I suspect a lot of it has to do with the sheer amount of things that need to get done. For a full stack app like I made, you need to build both a backend and a frontend. It really feels like making two apps. So, why bother with React? Because your content is rendered a lot faster.</p>

<p>With traditional web applications, your server does double duty. It builds a user interface, and it does a bunch of other stuff such as talking to the database. Then it puts everything together, and sends a bunch of files (mainly HTML, CSS and JS) to the browser. And it does this pretty much every time it receives a request. So, every time your server receives a request, it sends a bunch of stuff back: it sends both instructions for how to render the UI, as well as the data the user needs.</p>

<p>The advantage of using React is you don’t need to send the instructions for rendering the UI every time. Your server sends these instructions once, and upon further requests, all it sends is the data the user actually needs to see. Basically, it delegates the rendering of the UI to the browser so it can focus on other tasks like talking to the database, and so it doesn’t have to keep sending instruction for rendering the UI. No need to keep sending a bunch of HTML, CSS and JS files every time! Just the data the user actually needs–things like strings, numbers, and dates depending on the application. That’s a lot less information that’s being sent from your server to your browser, which accounts for why React apps are faster.</p>

<h2 id="state">State</h2>
<p>So, that’s the basic picture I got of React itself. Now for this application, I had to use something called <strong>state</strong>. Often you want a component to be rendered differently at different times. Simple example: when a user clicks on “Delete account”, you don’t want to delete the account right away (what if they clicked by mistake?). Rather, you want to display a confirmation modal or something like that. This modal component needs to be rendered differently at different times: by default, it should not be displayed at all, but it should be displayed if the user clicks “Delete account”. The way you do this in React is you give the component a state (such as <code class="language-plaintext highlighter-rouge">show</code>), which is basically just a variable that can take a number of values (in this case, <code class="language-plaintext highlighter-rouge">true</code> or <code class="language-plaintext highlighter-rouge">false</code>) and whose value can be updated as needed (in this case, set to <code class="language-plaintext highlighter-rouge">true</code> if the user click on “Delete account”).</p>

<p>Sometimes, only one component needs to have access to the state, but not always. For instance, I wanted both the navbar and the account page to display the user’s name, which I stored inside a user state. These are different components, so I needed two components to have access to the same user state. How do you do that? One way is to use <strong>props</strong>.</p>

<p>React components have something called props, which (if you are using functional components) are parameters where you can pass in values as arguments. React will then use these values to render the component differently depending on which arguments you passed–for instance, setting the modal’s display to <code class="language-plaintext highlighter-rouge">block</code> if you set <code class="language-plaintext highlighter-rouge">show</code> to <code class="language-plaintext highlighter-rouge">true</code> and <code class="language-plaintext highlighter-rouge">none</code> if you set it to <code class="language-plaintext highlighter-rouge">false</code>. Usually, you pass these props in the component’s parent component. So, if your modal is inside your account page, for instance, you might write something like this in <code class="language-plaintext highlighter-rouge">Account.js</code>:</p>

<figure class="highlight"><pre><code class="language-jsx" data-lang="jsx">    <span class="p">&lt;</span><span class="nc">Modal</span> <span class="na">show</span><span class="p">=</span><span class="si">{</span><span class="nx">show</span><span class="si">}</span> <span class="p">/&gt;</span></code></pre></figure>

<p>Here, we are passing the value of the <code class="language-plaintext highlighter-rouge">show</code> state to the <code class="language-plaintext highlighter-rouge">Modal</code> component as a prop.</p>

<p>So, props are passed from parent to child. If that’s how we pass states, however, we may end up with long chains of passing where one state is passed from one component to its child, and then from the child to its <em>own</em> child, and so on until the state reaches the desired component. This is known as <strong>prop drilling</strong>, and it can get quite obnoxious, which is why we use context.</p>

<h2 id="context-reducers-and-actions">Context, reducers, and actions</h2>
<p>A context–and again, this is just my current, (possibly incomplete!) understanding–is basically a place where we store states that we then can access from anywhere within our app. There are different ways of implementing context, but I used a context manager called Redux.</p>

<p>Whenever we use states, we need a way of updating those states–setting a modal’s <code class="language-plaintext highlighter-rouge">show</code> state to <code class="language-plaintext highlighter-rouge">true</code> when the user clicks on “Delete account”, or setting <code class="language-plaintext highlighter-rouge">user</code> to <code class="language-plaintext highlighter-rouge">null</code> when they log out. If we’re <em>using component-level</em> state–basically, a state that only one component needs access too–this is quite easy to do. React comes with a built-in <code class="language-plaintext highlighter-rouge">useState</code> function which initializes a <em>state</em> variable to a <code class="language-plaintext highlighter-rouge">defaultValue</code> and simultaneously creates a corresponding <code class="language-plaintext highlighter-rouge">setState</code> function that we can then use to update the state in question:</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">const</span> <span class="p">[</span> <span class="nx">show</span><span class="p">,</span> <span class="nx">setShow</span> <span class="p">]</span> <span class="o">=</span> <span class="nx">useState</span><span class="p">(</span><span class="nx">defaultValue</span><span class="p">)</span></code></pre></figure>

<p>This is all done from within the component that needs access to the state, and since we are dealing with component-level state, there is no need to pass it around.</p>

<p>If we are using <em>app-level state</em>–state that need to access from anywhere within our application–well, that’s a different story. If you use Redux like I did, you want to use something called <strong>reducers</strong>, whose sole purpose is to update your app’s state. However, you don’t want to call these reducers directly. Instead, you want to create something called actions, which are functions responsible for calling the reducers.</p>

<p>Why the extra step? Because, often, your app’s state is not the only thing that needs updating. If a user deletes a post, for instance, and you have your posts stored in your app’s state, then, of course, you want to update the state, but you also want to update the database. Otherwise, that pesky post will not really be gone–it will show up again on the next session.</p>

<p>So, often, you want to keep your state and your database in synch–and that’s where actions come in. Actions help you update your state and your database in parallel (or roughly in parallel). So, for instance, you might have a <code class="language-plaintext highlighter-rouge">deletePost</code> action which takes a post ID as an argument and makes a <code class="language-plaintext highlighter-rouge">DELETE</code> request to your server to tell it to delete the post from the database. Once the database is updated, your <code class="language-plaintext highlighter-rouge">deletePost</code> action can tell the reducer to delete the post from the state. So, <code class="language-plaintext highlighter-rouge">deletePost</code> is responsible for talking to both the database and the reducers, and this is how you can keep your database and state in synch.</p>

<p>One of the most important things I learned in this project was probably how to make efficient use of actions. And one point, I was using <code class="language-plaintext highlighter-rouge">deletePost</code> to update the database only. It would make a <code class="language-plaintext highlighter-rouge">DELETE</code> request to the server, but it wouldn’t tell the reducer to update the state. Instead, I called another action <code class="language-plaintext highlighter-rouge">getPosts</code>, which made a <code class="language-plaintext highlighter-rouge">GET</code> request to the server to fetch all the relevant posts. The server would send those posts back to my frontend, which would then call the reducers to update the state. Only then would my app’s state update. I then realized this was stupid because I was making two separate calls to my server, and because I was requesting a lot of unnecessary data. When a user deletes a post, all other posts remain unchanged and so I don’t need to get all posts–I already have most of them stored in the app, and most of them are up to date. To update the state, all I need is the one post that got deleted–and not even that, just the ID. As soon as I realized this, I switched to the correct approach: use the same action to update both the database and the state. No separate calls.</p>

<h2 id="next-steps">Next steps</h2>
<p>Well, I think that just about sums up the most important things I learned in making my first React app.</p>

<p>I now have three apps, only two more to go until I have a working portfolio. I have been so busy making apps that I have neglected my personal website, so this feels like a good time to take a breaking from app-making to give my website a little upgrading, putting to use everything I’ve learned so far.</p>]]></content><author><name>Arturo Javier-Castellanos</name></author><category term="react" /><summary type="html"><![CDATA[As I mentioned in my previous post, my plan for teaching myself web development is to build a largeish project after each course I complete. The last course I completed was Brad Traversy’s React Front to Back, and so around three weeks or four ago, I set out to build my first React app. Here are the results...]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://arturojc.dev/assets/share-card.png" /><media:content medium="image" url="https://arturojc.dev/assets/share-card.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Making my first Express app</title><link href="https://arturojc.dev/express/2021/12/06/making-my-first-express-app.html" rel="alternate" type="text/html" title="Making my first Express app" /><published>2021-12-06T22:04:39+00:00</published><updated>2021-12-06T22:04:39+00:00</updated><id>https://arturojc.dev/express/2021/12/06/making-my-first-express-app</id><content type="html" xml:base="https://arturojc.dev/express/2021/12/06/making-my-first-express-app.html"><![CDATA[<p>Two weeks ago, I completed Colt Steele’s web dev bootcamp and set out to build my own app applying what I learned. Here are the <a href="https://tidybuddy.herokuapp.com/">results</a>, and here’s the <a href="https://github.com/arturo-jc/TidyBuddy">repository</a></p>

<p>(This is part of my larger plan to teach myself web development by doing one largeish project after each course I complete. Next up, Brad Traversy’s React Front to Back).</p>

<p>Anyway, this time I made a point to write down each thing I learned as I worked on my project. Looking at my list, it may be broken down into three big topics:</p>

<ul>
  <li>Express</li>
  <li>EJS</li>
  <li>Mongoose</li>
</ul>

<h2 id="express">Express</h2>
<p>One of the big things I learned about Express was how to handle errors in a more organized way—how to divide the labor between controllers, middleware and error-handler.</p>

<p>In Colt Steele’s course, I learned how to use middleware to perform some basic checks—is the user logged in? Does the user own the resource in question? I copied this basic pattern, but at one point I found myself performing simple checks in the controllers themselves—for instance, checking if two passwords matched. I did this out of convenience—the logic was simple and didn’t reduce readability. I was both throwing errors and <em>handling</em> those errors in the controllers themselves—flashing and redirecting the user in some cases, calling next on the error in others. I was also handling errors directly in my middleware—again, flashing/redirecting in some middleware functions, calling next in others. But then I realized this was probably not a good idea in the long run.</p>

<p>So, what did I do? I delegated <em>all</em> authorization checks to my middleware, and used my controllers exclusively for interacting with the DB and rendering templates—no errors thrown in my controllers. And then I moved <em>all</em> the error handling—all the decision-making as to how to handle this or that error—from my middleware to my… well, error-handler.</p>

<p>This involved some creativity. When I was handling errors and failed checks directly in the controllers, this was easy—I could simply flash and redirect right from the controller, for instance. Now I had to tell the error-handler what to do with a given error via the middleware. How do I tell the error-handler that I want certain errors flashed and others rendered?</p>

<p>To do this, I adapted a technique I learned from Colt Steele. Following Steele, I defined an <code class="language-plaintext highlighter-rouge">ExpressError</code> class that extends <code class="language-plaintext highlighter-rouge">Error</code> and has <code class="language-plaintext highlighter-rouge">message</code> and <code class="language-plaintext highlighter-rouge">statusCode</code> parameters, except I added an optional <code class="language-plaintext highlighter-rouge">name</code> parameter. Then I used this <code class="language-plaintext highlighter-rouge">name</code> parameter to communicate from my middleware to my error-handler how I wanted each error handled. So, for instance, some middleware functions would throw an <code class="language-plaintext highlighter-rouge">ExpressError</code> and pass in “AuthorizationErrorFlash” as its name, others would pass “AuthorizationErrorRender”, and my error-handler would handle them accordingly. Then, when I wanted an authorization error in a given route to result in a flash message, I would simply pass in the appropriate middleware to the route in question. If I change my mind later on, it’s as easy as passing in a different middleware.</p>

<p>The other big thing I learned about Express was how to pass data directly from one controller to another—without the use of the DB.</p>

<p>Here’s the problem I faced. My dashboard template contains a feed. Inside the feed there can be many activities. Each activity has a comment section that’s hidden by default. The user can decide to open the comment section and post a comment, at which point the page refreshes, which means all comment sections are again hidden by default. That’s bad user experience. If you post a comment, you want to see it right away. So whenever a user posts a comment, I had to render the template in such a way that all comment sections are hidden by default <em>except for</em> whichever activity the user just commented under.</p>

<p>How do you do that? The first part was easy. From my <code class="language-plaintext highlighter-rouge">showHousehold</code> controllers which renders the dashboard, pass in a string to an <code class="language-plaintext highlighter-rouge">activityId</code> parameter in <code class="language-plaintext highlighter-rouge">res.render</code>, then when you’re rendering the comment sections below each activity, use EJS to include a “hidden” class if and only if the activity’s ID matches whatever string you passed as <code class="language-plaintext highlighter-rouge">activityId</code>:</p>

<figure class="highlight"><pre><code class="language-ejs" data-lang="ejs">    &lt;div class="comment-section &lt;%= activity._id.toString() === activityId? '' : 'hidden' %&gt;"&gt;</code></pre></figure>

<p>The problem is, how do I get the ID of whichever activity the user just commented under? Well, comments are created in my <code class="language-plaintext highlighter-rouge">createComment</code> controller, so that’s where the ID had to come from.</p>

<p>One option would have been to render the dashboard right from the <code class="language-plaintext highlighter-rouge">createComment</code> controller, but that wasn’t a good idea. There’s a good deal of logic that goes into rendering the dashboard, so rendering it from both <code class="language-plaintext highlighter-rouge">showHousehold</code> and <code class="language-plaintext highlighter-rouge">createComment</code> would have resulted in a lot of duplication.</p>

<p>Rather than rendering, I had to redirect the user to my show household route so that my <code class="language-plaintext highlighter-rouge">showHousehold</code> controller could carry out all that logic, but I had to somehow pass the activity ID from <code class="language-plaintext highlighter-rouge">createComment</code> over to <code class="language-plaintext highlighter-rouge">showHousehold</code>.</p>

<p>How do you do that? My solution was to pass it as a query string. Then I could simply catch the activity ID in <code class="language-plaintext highlighter-rouge">showHousehold</code> and pass it to <code class="language-plaintext highlighter-rouge">res.render</code> so that my app knows which comment sections to display and which to hide.</p>

<h2 id="ejs">EJS</h2>
<p>Two big things, which are probably going to strike experienced users as quite basic.</p>

<p>At one point, I needed to call a function that calculates the first day of the current week inside an EJS template. But I didn’t want to <em>define</em> the function inside the template—I didn’t want to clutter the template. Besides, I may need that function again in a different template. So, I learned that if you have some reusable JS code, you can always move it all to its dedicated EJS file, then include that file where needed. Handy!</p>

<p>Another problem I faced was I wanted to loop over an array and create a todo-item for each element of the array. Since I wanted to reuse this code, I created a dedicated <code class="language-plaintext highlighter-rouge">item.ejs</code> partial I could include in different places. First, I tried:</p>

<figure class="highlight"><pre><code class="language-ejs" data-lang="ejs">    for (let item of items){
        &lt;%- include("./item") %&gt;
    }</code></pre></figure>

<p>Bad news: item is undefined in <code class="language-plaintext highlighter-rouge">item.ejs</code>. Good news: the solution was not too far off. After a bit of googling, I discovered you can simply pass arguments to template parameters (such as item) by putting them inside an object and passing that object to <code class="language-plaintext highlighter-rouge">include</code>, so I made a new <code class="language-plaintext highlighter-rouge">items.ejs</code> partial and did:</p>

<figure class="highlight"><pre><code class="language-ejs" data-lang="ejs">    for (let item of frequentItems){
        &lt;%- include("./items", {items: frequentItems}) %&gt;
    }</code></pre></figure>

<p>Now I can use the same <code class="language-plaintext highlighter-rouge">items.ejs</code> partial and just pass different arrays into the items parameter. Neat!</p>

<h2 id="mongoose">Mongoose</h2>
<p>This is probably the topic I learned the most about.</p>

<p>The most important thing I learned was probably populating a document several levels deep.</p>

<p>In my app, every user should belong to a household. In order to render the dashboard, the user’s household document needs to be <em>fully</em> populated—every field and subfield.</p>

<p>My household documents have an <code class="language-plaintext highlighter-rouge">activityTypes</code> field, which is meant to store an array of activity type documents. Easy enough to populate:</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript">    <span class="kd">const</span> <span class="nx">household</span> <span class="o">=</span> <span class="k">await</span> <span class="nx">Household</span><span class="p">.</span><span class="nx">findById</span><span class="p">(</span><span class="nx">householdId</span><span class="p">)</span>
        <span class="p">.</span><span class="nx">populate</span><span class="p">(</span><span class="dl">"</span><span class="s2">activityTypes</span><span class="dl">"</span><span class="p">)</span></code></pre></figure>

<p>Problem is, activity type documents have a <code class="language-plaintext highlighter-rouge">completedBy</code> field, which is meant to store an array of activity documents. That needs to be populated as well. No big deal:</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript">    <span class="kd">const</span> <span class="nx">household</span> <span class="o">=</span> <span class="k">await</span> <span class="nx">Household</span><span class="p">.</span><span class="nx">findById</span><span class="p">(</span><span class="nx">householdId</span><span class="p">)</span>
        <span class="p">.</span><span class="nx">populate</span><span class="p">({</span>
            <span class="na">path</span><span class="p">:</span> <span class="dl">"</span><span class="s2">activityTypes</span><span class="dl">"</span><span class="p">,</span>
            <span class="na">populate</span><span class="p">:</span> <span class="p">{</span> <span class="na">path</span><span class="p">:</span> <span class="dl">"</span><span class="s2">completedBy</span><span class="dl">"</span> <span class="p">}</span>
        <span class="p">});</span></code></pre></figure>

<p>So far, so good. But activity documents have a <code class="language-plaintext highlighter-rouge">user</code> field that itself needs to be populated. And that’s how I ended up with this monstruous-looking thing:</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript">    <span class="nx">household</span> <span class="o">=</span> <span class="k">await</span> <span class="nx">Household</span><span class="p">.</span><span class="nx">findById</span><span class="p">(</span><span class="nx">householdId</span><span class="p">)</span>
        <span class="p">.</span><span class="nx">populate</span><span class="p">({</span>
            <span class="na">path</span><span class="p">:</span> <span class="dl">"</span><span class="s2">activityTypes</span><span class="dl">"</span><span class="p">,</span>
            <span class="na">populate</span><span class="p">:</span> <span class="p">{</span>
                <span class="na">path</span><span class="p">:</span> <span class="dl">"</span><span class="s2">completedBy</span><span class="dl">"</span><span class="p">,</span>
                <span class="na">populate</span><span class="p">:</span> <span class="p">{</span> <span class="na">path</span><span class="p">:</span> <span class="dl">"</span><span class="s2">user</span><span class="dl">"</span> <span class="p">}</span>
                <span class="p">}</span>
            <span class="p">});</span></code></pre></figure>

<p>The second big thing I learned was how to delete subdocument arrays.</p>

<p>In addition to the <code class="language-plaintext highlighter-rouge">user</code> field mentioned above, my activity documents also have a <code class="language-plaintext highlighter-rouge">comments</code> field, which is meant to store an array of—you guess it—comment documents. When an activity is deleted, there is nowhere for its comments to go, and so those comments should be automatically deleted along with it.</p>

<p>Turns out Mongoose middleware is tailor-made for this. All I had to do was plug this in to my activity schema:</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript">    <span class="nx">ActivitySchema</span><span class="p">.</span><span class="nx">post</span><span class="p">(</span><span class="dl">"</span><span class="s2">findOneAndDelete</span><span class="dl">"</span><span class="p">,</span> <span class="k">async</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">activity</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">if</span> <span class="p">(</span><span class="nx">activity</span><span class="p">)</span> <span class="p">{</span>
            <span class="k">await</span> <span class="nx">Comment</span><span class="p">.</span><span class="nx">deleteMany</span><span class="p">({</span> <span class="na">_id</span><span class="p">:</span> <span class="p">{</span> <span class="na">$in</span><span class="p">:</span> <span class="nx">activity</span><span class="p">.</span><span class="nx">comments</span> <span class="p">}</span> <span class="p">})</span>
        <span class="p">}</span>
    <span class="p">});</span></code></pre></figure>

<p>This tells Mongoose that if it deletes an activity, it should also delete all comments whose Id is included in the activity’s comments field, which is just what I wanted.</p>

<p>The third big thing I learned about Mongoose is how to delete “dead” references from documents. Here’s what I mean.</p>

<p>My household documents have a <code class="language-plaintext highlighter-rouge">users</code> field, which is meant to store an array of user documents. Except it doesn’t actually store the documents inside the array—instead, it stores a <em>reference</em> to each document that Mongoose uses to fetch the documents in question.</p>

<p>The problem is that when you delete a user document from the DB, the reference is not deleted from the users array. The array now contains a reference to a document that no longer exists. This is what I meant by a “dead” reference. This doesn’t cause problems in my limited experience, but I don’t like it all the same.</p>

<p>Since Mongoose wouldn’t automatically remove these references for me, I had to learn how to do it myself. So now when I delete a user in my <code class="language-plaintext highlighter-rouge">deleteAccount</code> controller, I call:</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript">    <span class="k">await</span> <span class="nx">Household</span><span class="p">.</span><span class="nx">updateMany</span><span class="p">(</span>
        <span class="p">{</span> <span class="na">users</span><span class="p">:</span> <span class="nx">user</span> <span class="p">},</span>
        <span class="p">{</span> <span class="na">$pull</span><span class="p">:</span> <span class="p">{</span> <span class="na">users</span><span class="p">:</span> <span class="nx">user</span><span class="p">.</span><span class="nx">_id</span> <span class="p">}</span> <span class="p">}</span>
    <span class="p">);</span></code></pre></figure>

<p>In a StackOverFlow thread, someone suggested to use Mongoose middleware for this purpose. However, I ran into circularity issues when I tried this approach (I was requesting two models into each other and using them to define each other). For all I know, it may be possible to get around this problem, but I didn’t keep trying as I was satisfied with the solution above.</p>

<p>The last Mongoose thing I learned was this. In my app, a user can request to join a household. When a user makes a request, I want to push the user into the household’s <code class="language-plaintext highlighter-rouge">pendingRequests</code> field, but <em>only if the user is not already in the field in question</em> (no point adding them twice over!)</p>

<p>I spent an embarrassing amount of time searching how to perform this kind of logic with Mongoose’s <code class="language-plaintext highlighter-rouge">findByIdAndUpdate</code> method, but it was worth it in the end because I learned about Mongo’s <code class="language-plaintext highlighter-rouge">$addToSet</code> operator, which does exactly what I wanted:</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript">    <span class="k">await</span> <span class="nx">Household</span><span class="p">.</span><span class="nx">findByIdAndUpdate</span><span class="p">(</span><span class="nx">householdId</span><span class="p">,</span>
        <span class="p">{</span>
            <span class="na">$addToSet</span><span class="p">:</span> <span class="p">{</span> <span class="na">pendingRequests</span><span class="p">:</span> <span class="nx">req</span><span class="p">.</span><span class="nx">user</span> <span class="p">}</span>
        <span class="p">}</span>
    <span class="p">);</span></code></pre></figure>

<p>One last thing that’s not exactly about Mongoose, but about a Mongoose plugin. For authentication, I used <code class="language-plaintext highlighter-rouge">passport</code> in conjunction with <code class="language-plaintext highlighter-rouge">passport-local-mongoose</code>. What the last package does is it adds a number of methods to your <code class="language-plaintext highlighter-rouge">User</code> model. You can use these methods to create and pass a strategy to <code class="language-plaintext highlighter-rouge">passport</code> like so:</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript">    <span class="nx">passport</span><span class="p">.</span><span class="nx">use</span><span class="p">(</span><span class="k">new</span> <span class="nx">LocalStrategy</span><span class="p">(</span><span class="nx">User</span><span class="p">.</span><span class="nx">authenticate</span><span class="p">()));</span></code></pre></figure>

<p>(<code class="language-plaintext highlighter-rouge">LocalStrategy</code> comes from a further package called <code class="language-plaintext highlighter-rouge">passport-local</code>—more about it in a moment).</p>

<p>However, I did not like the way <code class="language-plaintext highlighter-rouge">passport-local-mongoose</code> handles authentication by default. It fetches the user by username. I didn’t like that. Fortunately, you can tell <code class="language-plaintext highlighter-rouge">passport-local-mongoose</code> to use email instead:</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript">    <span class="nx">UserSchema</span><span class="p">.</span><span class="nx">plugin</span><span class="p">(</span><span class="nx">passportLocalMongoose</span><span class="p">,</span> <span class="p">{</span> <span class="na">usernameField</span><span class="p">:</span> <span class="dl">"</span><span class="s2">email</span><span class="dl">"</span> <span class="p">});</span></code></pre></figure>

<p>However, this is still not going to work—and this took me an embarrassingly long time to figure out. As I said, what this plug in does is add methods to your User model that you can then use to create and pass a strategy to passport. One of those methods is .authenticate, which works just fine if you’re happy with the way <code class="language-plaintext highlighter-rouge">passport-local-mongoose</code> handles authentication by default. But if you want it to use email instead (like I told it to above), you need to use a different method called <code class="language-plaintext highlighter-rouge">.authenticate</code> like so:</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript">    <span class="nx">passport</span><span class="p">.</span><span class="nx">use</span><span class="p">(</span><span class="nx">User</span><span class="p">.</span><span class="nx">createStrategy</span><span class="p">());</span></code></pre></figure>

<p>Notice I am no longer relying on <code class="language-plaintext highlighter-rouge">LocalStrategy</code>, which means I no longer need to require <code class="language-plaintext highlighter-rouge">passport-local</code>.</p>

<p>And that’s it for now.</p>

<p>Until next time!</p>]]></content><author><name>Arturo Javier-Castellanos</name></author><category term="express" /><summary type="html"><![CDATA[Two weeks ago, I completed Colt Steele’s web dev bootcamp and set out to build my own app applying what I learned. Here are the results...]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://arturojc.dev/assets/share-card.png" /><media:content medium="image" url="https://arturojc.dev/assets/share-card.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Making my first web app with flask</title><link href="https://arturojc.dev/flask/2021/10/21/making-my-first-web-app-with-flask.html" rel="alternate" type="text/html" title="Making my first web app with flask" /><published>2021-10-21T22:04:39+00:00</published><updated>2021-10-21T22:04:39+00:00</updated><id>https://arturojc.dev/flask/2021/10/21/making-my-first-web-app-with-flask</id><content type="html" xml:base="https://arturojc.dev/flask/2021/10/21/making-my-first-web-app-with-flask.html"><![CDATA[<p>I just completed my first web application using Flask, so I thought it would be a good idea to write down some reflections on my experience while the project is still fresh in my mind.</p>

<p>My goal for the app was to have the user create a template, set some parameters such as starting date and starting weights, then have the app automatically generate a workout program based on the values entered by the user. Figuring how to generate the program and enter it into the database took some trial and error, but things went more or less smoothly. The real challenge was figuring out how to display the program.</p>

<p>The way my application works, each program object has a number of child workout objects. In turn, each workout object has date and week attributes as well as a number of child exercise objects.</p>

<p>The desired functionality was to have the user select a program and a week, and display all matching workouts along with their corresponding exercises in a table, each column representing a different day of the week.</p>

<p>But how do you build such a table using Jinja (Flask’s templating language)? My first instinct was to build the table column by column. So, starting with the Monday column, I wanted to loop through the Monday workouts, and for each workout, create one cell for the workout’s name and one for each of its exercises, each cell sitting on top of the next. I wanted to create all these cells in the Monday column before moving on to the next column.</p>

<p>It turns out you cannot do this. In HTML, you cannot build a table column by column–you can only build it row by row. This is because you need to close each tag before you open the next. This meant that for each row, I had to create all cells within that row before moving on to the next.</p>

<p>So then I tried looping through all the workouts for the week, creating one row for each workout and one for each of its exercises. Inside each row, I created seven cells (corresponding to the seven days of the week) before closing the tag. If there was a workout scheduled for the corresponding day, the cell displayed the workout’s name or one of its exercises–otherwise the cell was blank.</p>

<p>This method works, but it results in a lot of wasted space. Suppose your program has only one workout on Monday and one workout on Tuesday–call them A and B. You would expect A and B to sit at the same level in the table. But that’s not what you get with this method. Instead, each workout get its own “level”–that is, each workout gets its own set of rows. So, you get one set of rows displaying A on Monday but nothing on Tuesday, and another set of rows below displaying B on Tuesday but nothing on Monday. That’s no good.</p>

<p>To get around these problems, I tried writing some convoluted Jinja code inside the HTML template before ultimately settling on a different kind of solution. The solution was to organize workouts into structures I called “layers” before passing them to the template. This approach is too convoluted to describe in any real detail here, but you can take a look at the solution if you search for “TABLE DATA” <a href="https://github.com/arturo-jc/musqlo/blob/master/main.py">here</a>.</p>

<p>So, what lessons can we draw from all this? I would say the main lesson is this. Even though you can use Jinja to write some logic inside the HTML template, you should really keep that to a minimum. Instead, you should stick all the logic inside your Flask application, and pass all the required data to the template in a format that makes it easy to work with inside the template.</p>

<p>This is something I first heard about in Angela Yu’s Python Udemy course, but doing this project really drove the point home.</p>]]></content><author><name>Arturo Javier-Castellanos</name></author><category term="flask" /><summary type="html"><![CDATA[I just completed my first web application using Flask, so I thought it would be a good idea to write down some reflections on my experience while the project is still fresh in my mind...]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://arturojc.dev/assets/share-card.png" /><media:content medium="image" url="https://arturojc.dev/assets/share-card.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry></feed>