<?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"><channel><title><![CDATA[Piyush's Blog]]></title><description><![CDATA[Piyush's Blog]]></description><link>https://blog.pycz.dev</link><generator>RSS for Node</generator><lastBuildDate>Sun, 08 Nov 2026 01:44:45 GMT</lastBuildDate><atom:link href="https://blog.pycz.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[DevJournal: converting my Astro website for custom link slugs - Astro(SSR), Vercel, PlanetScale, DrizzleORM]]></title><description><![CDATA[in easy words, a link shortner]]></description><link>https://blog.pycz.dev/devjournal-converting-my-astro-website-for-custom-link-slugs-astrossr-vercel-planetscale-drizzleorm</link><guid isPermaLink="true">https://blog.pycz.dev/devjournal-converting-my-astro-website-for-custom-link-slugs-astrossr-vercel-planetscale-drizzleorm</guid><category><![CDATA[Astro]]></category><category><![CDATA[Vercel]]></category><category><![CDATA[PlanetScale]]></category><category><![CDATA[Preact]]></category><category><![CDATA[DrizzleORM]]></category><dc:creator><![CDATA[Piyush]]></dc:creator><pubDate>Thu, 30 Mar 2023 13:02:46 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1680092492054/abb88ba7-0cd4-494a-b20f-bccb2ae831f1.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hey fellas o/. In this blog, we are going to tinker around with a new stack, something I wanted to try for quite some time. A few months ago, I created a new home for myself on the internet <em>(yet again)</em> - <a target="_blank" href="https://pycz.dev">pycz.dev</a>. It's been a long time, but I still obsess over getting a new website, and spin up a raw project with all the hyped things in the market, and take it to a drive. For this website, it was <a target="_blank" href="https://astro.build/">Astro</a>. I was surprised how simple it was to scaffold and ship a project so fast, plus the DX is <em>chef's kiss</em>.</p>
<p>The <mark>source code</mark> for this blog is available on Github: <a target="_blank" href="https://github.com/officialpiyush/pycz.dev">https://github.com/officialpiyush/pycz.dev</a></p>
<p>When I made the website, I added some links which would redirect to my socials</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1680089819436/56ff4f5d-9297-41d7-a7d0-e2e2d9babe5b.png" alt class="image--center mx-auto" /></p>
<p>I could've just embedded direct links to my socials, but I felt having pycz.dev/twitter would be more cool~. For this, I used Vercel redirect rules, which run on the edge</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1680090065566/f03c71fc-ab17-4b61-bdd2-91d4dce2ccb8.png" alt="vercel.json configuration showing redirect rules for routes" class="image--center mx-auto" /></p>
<p>This is how the redirect rules looked. Yeah, some sneaky regex for the GitHub redirects.</p>
<h1 id="heading-the-idea">💡 The idea</h1>
<p>Everything was cool till recently, I wanted to share a few links, and thought it would be easy if I could just dynamically update the links. This gave me the idea for creating a simple dynamic URL generation service. Taking it a step forward, I decided to integrate it with my existing Astro website.</p>
<h2 id="heading-the-stack">The Stack</h2>
<p>I made a <a target="_blank" href="https://twitter.com/PiyushCodez/status/1641023685950832641?s=20">tweet</a> about the project and the stack I'm using, so if you forgot to follow me there, why not do it now ;). As the title says, I am planning to use Astro (w/ SSR), PlanetScale for database, DrizzleORM for connecting to the database, and our good host Vercel for hosting it. I plan on making it run on the edge.</p>
<h1 id="heading-the-process">The Process</h1>
<p>I begin by creating a new branch for the features we are working on. I'll call it <code>custom-slugs</code>. After creating the branch, let's first enable SSR in Astro, it's easy, just set <code>output</code> option to <code>server</code>and voilà 🎉 we have now enabled SSR in Astro</p>
<p>Next, let's quickly head to PlanetScale and create a database instance.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1680093712043/0692024f-0fca-4df6-a425-c185c5bef909.png" alt class="image--center mx-auto" /></p>
<p>PlanetScale provides MySQL database, so for it, we have three options, either MySQL node driver, PlanetScale official driver, SQL ORM/ODM. I plan on hosting it on the edge, so the first option goes out of the scope. The second option looks like a good fit, but it executes direct queries, and won't be type-safe, so we move on to the third option, ORM/ODM. There are plenty in the market for SQL, like Prisma ORM, Knex QB, etc.</p>
<p>However, Prisma takes a lot of time to start, and is slow with joins, so, we're going to try DrizzleORM, which is pretty awesome in my opinion, because it provides better speed over Prisma, but can also integrate with the official PlanetScale driver.</p>
<h2 id="heading-setting-up-the-database">Setting up the database</h2>
<p>For this, let's create a new branch from the <code>custom-slugs</code> branch, and name it <code>custom-slugs-database</code>. Now that we have moved to a new branch, let's quickly install the dependencies:</p>
<pre><code class="lang-bash">pnpm add drizzle-orm @planetscale/database dotenv 
pnpm add -D drizzle-kit @types/node
</code></pre>
<p>After this is installed, I quickly created the <code>links</code> table in Drizzle, it was as smooth as a breeze.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> links = mysqlTable(
  <span class="hljs-string">"links"</span>,
  {
    id: text(<span class="hljs-string">"id"</span>).primaryKey().default(nanoid()),
    key: text(<span class="hljs-string">"key"</span>),
    parent: text(<span class="hljs-string">"parent"</span>),
    description: text(<span class="hljs-string">"description"</span>),
    url: text(<span class="hljs-string">"url"</span>),
    createdAt: timestamp(<span class="hljs-string">"created_at"</span>, { fsp: <span class="hljs-number">2</span> }).notNull().defaultNow(),
    enabled: <span class="hljs-built_in">boolean</span>(<span class="hljs-string">"enabled"</span>).default(<span class="hljs-literal">true</span>),
  },
  <span class="hljs-function">(<span class="hljs-params">links</span>) =&gt;</span> ({
    keyIndex: uniqueIndex(<span class="hljs-string">"key_idx"</span>).on(links.key),
  })
);
</code></pre>
<p>After this, I quickly created a PR from the current branch to the <code>custom-slugs</code> branch - <a target="_blank" href="https://github.com/officialpiyush/pycz.dev/pull/4">https://github.com/officialpiyush/pycz.dev/pull/4</a></p>
<h2 id="heading-debugging-cd-errors">Debugging CD errors</h2>
<p>After I had merged the PR, I had to set up a deployment adapter, which basically means that we are telling Astro that you would be deployed on this platform, build yourself accordingly. But, after setting up the vercel edge runtime adapter, the build was still continuously failing, and ESBuild prompted me to use <code>platform='node'</code>on every build. It was confusing because I was not using, nor doing anything which was dependent on the node runtime, everything was supposed to be edge safe.</p>
<p>After a lot of debugging, I came across the root issue, it was not a direct dependency, but rather an indirect dependency of <code>astro-icon</code> package which was causing the build to fail. Fortunately, I was using pnpm, so I was able to quickly patch and commit the package locally to remove the underlying code which was causing the issue. It can be found in this commit - <a target="_blank" href="https://github.com/officialpiyush/pycz.dev/pull/5/commits/96017e19d61d452291be063124561b9ca2496fc4">https://github.com/officialpiyush/pycz.dev/pull/5/commits/96017e19d61d452291be063124561b9ca2496fc4</a></p>
<h2 id="heading-setting-up-the-api">Setting up the API</h2>
<p>This section is going to be quick. I am not going to add any hi-fi authentication mechanism, just a small token based authentication to protect the route, because it would just be me using the dashboard.</p>
<p>Moving forward, I'll now create another git branch with <code>custom-slugs</code> as the base branch, and this time I will name it <code>custom-slugs-api</code>. After this, I'm installing the required packages, and setting up the API structure. Here is the PR for API - <a target="_blank" href="https://github.com/officialpiyush/pycz.dev/pull/6">https://github.com/officialpiyush/pycz.dev/pull/6</a></p>
<h2 id="heading-merging-it-all-together">Merging it all together</h2>
<p>After merging the PR, I had to sync my schema with the database, for this, I searched a lot, but there was no direct way of doing it in Drizzle like there was in Prisma. I asked about it, and Andrew from the Drizzle team told that the feature was there, but it was in an internal testing phase. I then switched my <code>drizzle-kit</code> version to the version he mentioned, and voilà, it was done!</p>
<h2 id="heading-making-the-ui-to-create-links">Making the UI to create links</h2>
<p>After the API, I now have to make a dashboard to manage the links, so let's move forward and do that. I won't be creating another branch for it.</p>
<p>While I was creating the UI, I came across a roadblock, how to manage state and call our router. I tried same path POST request, but couldn't get it to work. Fortunately, Astro has framework adapters, and we would be using Preact for our dashboard UI.</p>
<p>After going back and forth, I created a dead simple UI for the dashboard.</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>Overall, it was a smooth experience working with these tools. I think I would start using them in my upcoming projects, because of how powerful they are, but also because of how easy they were to set up. I'm also excited to see how DrizzleORM matures.</p>
<h2 id="heading-source-code">Source Code</h2>
<p>The source code for this blog is available on Github: <a target="_blank" href="https://github.com/officialpiyush/pycz.dev">https://github.com/officialpiyush/pycz.dev</a> and the PR can be found here - <a target="_blank" href="https://github.com/officialpiyush/pycz.dev/pull/5">https://github.com/officialpiyush/pycz.dev/pull/5</a></p>
<p>Connect with me on <a target="_blank" href="https://www.linkedin.com/in/piyushbhangale/">Linkedin</a> and <a target="_blank" href="https://twitter.com/PiyushCodez">Twitter</a>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1674121667388/eab6cff7-7759-48e2-8822-45485f0100a2.jpeg?auto=compress,format&amp;format=webp" alt class="image--center mx-auto" /></p>
]]></content:encoded></item><item><title><![CDATA[DevJournal: DiscordDrive - Proof of Concept: store data on discord]]></title><description><![CDATA[I am currently pursuing my undergrad degree in computer engineering. Being a student, I have lots of data to store, courses, reference materials, etc. I…]]></description><link>https://blog.pycz.dev/devjournal-discorddrive-proof-of-concept-store-data-on-discord</link><guid isPermaLink="true">https://blog.pycz.dev/devjournal-discorddrive-proof-of-concept-store-data-on-discord</guid><category><![CDATA[discord]]></category><category><![CDATA[Rust]]></category><category><![CDATA[rust lang]]></category><category><![CDATA[storage]]></category><category><![CDATA[command line]]></category><dc:creator><![CDATA[Piyush]]></dc:creator><pubDate>Thu, 19 Jan 2023 17:08:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1674114963554/e4020443-a150-4c7c-bc7c-35fc3f0da341.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I am currently pursuing my undergrad degree in computer engineering. Being a student, I have lots of data to store, courses, reference materials, etc. I used to use uni's Google Drive for storage, but google recently capped the storage. So, it made me wonder where I could store all of my data. I tried telegram because of its file limit, but it was too slow. I used to store small files, which I frequently used to share on Discord, mainly because it provided unrestricted access to people having the link. Discord had and still has a very reliable storage architecture and network. It is a good choice for me to store the files, but with only one limitation, we can only upload 8 MB files without nitro.</p>
<p>What if I split the files into small chunks of ~8 MB each, and then upload them? Downloading them would be easy, just a synchronous fetch stream on the list of buffers, served (and cached) through serverless functions. Although this sounds pretty easy, there are a lot of factors to consider, machine's uploading capacity to handle big files, rate limits imposed, serverless rate limits on the free plan, and much more that would come along the way in developing the application/service. I think this would be fun and a great learning experience, so why not try it out ;)</p>
<p><img src="https://media.tenor.com/I5SAEpMQJtQAAAAC/cute-baby.gif" alt class="image--center mx-auto" /></p>
<p>I was thinking of Node.js for the tech stack, mainly because I could use the <a target="_blank" href="https://nodejs.org/api/stream.html#class-streamtransform">stream. Transform</a> class to convert the file into chunks, but then there could be cases where I could run out of memory. This could be a problem, however, there could be ways in which I could handle this, I thought of using rust for it. Why? Simply because I wanted to work on a project in Rust for so long. The last “real” project I had in Rust was in 2021, Mayuzumi, I worked on it for almost 6 months, then the project was dropped. I enjoyed using Rust for that project. So now that I decided what language to use, now I had to decide what crates should I use. The requirements were simple:</p>
<ul>
<li><p>should split the files into chunks</p>
</li>
<li><p>should not run out of memory</p>
</li>
<li><p>should upload them to discord</p>
</li>
<li><p>while uploading, it should not block other processes</p>
</li>
</ul>
<p>The last point is important because imagine you have a compressed file of about 1 GB, and after the chunking, you would have roughly 125 files, which would be needed to upload to discord. Assuming it would take almost a minute to upload them to discord, the whole process would take around 125 minutes, or roughly 2 hours, just to upload a single GB. To tackle this, we would leverage the threading mechanism. With this initial idea and requirements in mind, I started looking for libraries. One of the main requirements, should not run out of memory was a bit tricky, but after some digging, I was able to find <code>StreamingIterator</code> crate, which would help me avoid using the memory most of the time, as, theoretically, we could modify it to directly stream chunks from the file system itself. I gathered some more libraries' <a target="_blank" href="https://crates.io/crates/rayon">Rayon</a>, <a target="_blank" href="https://crates.io/crates/serenity">Serenity</a>. These are not the “only” libraries we need, but I think these are enough to start with the MVP. At this point, I just had the libraries which I would use, but didn't try any of them.</p>
<p><strong>17 Jan '23</strong> - As I said, I didn't try any of the libraries, but while implementing it, it turns out that it may end up taking more memory than the inbuilt <code>BufReader</code>. So, I resolved to <code>BufReader</code> to read data chunk by chunk, each chunk being 7 MB. And for the uploading part, I chose <code>tokio</code> because it would be an upload operation, for which <code>tokio</code> is more suited than <code>rayon</code>.</p>
<h1 id="heading-storing-the-data">Storing the Data</h1>
<p>Here is the initial code I wrote to test the file chunking logic.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> futures::future::join_all;
<span class="hljs-keyword">use</span> std::{
    fs::File,
    sync::Arc,
    io::{BufReader, Read}
};
<span class="hljs-keyword">use</span> tokio::{sync::Semaphore, time};

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">chunk_file</span></span>() {
    <span class="hljs-comment">// semaphore to allow 24 concurrent upload </span>
    <span class="hljs-comment">// to avoid ratelimit</span>
    <span class="hljs-keyword">let</span> semaphore = Arc::new(Semaphore::new(<span class="hljs-number">24</span>));

    <span class="hljs-comment">// open the file, for testing, rq.rar file was ~2GB</span>
    <span class="hljs-keyword">let</span> file = File::open(<span class="hljs-string">"trial/rq.rar"</span>).unwrap();
    <span class="hljs-comment">// use BufReader to add buffering to the file</span>
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> reader = BufReader::new(file);
    <span class="hljs-comment">// initialize this to the size of the chunk we want to generate</span>
    <span class="hljs-keyword">let</span> buffer_size = <span class="hljs-number">7</span> * <span class="hljs-number">1024</span> * <span class="hljs-number">1024</span>; <span class="hljs-comment">// 7MB buffer</span>
    <span class="hljs-comment">// create a mutable vector with (7 * 1024 * 1024) 0s</span>
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> buffer = <span class="hljs-built_in">vec!</span>[<span class="hljs-number">0</span>; buffer_size];
    <span class="hljs-comment">// initialize mut index</span>
    <span class="hljs-comment">// it would be used to identify the chunks while joining</span>
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> i = <span class="hljs-number">0</span>;
    <span class="hljs-comment">// an vector to store all the future tasks </span>
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> handles = <span class="hljs-built_in">vec!</span>[];

    <span class="hljs-comment">// iterate infinitely</span>
    <span class="hljs-keyword">loop</span> {
        <span class="hljs-comment">// read the file data into our buffer</span>
        <span class="hljs-comment">// reads only 7MB at a time</span>
        <span class="hljs-keyword">let</span> bytes_read = reader.read(&amp;<span class="hljs-keyword">mut</span> buffer).unwrap();
        <span class="hljs-comment">// break the loop if no bytes are left to read</span>
        <span class="hljs-keyword">if</span> bytes_read == <span class="hljs-number">0</span> {
            <span class="hljs-keyword">break</span>;
        }
        <span class="hljs-comment">// take a slice of the data we read</span>
        <span class="hljs-comment">// converts it to a Vector&lt;u8&gt;</span>
        <span class="hljs-comment">// because in the last iteration the data might be smaller</span>
        <span class="hljs-comment">// it may be 2.3MB instead of 7MB</span>
        <span class="hljs-comment">// that case is handled</span>
        <span class="hljs-keyword">let</span> data = (&amp;buffer[..bytes_read]).to_vec();
        <span class="hljs-comment">// spawn a background process to upload the chunk to discord</span>
        <span class="hljs-comment">// runs concurrently (in parallel)</span>
        <span class="hljs-comment">// assign handle to it</span>
        <span class="hljs-keyword">let</span> handle = tokio::spawn(<span class="hljs-keyword">async</span> <span class="hljs-keyword">move</span> {
            <span class="hljs-comment">// try to acquire a semaphore lock</span>
            <span class="hljs-comment">// if none exists, wait for earlier tasks to finish</span>
            <span class="hljs-keyword">let</span> _permit = semaphore_handle.acquire().<span class="hljs-keyword">await</span>.unwrap();
            <span class="hljs-comment">// after getting a permit, upload to discord</span>
            upload_chunk(i, data).<span class="hljs-keyword">await</span>;
            <span class="hljs-comment">// upload complete, we drop the permit</span>
            <span class="hljs-comment">// next chunk in the queue can now start</span>
            <span class="hljs-built_in">drop</span>(_permit);
        });
        <span class="hljs-comment">// push that handle to our futures group</span>
        handles.push(handle);
        <span class="hljs-comment">// increment the index</span>
        i += <span class="hljs-number">1</span>;
    }

    <span class="hljs-comment">// wait for all the futures to be completed</span>
    join_all(handles).<span class="hljs-keyword">await</span>;
}
</code></pre>
<p>Takes ~1 second to split a 2 GB file into 293 chunks of 7 MB each. Assuming 24 concurrent tasks don't hit the rate limit, and it takes around 30 seconds to upload 7 MB, we can upload 2 GB of data in around ~6 minutes. But it's highly likely that we could hit the rate limit, so the only way to know it is by actually trying it. We also have not considered the internet upload speed here, which may also be a crucial factor while estimating the total time to upload the file.</p>
<p>So, now we move to the upload part. For this, I first initialized all webhooks using the serenity library concurrently. Since <code>Http</code> from serenity doesn't implement <code>Clone</code>, I had to wrap it in <code>Arc</code>.</p>
<pre><code class="lang-rust"><span class="hljs-meta">#[tokio::main]</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
  <span class="hljs-comment">// ...</span>
  <span class="hljs-comment">// ... initialization code</span>

  <span class="hljs-comment">// create an vector to store the webhooks</span>
  <span class="hljs-keyword">let</span> webhooks = Arc::new(Mutex::new(<span class="hljs-built_in">vec!</span>[]));
  <span class="hljs-comment">// wrap the http new into an arc</span>
  <span class="hljs-comment">// we can now clone it and access it concurrently</span>
  <span class="hljs-keyword">let</span> http = Arc::new(Http::new(<span class="hljs-string">""</span>));
  <span class="hljs-comment">// an vector to store futures</span>
  <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> webhook_handles = <span class="hljs-built_in">vec!</span>[];

  <span class="hljs-comment">// iterate over the webhook URLs</span>
  <span class="hljs-keyword">for</span> webhook <span class="hljs-keyword">in</span> cfg.webhooks {
      <span class="hljs-comment">// clone to access them from spawned tasks</span>
      <span class="hljs-keyword">let</span> http = http.clone();
      <span class="hljs-keyword">let</span> webhook_clone = webhooks.clone();
      <span class="hljs-comment">// spawm tasks to initialize the webhooks</span>
      <span class="hljs-keyword">let</span> handle = tokio::spawn(<span class="hljs-keyword">async</span> <span class="hljs-keyword">move</span> {
          <span class="hljs-keyword">let</span> webhook = Webhook::from_url(http.as_ref(), &amp;webhook)
              .<span class="hljs-keyword">await</span>
              .expect(&amp;<span class="hljs-built_in">format!</span>(<span class="hljs-string">"Failed to get webhook from url: {}"</span>, webhook));
          <span class="hljs-comment">// access the webhook vector</span>
          <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> webhook_vec = webhook_clone.lock().unwrap();
          <span class="hljs-comment">// push the created webhook</span>
          webhook_vec.push(webhook);
      });
      <span class="hljs-comment">// push it to the future vector</span>
      webhook_handles.push(handle);
  }

  <span class="hljs-comment">// wait for all the futures to be over</span>
  join_all(webhook_handles).<span class="hljs-keyword">await</span>;
}
</code></pre>
<p>Now that all the webhooks have been initialized, I have to pass them to my chunk_files function, so that the chunked files can be uploaded. For this, I had two options, pass the instance of <code>Http</code> and each <code>Webhook</code> as it is, or create a struct to send them. The first one is an easy option, and the most sensible one, but I went with the second option, which is to create a struct to combine <code>Http</code> and <code>Webhook</code>, and pass it. The <code>WebhookData</code> struct would need to implement <code>Clone</code> as it is a custom structure, which would be needed to clone while using it concurrently. This is how it would look.</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">WebhookData</span></span> {
    http: Arc&lt;Http&gt;,
    webhook: Webhook,
}

<span class="hljs-keyword">impl</span> <span class="hljs-built_in">Clone</span> <span class="hljs-keyword">for</span> WebhookData {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">clone</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-keyword">Self</span> {
        WebhookData {
            http: <span class="hljs-keyword">self</span>.http.clone(),
            webhook: <span class="hljs-keyword">self</span>.webhook.clone(),
        }
    }
}
</code></pre>
<p>Now that we have our struct, we need to change some of our code to support the passing of the data.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> webhooks: Arc&lt;Mutex&lt;<span class="hljs-built_in">Vec</span>&lt;WebhookData&gt;&gt;&gt; = Arc::new(Mutex::new(<span class="hljs-built_in">vec!</span>[]));

<span class="hljs-keyword">let</span> http = Arc::new(Http::new(<span class="hljs-string">""</span>));
<span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> webhook_handles = <span class="hljs-built_in">vec!</span>[];

<span class="hljs-keyword">for</span> webhook <span class="hljs-keyword">in</span> cfg.webhooks {
    <span class="hljs-keyword">let</span> http = http.clone();
    <span class="hljs-keyword">let</span> webhook_clone = webhooks.clone();
    <span class="hljs-keyword">let</span> handle = tokio::spawn(<span class="hljs-keyword">async</span> <span class="hljs-keyword">move</span> {
        <span class="hljs-keyword">let</span> webhook = Webhook::from_url(http.as_ref(), &amp;webhook)
            .<span class="hljs-keyword">await</span>
            .expect(&amp;<span class="hljs-built_in">format!</span>(<span class="hljs-string">"Failed to get webhook from url: {}"</span>, webhook));
        <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> webhook_vec = webhook_clone.lock().unwrap();
        webhook_vec.push({
            WebhookData {
                http: http.clone(),
                webhook: webhook.clone(),
            }
        });
    });
    webhook_handles.push(handle);
}

join_all(webhook_handles).<span class="hljs-keyword">await</span>;
</code></pre>
<p>I ran the code, and it took <code>558.476888248</code> seconds, which is approximately 9 minutes. It's a lot for a 2 GB file, but it uploaded ~295 chunks of files, all that while respecting the rate limits of discord. The average upload speed I could get was ~6.5 MiB/s.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1673968797474/378213ae-3af0-4ba6-8e4e-aa14829da109.png" alt class="image--center mx-auto" /></p>
<p>Now, let's experiment, all the rate limits are handled by the <code>Http</code> handler we declared, but what if we declared two <code>Http</code> handlers instead of one. This may or may not work, as <code>serenity</code> handles rate limits based on the response headers of the webhooks, but trying doesn't hurt, does it?</p>
<p><img src="https://media.tenor.com/l37il_hI3tEAAAAC/smilecat.gif" alt class="image--center mx-auto" /></p>
<p>So, now we assign all odd index <code>Http</code> handler <code>http_one</code>, and the even index <code>Http</code> handler <code>http_two</code>. So, now our code becomes something like this.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> http_one = Arc::new(Http::new(<span class="hljs-string">""</span>));
<span class="hljs-keyword">let</span> http_two = Arc::new(Http::new(<span class="hljs-string">""</span>));

<span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> webhook_handles = <span class="hljs-built_in">vec!</span>[];

<span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> webhook_index = <span class="hljs-number">1</span>;
<span class="hljs-keyword">for</span> webhook <span class="hljs-keyword">in</span> cfg.webhooks {
    <span class="hljs-keyword">let</span> http = <span class="hljs-keyword">if</span> webhook_index % <span class="hljs-number">2</span> != <span class="hljs-number">0</span> {
        http_one.clone()
    } <span class="hljs-keyword">else</span> {
        http_two.clone()
    };

    <span class="hljs-keyword">let</span> webhook_clone = webhooks.clone();
    <span class="hljs-keyword">let</span> handle = tokio::spawn(<span class="hljs-keyword">async</span> <span class="hljs-keyword">move</span> {
        <span class="hljs-keyword">let</span> webhook = Webhook::from_url(http.as_ref(), &amp;webhook)
            .<span class="hljs-keyword">await</span>
            .expect(&amp;<span class="hljs-built_in">format!</span>(<span class="hljs-string">"Failed to get webhook from url: {}"</span>, webhook));
        <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> webhook_vec = webhook_clone.lock().unwrap();
        webhook_vec.push({
            WebhookData {
                http: http.clone(),
                webhook: webhook.clone(),
            }
        });
    });
    webhook_handles.push(handle);
    webhook_index += <span class="hljs-number">1</span>;
}

join_all(webhook_handles).<span class="hljs-keyword">await</span>;
</code></pre>
<p>But, as expected this did not work, it still took <code>556.185072046</code> seconds to upload the same file, which estimates to be around ~9 minutes, so not much of a difference. Kudos to the authors of <code>serenity</code> though, they have implemented rate limit handling in such a neat way.</p>
<p>So we now got chunked file upload feature sorted, now there are two more main features left, storing the links in the database-so that it is possible to retrieve the chunks from discord and merge them into a single file, and the other feature being is to download the chunks from discord and merge them into a single file with the order of data from the database. I'm calling it a day now, I have spent more than 7 hours coding on this project today.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1673969374999/445dcce8-3354-40ac-bb55-86b59b99a134.png" alt class="image--center mx-auto" /></p>
<p><strong>18 January '23</strong> - Today, I have to figure out which database to choose, implement the code to download, and merge all the chunks into a single file.</p>
<h1 id="heading-database">Database</h1>
<p>So, for the database, I decided to go with Google's <code>Firestore</code>, because I also have plans to convert this into a multi-device application. <code>Firestore</code> would fit all my needs. Fortunately, there is a library <code>firestore</code> which is being actively maintained, with its latest version released 3 days ago. So, I went ahead and created a new Firebase project.</p>
<p><img src="https://i.imgur.com/EkrUwMp.gif" alt class="image--center mx-auto" /></p>
<p>Now, we have the firestore database ready, we create a service account, because we would need a token to connect to our firestore database. Now, we have to configure the rules, I am thinking of adding an auth_token field in all data sent, not the best possible way to do it, but <em>meh</em></p>
<pre><code class="lang-rust">rules_version = <span class="hljs-string">'2'</span>;
service cloud.firestore {
  <span class="hljs-keyword">match</span> /databases/{database}/documents {
    <span class="hljs-keyword">match</span> /{document=**} {
      allow read, write: <span class="hljs-keyword">if</span> request.resource.data[<span class="hljs-string">"auth_token"</span>] == <span class="hljs-string">"your_unique_auth_token"</span>;
    }
  }
}
</code></pre>
<p>Now, let's grab our service account file.</p>
<p><img src="https://i.imgur.com/QiLlsAd.gif" alt class="image--center mx-auto" /></p>
<p>Now, that we have firestore setup, let's install the <code>firestore</code> dependency into our project. After installing it, we need to configure it to use our service account. This is going to be tricky, as there is no documentation on how to use it with a service account, it expects the settings to be in the GKE environment, however, it is possible to use a service account, but the builds of the underlying library <code>gcloud-sdk</code>, are continuously failing. The documentation mentions that we could set an environment variable, but I believe that it may coincide with any developer environment the user may configure. So, we have to go through the source code to find out. Created an <a target="_blank" href="https://github.com/abdolence/gcloud-sdk-rs/issues/54">issue</a> for the documentation bit, so we wait till we get any updates.</p>
<p>Fortunately, the author was quick, and it was clear that there was no other option, but to set the environment variable. We would use the <a target="_blank" href="https://doc.rust-lang.org/std/env/fn.set_var.html"><code>set_var</code></a> to set the path of the config file. I have not coded much today, so let's get into it!</p>
<pre><code class="lang-rust"><span class="hljs-comment">// set the environment variable for the process</span>
set_var(
    <span class="hljs-string">"GOOGLE_APPLICATION_CREDENTIALS"</span>,
    cfg.service_account_file_location,
);

<span class="hljs-comment">// create an firestore instance </span>
<span class="hljs-keyword">let</span> db = FirestoreDb::new(<span class="hljs-string">"discord-ddrive"</span>).<span class="hljs-keyword">await</span>.unwrap();
</code></pre>
<p>With much effort, I configured it to store data in firestore. Much of it is not documented here, because of the time limitations I had today, I wanted to complete both, storing into the database and retrieving today, but only ended up storing them in the database.</p>
<p>Here is what I did today in brief, I created a separate function called <code>add_to_database</code>, which stores the data in our firestore database. It appends every chunk's metadata to a field - <code>parts</code> in the document, which is an array. When retrieving, I would use this array to download the chunks and merge them in order. This is somewhat the backbone of the whole "after-upload" thingy.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">add_to_database</span></span>(db: FirestoreDb, name: <span class="hljs-built_in">String</span>, part: <span class="hljs-built_in">i32</span>, attachment_url: <span class="hljs-built_in">String</span>) {
    <span class="hljs-keyword">let</span> master_directory_child: MasterDirectoryChildPart = MasterDirectoryChildPart {
        name: name.clone(),
        id: <span class="hljs-built_in">format!</span>(<span class="hljs-string">"{}.part{}"</span>, &amp;name, part),
        part: part,
        parent: name,
        url: attachment_url,
    };

    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> transaction = db.begin_transaction().<span class="hljs-keyword">await</span>.unwrap();

    <span class="hljs-keyword">let</span> _added = db
        .fluent()
        .update()
        .fields(paths!(MasterDirectoryChild::parts))
        .in_col(MASTER_DIRECTORY_COLLECTION_NAME)
        .document_id(&amp;master_directory_child.name)
        .transforms(|transform_builder| {
            <span class="hljs-built_in">vec!</span>[transform_builder
                .field(path!(MasterDirectoryChild::parts))
                .append_missing_elements([&amp;master_directory_child])
                .unwrap()]
        })
        .only_transform()
        .add_to_transaction(&amp;<span class="hljs-keyword">mut</span> transaction)
        .unwrap();

    transaction.commit().<span class="hljs-keyword">await</span>.unwrap();
}
</code></pre>
<p>This code adds the chunk data into <code>parts</code> - which is an array field.</p>
<p>Today was a not-so-productive day IMO, I only coded for over more than 2.5 hours today.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1674066331650/da1a84c9-fea7-4027-92d4-613124bf9f27.png" alt class="image--center mx-auto" /></p>
<p>Only 4 minutes left for the day to be over. Tomorrow I would focus on retrieving and merging the data into a single file as it was before.</p>
<p><strong>19 January '23</strong> - Today I have to work on merging the file back into one piece. So, the initial idea I have in mind is to first download all parts on disk for redundancy, and after all chunks have been downloaded, open the file in append mode, iterate over the chunks on disk, and then append the chunk to the main file, and delete the downloaded chunk file. This would avoid filling the memory.</p>
<h1 id="heading-retrieving-the-data">Retrieving the Data</h1>
<p>So, right now, the plan is to use <code>BufWriter</code> with a capacity of 1 GB. This would make sure that we don't have frequent disk operations for every 7 MB file, and data is flushed into the main file only after 1 GB of the buffer memory is filled. For this, we would need to download the files from discord, so I'll install the <code>reqwest</code> crate.</p>
<p>Now, I create a function <code>retrieve_and_save</code> to download chunks, and store them on disk. It gets the document from the database and then iterates over the <code>parts</code> field, spawns a <code>tokio</code> task to download the chunk using the <code>reqwest</code> crate, and then saves it to a file on disk. Now, we are using <code>tokio</code> to spawn the tasks, and <code>semaphores</code> to only allow 24 concurrent download tasks at once, we also have to make sure we do not block the execution of task using file operations. This may lead to poor performance and it may delay the execution of the next task. To solve this, we are going to use the non-blocking file module provided by <code>tokio</code> crate. This is how my function looks right now.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">retrieve_and_save</span></span>(db: FirestoreDb, name: &amp;<span class="hljs-built_in">str</span>) {
    <span class="hljs-keyword">let</span> semaphore = Arc::new(Semaphore::new(<span class="hljs-number">24</span>));

    <span class="hljs-keyword">let</span> master_directory: MasterDirectoryChild = db
        .fluent()
        .select()
        .by_id_in(MASTER_DIRECTORY_COLLECTION_NAME)
        .obj()
        .one(name)
        .<span class="hljs-keyword">await</span>
        .unwrap()
        .unwrap();

    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> part_ids_children = master_directory.parts.to_vec();
    part_ids_children.sort_by(|a, b| a.part.cmp(&amp;b.part));
    <span class="hljs-keyword">let</span> part_ids = part_ids_children
        .iter()
        .map(|part| part.id.clone())
        .collect::&lt;<span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">String</span>&gt;&gt;();

    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> handles = <span class="hljs-built_in">vec!</span>[];

    <span class="hljs-keyword">for</span> part <span class="hljs-keyword">in</span> master_directory.parts {
        <span class="hljs-keyword">let</span> semaphore = semaphore.clone();
        <span class="hljs-keyword">let</span> handle = tokio::spawn(<span class="hljs-keyword">async</span> <span class="hljs-keyword">move</span> {
            <span class="hljs-keyword">let</span> permit = semaphore.acquire().<span class="hljs-keyword">await</span>.unwrap();
            <span class="hljs-keyword">let</span> response = reqwest::get(&amp;part.url)
                .<span class="hljs-keyword">await</span>
                .unwrap()
                .bytes()
                .<span class="hljs-keyword">await</span>
                .unwrap();
            <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> file = tokio::fs::File::create(<span class="hljs-built_in">format!</span>(<span class="hljs-string">"chunks/{}"</span>, part.id))
                .<span class="hljs-keyword">await</span>
                .unwrap();

            file.write_all(&amp;response)
                .<span class="hljs-keyword">await</span>
                .expect(<span class="hljs-string">"Couldn't write to file"</span>);
            file.flush().<span class="hljs-keyword">await</span>.unwrap();
            <span class="hljs-built_in">drop</span>(permit);
            <span class="hljs-built_in">drop</span>(response);
        });
        handles.push(handle);
    }

    join_all(handles).<span class="hljs-keyword">await</span>;
}
</code></pre>
<p>the notable things here are <code>tokio::fs::File::create</code>, <code>file.write_all</code> and <code>flush</code> . It is what it looks like, first it creates the files, then it writes the response to the file, and then makes sure everything is flushed down in the file before continuing.</p>
<p>Now, we have to move ahead and merge all of them into one. This one is really easy, just use <code>BufWriter</code> to create an in-memory buffer of some capacity, I am thinking of 500MB. It would then open the chunk file and then use the <code>std::io::copy</code> function to copy the data from <code>reader</code> to <code>writer</code>. The maximum amount of data that will be held in memory at any given time is the buffer size that we set, which is 500MB. After merging, it deletes the chunk file, so that we don't hog the disk space.</p>
<p>Here is how I implemented it.</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">merge_files</span></span>(files: <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">String</span>&gt;, name: &amp;<span class="hljs-built_in">str</span>) {
    <span class="hljs-keyword">let</span> output_file = File::create(name).unwrap();
    <span class="hljs-comment">// 500MB capacity</span>
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> writer = BufWriter::with_capacity(<span class="hljs-number">1024</span> * <span class="hljs-number">512</span> * <span class="hljs-number">500</span>,output_file);

    <span class="hljs-keyword">for</span> file <span class="hljs-keyword">in</span> files {
        <span class="hljs-keyword">let</span> input_file = File::open(<span class="hljs-built_in">format!</span>(<span class="hljs-string">"chunks/{}"</span>, file)).unwrap();
        <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> reader = BufReader::new(input_file);

        <span class="hljs-comment">// Copy the contents of the input file to the output file</span>
        std::io::copy(&amp;<span class="hljs-keyword">mut</span> reader, &amp;<span class="hljs-keyword">mut</span> writer).unwrap();

        <span class="hljs-comment">// Delete the input file</span>
        std::fs::remove_file(<span class="hljs-built_in">format!</span>(<span class="hljs-string">"chunks/{}"</span>, file)).unwrap();
    }

    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Successfully Merged files!"</span>);
}
</code></pre>
<p>And yes, the file exists and I was able to successfully un-archive it</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1674119073977/47c7d38f-7532-4091-acc0-dd7268a4b3ae.png" alt class="image--center mx-auto" /></p>
<p>We did it \o/</p>
<p><img src="https://media.tenor.com/wto_9CjqJTcAAAAM/dance-cat.gif" alt class="image--center mx-auto" /></p>
<h1 id="heading-final-steps">Final Steps</h1>
<p>Now that our MVP is ready, let's clean up our codebase, and implement it in command line format!</p>
<h2 id="heading-creating-a-cli-application">Creating a CLI application</h2>
<p>I don't have any experience in creating CLI programs in rust, so I did a quick google search and found the awesome <a target="_blank" href="https://rust-cli.github.io/book/index.html">Rust CLI Book</a>. I gave it a quick read and started playing around. I played more, then I stumbled across <code>structopt</code>, it is a great library to parse command line arguments. I skimmed through the docs and created an initial parser.</p>
<p>This is how it looks:</p>
<pre><code class="lang-rust">
<span class="hljs-meta">#[derive(StructOpt, Debug)]</span>
<span class="hljs-meta">#[structopt(name = <span class="hljs-meta-string">"discord_drive"</span>)]</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Opts</span></span> {
    <span class="hljs-meta">#[structopt(subcommand)]</span>
    command: Command,
}

<span class="hljs-meta">#[derive(StructOpt, Debug)]</span>
<span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">Command</span></span> {
    <span class="hljs-meta">#[structopt(name = <span class="hljs-meta-string">"store"</span>)]</span>
    Store {
        <span class="hljs-meta">#[structopt(name = <span class="hljs-meta-string">"file"</span>, parse(from_os_str))]</span>
        file: std::path::PathBuf,
    },
    <span class="hljs-meta">#[structopt(name = <span class="hljs-meta-string">"retrieve"</span>)]</span>
    Retrieve {
        <span class="hljs-meta">#[structopt(name = <span class="hljs-meta-string">"word"</span>)]</span>
        word: <span class="hljs-built_in">String</span>,
    },
}

<span class="hljs-meta">#[tokio::main]</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> opts = Opts::from_args();

    <span class="hljs-keyword">let</span> start = Instant::now();
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Hello, world!"</span>);
    <span class="hljs-keyword">let</span> config_path = Path::new(<span class="hljs-string">"config/config.toml"</span>);
    <span class="hljs-keyword">let</span> cfg: DriveConfig = confy::load_path(config_path).unwrap();

    set_var(
        <span class="hljs-string">"GOOGLE_APPLICATION_CREDENTIALS"</span>,
        cfg.service_account_file_location,
    );

    <span class="hljs-keyword">let</span> db = FirestoreDb::new(<span class="hljs-string">"discord-ddrive"</span>).<span class="hljs-keyword">await</span>.unwrap();

    <span class="hljs-keyword">if</span> cfg.webhooks.len() &lt;= <span class="hljs-number">0</span> {
        <span class="hljs-built_in">panic!</span>(<span class="hljs-string">"No webhooks found in config file"</span>)
    }

    <span class="hljs-keyword">let</span> webhooks: Arc&lt;Mutex&lt;<span class="hljs-built_in">Vec</span>&lt;WebhookData&gt;&gt;&gt; = Arc::new(Mutex::new(<span class="hljs-built_in">vec!</span>[]));

    <span class="hljs-keyword">let</span> http_one = Arc::new(Http::new(<span class="hljs-string">""</span>));
    <span class="hljs-keyword">let</span> http_two = Arc::new(Http::new(<span class="hljs-string">""</span>));

    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> webhook_handles = <span class="hljs-built_in">vec!</span>[];

    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> webhook_index = <span class="hljs-number">1</span>;
    <span class="hljs-keyword">for</span> webhook <span class="hljs-keyword">in</span> cfg.webhooks {
        <span class="hljs-keyword">let</span> http = <span class="hljs-keyword">if</span> webhook_index % <span class="hljs-number">2</span> != <span class="hljs-number">0</span> {
            http_one.clone()
        } <span class="hljs-keyword">else</span> {
            http_two.clone()
        };

        <span class="hljs-keyword">let</span> webhook_clone = webhooks.clone();
        <span class="hljs-keyword">let</span> handle = tokio::spawn(<span class="hljs-keyword">async</span> <span class="hljs-keyword">move</span> {
            <span class="hljs-keyword">let</span> webhook = Webhook::from_url(http.as_ref(), &amp;webhook)
                .<span class="hljs-keyword">await</span>
                .expect(&amp;<span class="hljs-built_in">format!</span>(<span class="hljs-string">"Failed to get webhook from url: {}"</span>, webhook));
            <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> webhook_vec = webhook_clone.lock().unwrap();
            webhook_vec.push({
                WebhookData {
                    http: http.clone(),
                    webhook: webhook.clone(),
                }
            });
        });
        webhook_handles.push(handle);
        webhook_index += <span class="hljs-number">1</span>;
    }

    join_all(webhook_handles).<span class="hljs-keyword">await</span>;

    <span class="hljs-built_in">print!</span>(<span class="hljs-string">"Webhooks: {} "</span>, webhooks.lock().unwrap().len());

    <span class="hljs-keyword">let</span> webhooks_clone = webhooks.clone().lock().unwrap().to_vec();

    <span class="hljs-keyword">match</span> opts.command {
        Command::Store { file } =&gt; {
            <span class="hljs-comment">// check if file is a directory</span>
            <span class="hljs-keyword">if</span> file.is_dir() {
                eprintln!(<span class="hljs-string">"Error: {} is a directory"</span>, file.display());
                std::process::exit(<span class="hljs-number">1</span>);
            }

            <span class="hljs-comment">// store the file</span>
            <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Storing file: {}"</span>, file.display());
            chunk_file(file, webhooks_clone, db).<span class="hljs-keyword">await</span>;
        }
        Command::Retrieve { word } =&gt; {
            <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Retrieving word: {}"</span>, word);
            retrieve_and_save(db, <span class="hljs-string">"rq.rar"</span>).<span class="hljs-keyword">await</span>;
        }
    }

    <span class="hljs-keyword">let</span> duration = start.elapsed();
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Time taken: {:?}s"</span>, duration);
}
</code></pre>
<p>That's all!</p>
<h1 id="heading-future-scope">Future Scope</h1>
<p>This is an MVP, there are many things still left to do, but one of the main things is the organization. Professional Rustaceans might be annoyed because of the single file structure, but it would be sorted in future iterations :eyes:</p>
<p>There are a lot of features that would be implemented</p>
<ul>
<li><p>storing whole directories</p>
</li>
<li><p>able to view and download the data directly from the browser itself.</p>
</li>
<li><p>and many more...</p>
</li>
</ul>
<h2 id="heading-source-code">Source Code</h2>
<p>The source code for this blog is available on Github: <a target="_blank" href="https://github.com/officialpiyush/discord-drive">https://github.com/officialpiyush/discord-drive</a></p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>These three days were very interesting, I learned a lot, coded a lot, and experienced a lot of new unexplored stuff. I enjoyed creating this project. I think I would work more on this project, if I do, I would most probably write a Part 2 blog for it.</p>
<p>I spent almost 13 hours coding into this project</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1674125691476/25cc2711-5ef8-45bd-a3c3-6a928942ddcb.png" alt class="image--center mx-auto" /></p>
<p>Connect with me on <a target="_blank" href="https://www.linkedin.com/in/piyushbhangale/">Linkedin</a> and <a target="_blank" href="https://twitter.com/PiyushCodez">Twitter</a>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1674121667388/eab6cff7-7759-48e2-8822-45485f0100a2.jpeg" alt class="image--center mx-auto" /></p>
]]></content:encoded></item><item><title><![CDATA[Building Note App with NHost]]></title><description><![CDATA[Backend-as-a-Service - has been around for quite some time now. You must've heard about Google's Firebase or similar services, which allow you to focus on…]]></description><link>https://blog.pycz.dev/building-note-app-with-nhost</link><guid isPermaLink="true">https://blog.pycz.dev/building-note-app-with-nhost</guid><category><![CDATA[React]]></category><category><![CDATA[nhost]]></category><category><![CDATA[baas]]></category><dc:creator><![CDATA[Piyush]]></dc:creator><pubDate>Mon, 26 Dec 2022 18:01:07 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1670912085429/SWZtHXMqd.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-what-is-nhost">What is NHost?</h1>
<p>Backend-as-a-Service - has been around for quite some time now. You must've heard about Google's Firebase or similar services, which allow you to focus on developing your applications instead of worrying about the infrastructure. Among the small pool of providers, there is a relatively new player in the BaaS space - NHost.</p>
<h1 id="heading-why-nhost">Why NHost?</h1>
<p>NHost advertises itself as an open-source alternative to Firebase. Personally, I have been using Firebase for around 3–4 years now. Recently, I attended a session - BuildWith x NHost, a hands-on session by HackThisFall and NHost. Pratim took an awesome session, introducing us all to what NHost is. The session was quite intriguing since personally I enjoy exploring the backend, NHost really caught my interest.</p>
<p>The session started with how Nhost works, what it is and why should we check it out, since it was a hands-on workshop, we decided together to get started with Nhost by building something simple, as Pratim said "A note app is the Hello-World to web development". A note to myself when trying out something new ;)</p>
<p>One of the many things I found interesting about NHost is that it provides a GraphQL endpoint using Hasura to interact with the database it provides.</p>
<h1 id="heading-what-is-graphql">What is GraphQL?</h1>
<p>Some of you may have heard about GraphQL before, and some of you may have not - well it's worth giving a read. GraphQL is a specification, which follows a simple motto, you only get what you request.</p>
<p>To better understand this, let's take an example of a grocery shop. You go there and order an item, say Toothpaste. Now imagine if the shopkeeper gets you toothpaste, and along with it, some items like toothbrush, mouthwash, floss, toothpick, etc., most of which you do not need. This is how a typical REST API works.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1671100173249/3vp-554Zz.png" alt="The REST Cat" class="image--center mx-auto" /></p>
<p>Now, in the case of GraphQL, the shopkeeper would only get you the toothpaste, that is, the only thing you need.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1671100566797/I-0xgSR11.png" alt class="image--center mx-auto" /></p>
<h1 id="heading-lets-get-building">Let's get building!</h1>
<p>The stack would consist of:</p>
<ul>
<li><p>React</p>
</li>
<li><p>WindiCSS</p>
</li>
<li><p>NHost - for authentication and database</p>
</li>
</ul>
<p>The source code for this blog is available at <a target="_blank" href="https://github.com/officialpiyush/notes-app">https://github.com/officialpiyush/notes-app</a></p>
<p>To start, let's create a project on Nhost. Navigate to <a target="_blank" href="https://app.nhost.io/">https://app.nhost.io/</a> and click on the "New Project" button. Write in any name and select a region, click create, and we're good to go 🚀</p>
<p>There are some core files like the one in providers, it's better to leave it alone, but it's a great start if you want to mess around and break some stuff to understand what's going on under the hood.</p>
<p>Now, let's begin with the coding part.</p>
<h2 id="heading-authentication">Authentication</h2>
<p>Here is the thing I like about NHost client libraries, they come with some pre-defined hooks and components which help simplify the development process plus improves DX. For example, here we would be using the <code>&lt;SignedIn /&gt;</code> and <code>&lt;SignedOut /&gt;</code> helpers, which would help ease the authentication checking process. Let's start!</p>
<p>In our <code>src/pages/index.tsx</code> file, we import the components from the <code>@nhost/react</code> package.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { SignedIn, SignedOut } <span class="hljs-keyword">from</span> <span class="hljs-string">"@nhost/react"</span>;
<span class="hljs-keyword">import</span> SignIn <span class="hljs-keyword">from</span> <span class="hljs-string">"../components/SignIn"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">HomePage</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    &lt;div&gt;
      &lt;SignedIn&gt;
        &lt;div&gt;Welcome!&lt;/div&gt;
      &lt;/SignedIn&gt;
      &lt;SignedOut&gt;
        &lt;SignIn /&gt;
      &lt;/SignedOut&gt;
    &lt;/div&gt;
  );
}
</code></pre>
<p>This is how simple it is to check if a user is signed in or not! Isn't it great?</p>
<p>Now, if you're wondering, what would be the logic to log the user in, that is also very simple.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> { useSignInEmailPassword } <span class="hljs-keyword">from</span> <span class="hljs-string">"@nhost/react"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> YourFunction() {
  <span class="hljs-keyword">const</span> [email, setEmail] = useState(<span class="hljs-string">""</span>);
  <span class="hljs-keyword">const</span> [password, setPassword] = useState(<span class="hljs-string">""</span>);

  <span class="hljs-keyword">const</span> { signInEmailPassword, error } = useSignInEmailPassword();

  <span class="hljs-keyword">const</span> handleSubmit = <span class="hljs-keyword">async</span> () =&gt; {
    <span class="hljs-keyword">await</span> signInEmailPassword(email, password);
  };

  <span class="hljs-keyword">return</span> (
    <span class="hljs-comment">// HTML here</span>
  )
}
</code></pre>
<p>PS: HashNode doesn't support JSX/TSX highlighting, so there might be some formatting issues in the code block!</p>
<p>This is how simple it is. Now, to test the authentication, we would need to have a user, so, this is how we create a new user from the dashboard:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672058736126/b76cc41e-6664-44ed-88b1-fd96c103b3a2.gif" alt class="image--center mx-auto" /></p>
<p>Now, for this to work, we need to do one last thing, which is to disable "Required Verified Email" in the settings. This is how you do it:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672058920738/c5f8a698-3810-4524-9f3a-1ce13d814525.gif" alt class="image--center mx-auto" /></p>
<p>Log-in is done, but what if the user wants to log out now? Well, that is easy too! We just have to call the <code>&lt;nhostClient&gt;.auth.signOut()</code> to sign the user out. Now, to implement this, I created a Navbar, which has a button to sign out. If you want to sign out, you must be signed in, right? To solve the issue of checking whether the user is authenticated or not, the NHost client SDK also provides us with the <code>isAuthenticatedAsync()</code> function. You might ask why the <code>Async</code> function. The SDK happens to provide two functions, <code>isAuthenticated()</code>and <code>isAuthenticaedAsync()</code>. The only difference between them is that the <code>isAuthenticatedAysnc()</code> function will always return the true state of the user authentication status. Here is what the docs say about them</p>
<p><a target="_blank" href="https://docs.nhost.io/reference/react/auth/is-authenticated"><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672061594844/9157df93-8bd2-46bc-82de-20736e02852c.png" alt class="image--center mx-auto" /></a></p>
<p><a target="_blank" href="https://docs.nhost.io/reference/react/auth/is-authenticated-async"><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672061610351/77b14da6-0f1a-443d-aed2-a6659f8daf06.png" alt class="image--center mx-auto" /></a></p>
<p>Yay! The authentication process is done!</p>
<h2 id="heading-database">Database</h2>
<p>Now that our authentication part is done, we can now move on to think about how to store the data. For this, NHost provides a PostgreSQL database with 500 MB storage in their free tier. We are going to leverage this for our project.</p>
<p>Let's start by creating a table named <code>notes</code> having fields <code>id</code>, <code>created_at</code>, <code>updated_at</code>, <code>title</code> and <code>user_id</code>. This is how we do it:</p>
<p><img src="https://i.imgur.com/b912Owr.gif" alt class="image--center mx-auto" /></p>
<p>It may seem slow because of the low frame rate, but you'll get an idea of how to create the table. This is how the final table must look like: (don't worry about the foreign key thing, there is another screenshot about it below)</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672066326794/43f0c6db-8f71-4c0f-bc51-ccde9f2197fd.png" alt class="image--center mx-auto" /></p>
<p>This is how the foreign key section should be, <code>user_id</code> from the <code>notes</code> table references the <code>id</code> column from the <code>users</code> table:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672066272790/f2bc1e6f-d21e-4bc2-9e2f-1993cfbe51b4.png" alt class="image--center mx-auto" /></p>
<p>Click <code>Create</code>, and we're done!</p>
<h3 id="heading-hasura">Hasura</h3>
<p>If you're wondering what Hasura is, it is a tool that helps developers manage GraphQL servers. In short, it creates a GraphQL layer about your traditional database to be able to access it over the GraphQL Endpoint. NHost provides Hasura to connect and transact with our database! Let's get started then \o/</p>
<p><img src="https://i.imgur.com/DwqXfhJ.gif" alt class="image--center mx-auto" /></p>
<p>This is how you modify the permissions to allow an authenticated user to create an entry in the database over GraphQL. If the default value for user_id is hard to read in the GIF, here is what it is:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672071346716/cba26ed4-6e90-4eb1-a6bc-169c65e80bcd.png" alt class="image--center mx-auto" /></p>
<p>Now that we have the insert data permission set, let's work on the other permissions</p>
<p><img src="https://i.imgur.com/xS9Y4DY.gif" alt class="image--center mx-auto" /></p>
<p>And that's it for the permissions side! Let's get back to building our application. Here is a basic GraphQL query for the insert operation:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { gql } <span class="hljs-keyword">from</span> <span class="hljs-string">"urql"</span>;

<span class="hljs-keyword">const</span> INSERT_NOTE = gql<span class="hljs-string">`
  mutation insertNote($note: notes_insert_input!) {
    insert_notes_one(object: $note) {
      __typename
      title
    }
  }
`</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> INSERT_NOTE;
</code></pre>
<p>Now, for the React part, here is the core logic to interact with NHost:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">CreateNote</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [note, setNote] = useState(<span class="hljs-string">""</span>);
  <span class="hljs-keyword">const</span> [insertError, setInsertError] = useState&lt;CombinedError | <span class="hljs-literal">null</span>&gt;(<span class="hljs-literal">null</span>);
  <span class="hljs-keyword">const</span> [{ fetching }, insertNote] = useMutation(INSERT_NOTE);

  <span class="hljs-keyword">const</span> addNote = <span class="hljs-keyword">async</span> () =&gt; {
    <span class="hljs-keyword">if</span> (!note) <span class="hljs-keyword">return</span>;
    setInsertError(<span class="hljs-literal">null</span>);

    <span class="hljs-keyword">const</span> { error } = <span class="hljs-keyword">await</span> insertNote({
      note: {
        title: note,
      },
    });

    <span class="hljs-keyword">if</span> (error) {
      setInsertError(error);
    } <span class="hljs-keyword">else</span> {
      setNote(<span class="hljs-string">""</span>);
    }
  };

  <span class="hljs-keyword">return</span> (
    <span class="hljs-comment">// HTML here</span>
  )
}
</code></pre>
<p>That was easy! Now, let's move to the part where we have to fetch the notes!</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { useQuery } <span class="hljs-keyword">from</span> <span class="hljs-string">"urql"</span>;
<span class="hljs-keyword">import</span> GET_NOTES <span class="hljs-keyword">from</span> <span class="hljs-string">"../../utils/graphql/get"</span>;

<span class="hljs-keyword">const</span> [{ data, fetching }] = useQuery({
    query: GET_NOTES,
});
</code></pre>
<p>This is pretty easy too, now moving to the last part, deleting the note.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { gql } <span class="hljs-keyword">from</span> <span class="hljs-string">"urql"</span>;

<span class="hljs-keyword">const</span> DELETE_NOTE = gql<span class="hljs-string">`
  mutation deleteNote($id: uuid!) {
    delete_notes_by_pk(id: $id) {
        id
    }
  }
`</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> DELETE_NOTE;
</code></pre>
<p>This is the query mutation, and to delete it, we just call the <code>deleteNote</code> function</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">NoteCard</span>(<span class="hljs-params">{ id, title }: NoteCardProps</span>) </span>{
  <span class="hljs-keyword">const</span> [insertError, setInsertError] = useState&lt;CombinedError | <span class="hljs-literal">null</span>&gt;(<span class="hljs-literal">null</span>);
  <span class="hljs-keyword">const</span> [{ fetching }, deleteNote] = useMutation(DELETE_NOTE);

  <span class="hljs-keyword">const</span> onDeleteNote = <span class="hljs-keyword">async</span> () =&gt; {
    setInsertError(<span class="hljs-literal">null</span>);

    <span class="hljs-keyword">const</span> { error } = <span class="hljs-keyword">await</span> deleteNote({
      id,
    });

    <span class="hljs-keyword">if</span> (error) {
      setInsertError(error);
    }
  };

  <span class="hljs-keyword">return</span> (
    <span class="hljs-comment">// HTML here</span>
  )
}
</code></pre>
<p>This is how simple it is to create a full-fledged application using NHost. It was fun using NHost for this project, and I think NHost would be my go-to choice in the future!</p>
<p>Again, The complete source code for this blog is available at <a target="_blank" href="https://github.com/officialpiyush/notes-app">https://github.com/officialpiyush/notes-app</a></p>
<p>Building this app with NHost was super quick and easy, hope this almost follow-along blog tinkers you to experiment with NHost too, [happy coding!]</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672077473877/02c3f261-25a8-4d23-b69b-5d3ec5154a89.jpeg" alt class="image--center mx-auto" /></p>
]]></content:encoded></item></channel></rss>