<?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[The Wannabe Dev]]></title><description><![CDATA[The Wannabe Dev]]></description><link>https://thewannabedev.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Thu, 12 Nov 2026 19:00:52 GMT</lastBuildDate><atom:link href="https://thewannabedev.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Twiginity: Bulk delete all your tweets for FREE]]></title><description><![CDATA[In this article, I share all details behind the making of Twiginity, from mockups to the tools used, the challenges faced and how I overcame them.]]></description><link>https://thewannabedev.hashnode.dev/twiginity-bulk-delete-all-your-tweets-for-free</link><guid isPermaLink="true">https://thewannabedev.hashnode.dev/twiginity-bulk-delete-all-your-tweets-for-free</guid><category><![CDATA[Twitter]]></category><category><![CDATA[REST API]]></category><category><![CDATA[MERN Stack]]></category><category><![CDATA[React]]></category><category><![CDATA[Express]]></category><dc:creator><![CDATA[Othmane Lamnabhi]]></dc:creator><pubDate>Tue, 22 Mar 2022 21:48:48 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1741734303850/3ad6f85e-2dc0-4438-9d45-8b6d1ca33fd3.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-what-is-twiginity">What is Twiginity?</h2>
<p>Twignity is a mass tweet deleter. Easy. Plain. Simple.</p>
<p>There are many of these out there if you search on GitHub but they're for the most part CLI which makes them mostly usable by savvy people with a Twitter developper account.</p>
<p>Some people will say</p>
<blockquote>
<p>❝ <a target="_blank" href="https://tweetdelete.net">TweetDelete</a> exists ❞</p>
</blockquote>
<p>But you can only delete up to 3.200 tweets... to delete anything beyond that number you'd need to pay.</p>
<p><strong>Note:</strong> <code>Twitter API v1.1 is now deprecated, and with the API becoming a paid product, this app can’t be used anymore.</code></p>
<h2 id="heading-features">Features ✨</h2>
<ul>
<li><p>Delete the 3200 most recent tweets (this is as much as Twitter API will allow you to fetch)</p>
</li>
<li><p>Delete tweets past a certain date</p>
</li>
<li><p>Delete only tweets containing a certain keyword</p>
</li>
<li><p>Delete all your account's tweets if you provide your <em>tweets.js</em> file</p>
</li>
</ul>
<h2 id="heading-design">Design 🎨</h2>
<p>Truthfully, I did not dwell much on the UI so I tried copying something I liked.</p>
<p>The result was a mashup between <a target="_blank" href="https://hypefury.com">Hypefury</a> &amp; <a target="_blank" href="https://tweetdelete.net">TweetDelete</a> which turned out ok (although don't ask <a target="_blank" href="https://twitter.com/gitignorer?s=21">@gitignorer</a> for his opinion on the accent color... he HATES it and that's why I'm keeping it 😜).</p>
<ul>
<li><p>Twiginity's homepage when the user is not logged in</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1647723601589/v_RcD0wvl.jpg" alt="Twiginity's homepage when the user is not logged in" /></p>
</li>
<li><p>The screen that appears when the user clicks on "Most Recent"</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1647723981822/gMKJKVWyV.jpg" alt="The screen that appears when the user clicks on &quot;Most Recent&quot;" /></p>
</li>
<li><p>The screen that appears when the user clicks on "Everything"</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1647724001129/x5qS2APjS.png" alt="The screen that appears when the user clicks on &quot;Everything&quot;" /></p>
</li>
</ul>
<p>These mockups provided the clarity needed for me to start working on Twiginity, but as I would learn later, the devil is in the details, and as I was coding and getting into the nooks and crannies of each feature, many new details I hadn't thought of surfaced.</p>
<h2 id="heading-tech-stack">Tech Stack 🛠️</h2>
<h3 id="heading-front-end">Front-end</h3>
<ul>
<li><p>React</p>
</li>
<li><p><a target="_blank" href="https://mui.com">MUI</a></p>
</li>
<li><p><a target="_blank" href="https://pqina.nl/filepond/">Filepond</a></p>
</li>
<li><p><a target="_blank" href="https://socket.io">Socket.IO</a></p>
</li>
</ul>
<h3 id="heading-back-end">Back-end</h3>
<ul>
<li><p>Node</p>
</li>
<li><p>Express</p>
</li>
<li><p><a target="_blank" href="https://socket.io">Socket.IO</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/bee-queue/bee-queue">bee-queue</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/bee-queue/arena#readme">bull-arena</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/richardgirges/express-fileupload#readme">express-fileupload</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/pensierinmusica/firstline">firstline</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/codealchemist/line-replace#readme">line-replace</a></p>
</li>
<li><p><a target="_blank" href="https://www.passportjs.org/">passport</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/redis/node-redis">redis</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/plhery/node-twitter-api-v2#readme">twitter-api-v2</a></p>
</li>
</ul>
<h3 id="heading-deployment">Deployment</h3>
<p>Initially I was planning on getting a VPS from Hostinger because I wanted to have root access to customize anything I wanted (database, nginx, php version, redis server, etc...), I also wanted to host my future personal website and other portfolio items on there as well.</p>
<p>A friend of mine convinced me (pretty easily) to try <a target="_blank" href="https://heroku.com">Heroku</a>'s free tier package. And after some reading, I went through my code again, rewriting some parts to get it production-ready.</p>
<p>I hooked Heroku to Twiginity's repo and added a script that would start building my app automatically right after commit.</p>
<h4 id="heading-1st-commit">❌ 1st commit</h4>
<p>App failed to run because one of the dependencies <code>stream-replace-string</code> had to be compiled into a commonJS module before usage.</p>
<ul>
<li>I created a helper script and added it to <code>heroku-postbuild</code> so that the compiling would happen right after all the dependencies have been installed.</li>
</ul>
<h4 id="heading-2nd-commit">❌ 2nd commit</h4>
<p>Twiginity failed to run because one of the dependencies (<code>morgan</code>) was missing, although I was pretty sure I never deleted it.</p>
<p>Turns out, that when Heroku build your apps and installs your dependencies, it uninstalls the dev ones right after, which explains the <em>"missing dependency"</em> error.</p>
<ul>
<li>Since I had no more use for that dependency, I just deleted it from my code and my <code>package.json</code> file.</li>
</ul>
<h4 id="heading-3rd-commit">✅ 3rd commit</h4>
<p>Still no luck getting the app to run, because Heroku could not manage to bind the app to a port.</p>
<ul>
<li>All I had to do though was to rename the PORT env variable to <code>PORT</code> so my app could use the port number assigned by Heroku.</li>
</ul>
<h2 id="heading-twiginitys-main-features">Twiginity's main features</h2>
<h3 id="heading-authentication">Authentication</h3>
<p>To use the app, the user has to sign in with Twitter.</p>
<h4 id="heading-backend">Backend</h4>
<p>The authentication is handled on the backend with <a target="_blank" href="https://www.passportjs.org/">passport</a> through these different endpoints:</p>
<ul>
<li><p><code>/auth/twitter</code> — authenticate via passport twitter</p>
</li>
<li><p><code>/auth/login/success</code> — returns login success response with user information</p>
</li>
<li><p><code>/auth/login/failed</code> — returns login failed message</p>
</li>
<li><p><code>/auth/logout</code> — log-out and redirects to client home page</p>
</li>
<li><p><code>/auth/twitter/redirect</code> — redirect to "Most Recent" screen if login succeeded or redirect to homepage if failed</p>
</li>
</ul>
<p>Once the user clicks on the <code>Sign in with Twitter</code> button, his profile picture, his username, his Twitter ID and his tokens are fetched during the OAUTH login flow, then the tokens are encrypted before everything is stored in a MongoDB database.</p>
<p>When the login is successful, the user is redirected to the "Most Recent" page and cookies are set.</p>
<h4 id="heading-frontend">Frontend</h4>
<p>On the frontend, the authentication data and methods are made available through a context provider that wraps around the whole app.</p>
<pre><code class="lang-plaintext">    &lt;AuthProvider&gt;
      &lt;App /&gt;
    &lt;/AuthProvider&gt;
</code></pre>
<p>You can find below the code making up <code>AuthProvider</code></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">AuthProvider</span>(<span class="hljs-params">{ children }</span>) </span>{
  <span class="hljs-keyword">const</span> [authenticatedUser, setAuthenticatedUser] = useState({
    <span class="hljs-attr">authenticated</span>: <span class="hljs-literal">null</span>,
    <span class="hljs-attr">user</span>: <span class="hljs-literal">null</span>,
  });

  <span class="hljs-keyword">const</span> { authenticated } = authenticatedUser;

  <span class="hljs-keyword">const</span> twitterId = authenticatedUser?.user?.twitterId;

  useEffect(<span class="hljs-function">() =&gt;</span> {
    fetch(<span class="hljs-string">"/auth/login/success"</span>, {
      <span class="hljs-attr">method</span>: <span class="hljs-string">"GET"</span>,
      <span class="hljs-attr">credentials</span>: <span class="hljs-string">"include"</span>,
      <span class="hljs-attr">headers</span>: {
        <span class="hljs-attr">Accept</span>: <span class="hljs-string">"application/json"</span>,
        <span class="hljs-string">"Content-Type"</span>: <span class="hljs-string">"application/json"</span>,
        <span class="hljs-string">"Access-Control-Allow-Credentials"</span>: <span class="hljs-literal">true</span>,
      },
    })
      .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> {
        <span class="hljs-keyword">if</span> (response.status === <span class="hljs-number">200</span>) <span class="hljs-keyword">return</span> response.json();
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"failed to authenticate user"</span>);
      })
      .then(<span class="hljs-function">(<span class="hljs-params">responseJson</span>) =&gt;</span> {
        <span class="hljs-keyword">const</span> authInfo = {
          <span class="hljs-attr">authenticated</span>: <span class="hljs-literal">true</span>,
          <span class="hljs-attr">user</span>: responseJson.user,
        };
        setAuthenticatedUser(authInfo);
      })
      .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
        setAuthenticatedUser({
          <span class="hljs-attr">authenticated</span>: <span class="hljs-literal">false</span>,
          <span class="hljs-attr">error</span>: <span class="hljs-string">"Failed to authenticate user"</span>,
        });
      });
  }, []);

  <span class="hljs-keyword">const</span> socket = authenticated
    ? io({
        <span class="hljs-attr">autoConnect</span>: <span class="hljs-literal">false</span>,
        <span class="hljs-attr">query</span>: {
          twitterId,
        },
      })
    : <span class="hljs-literal">null</span>;

  <span class="hljs-keyword">const</span> handleSignInClick = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">window</span>.open(<span class="hljs-string">"/auth/twitter"</span>, <span class="hljs-string">"_self"</span>);
  };

  <span class="hljs-keyword">const</span> handleLogoutClick = <span class="hljs-function">(<span class="hljs-params">e, expired = <span class="hljs-literal">false</span></span>) =&gt;</span> {
    expired
      ? <span class="hljs-built_in">window</span>.open(<span class="hljs-string">`/auth/logout?session=expired`</span>, <span class="hljs-string">"_self"</span>)
      : <span class="hljs-built_in">window</span>.open(<span class="hljs-string">`/auth/logout`</span>, <span class="hljs-string">"_self"</span>);
    handleNotAuthenticated();
  };

  <span class="hljs-keyword">const</span> handleNotAuthenticated = <span class="hljs-function">() =&gt;</span> {
    socket.disconnect();
    setAuthenticatedUser({ <span class="hljs-attr">authenticated</span>: <span class="hljs-literal">false</span> });
  };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">AuthContext.Provider</span>
      <span class="hljs-attr">value</span>=<span class="hljs-string">{{</span>
        <span class="hljs-attr">authenticatedUser</span>,
        <span class="hljs-attr">handleLogoutClick</span>,
        <span class="hljs-attr">handleSignInClick</span>,
        <span class="hljs-attr">socket</span>,
        <span class="hljs-attr">handleNotAuthenticated</span>,
      }}&gt;</span>
      {children}
    <span class="hljs-tag">&lt;/<span class="hljs-name">AuthContext.Provider</span>&gt;</span></span>
  );
}
</code></pre>
<p>When the app is loaded the first time or refreshed, a request is sent to <code>/auth/login/success</code>. If the request is signed with a cookie, then a <code>200</code> response is received, the user auth status is set to <code>true</code> and a socket is instantiated.</p>
<h3 id="heading-protected-routes">Protected routes</h3>
<p>To use the the app's features, you need to be logged in. Which means that access to "Most Recent" and "Everything" should be restricted to signed in users only.</p>
<p>To make that happen, I created a component named <code>RequireAuth</code> that I wrapped around components I wanted to protect.</p>
<pre><code class="lang-javascript">&lt;Route exact path=<span class="hljs-string">'/delete-everything'</span> element={ <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">RequireAuth</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">DeleteEverything</span> /&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">RequireAuth</span>&gt;</span></span>} /&gt;
</code></pre>
<p>This component checks whether the user is authenticated before rendering the children.</p>
<h4 id="heading-issue-with-routing">⚠️ Issue with routing</h4>
<p>When trying to access one of the protected routes from the address bar, I always ended up being redirected to the homepage.</p>
<p>This was due to my initial auth state being set to <code>false</code> inside <code>AuthProvider</code>, which meant that <code>RequireAuth</code> was rendering the unauthenticated route before <code>AuthProvider</code>'s useEffect had a chance to run and set my auth status to <code>true</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">RequireAuth</span>(<span class="hljs-params">{ children }</span>) </span>{
  <span class="hljs-keyword">let</span> {
    <span class="hljs-attr">authenticatedUser</span>: { authenticated },
  } = useAuth();

  <span class="hljs-keyword">return</span> authenticated ? children : <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Navigate</span> <span class="hljs-attr">to</span>=<span class="hljs-string">'/'</span> /&gt;</span></span>;
}
</code></pre>
<h4 id="heading-solution">✅ Solution</h4>
<p>I set the initial auth status to <code>null</code> and then rewrote <code>RequireAuth</code> so as to not render anything until useEffect runs thus setting the auth state and triggering a rerender.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">RequireAuth</span>(<span class="hljs-params">{ children }</span>) </span>{
  <span class="hljs-keyword">let</span> {
    <span class="hljs-attr">authenticatedUser</span>: { authenticated },
  } = useAuth();

  <span class="hljs-keyword">return</span> authenticated === <span class="hljs-literal">null</span> ? <span class="hljs-literal">null</span> : authenticated ? children : <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Navigate</span> <span class="hljs-attr">to</span>=<span class="hljs-string">'/'</span> /&gt;</span></span>;
}
</code></pre>
<h3 id="heading-log-user-out-on-unauthenticated-request">Log user out on unauthenticated request</h3>
<p>When the user signs in with Twitter, a cookie is created and stored with his ID and every subsequent request made is signed with that cookie before getting sent to the backend.</p>
<p>The backend then makes a request to Twitter with the API keys and access tokens. These tokens never expire UNLESS you revoke Twiginity's permissions or deactivate your account.</p>
<p>But if any of those two scenarios happen, an issue arises.</p>
<h4 id="heading-issue">⚠️ Issue</h4>
<p>Say you logged in to use Twiginity and then decided to deactivate your account or revoke permissions once you were done.</p>
<p>a Twiginity session is 24h long, so if you forgot to delete some tweets and came back to use it, you would find yourself still logged in, but any attempt to delete tweets or upload a file would result in errors because the requests you'd be making to the Twitter API would be using expired tokens.</p>
<h4 id="heading-solution-1">✅ Solution</h4>
<p>To fix that, I added inside each route a simple request to the Twitter API that fetches the ID of the pinned tweet. If that request goes through then the rest of the code will go through, if that request fails with a status code 401 then an error is thrown inside the try/catch block.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">await</span> client.v2.me({ <span class="hljs-attr">expansions</span>: [<span class="hljs-string">"pinned_tweet_id"</span>] });
</code></pre>
<p>A <code>401</code> error triggers the <code>handleLogoutClick</code> function that initiates the logout sequence by logging the user out thanks to passport, disconnecting the socket instance and setting auth status to <code>false</code> in the <code>AuthProvider</code>.</p>
<pre><code class="lang-javascript">axios
      .delete(<span class="hljs-string">"/tweets/delete-recent-tweets"</span>, {
        <span class="hljs-attr">data</span>: { <span class="hljs-attr">time</span>: pastTime, keyword },
        <span class="hljs-attr">withCredentials</span>: <span class="hljs-literal">true</span>,
      })
      .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> {
        setState(response.data);
      })
      .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
        <span class="hljs-keyword">if</span> (error.response.status === <span class="hljs-number">401</span>) {
          <span class="hljs-keyword">return</span> handleLogoutClick(<span class="hljs-literal">undefined</span>, <span class="hljs-literal">true</span>);
        }
        setState({ <span class="hljs-attr">type</span>: deletionState.error, <span class="hljs-attr">message</span>: error.response.data.message });
      });
</code></pre>
<pre><code class="lang-javascript">  <span class="hljs-keyword">const</span> handleLogoutClick = <span class="hljs-function">(<span class="hljs-params">e, expired = <span class="hljs-literal">false</span></span>) =&gt;</span> {
    expired
      ? <span class="hljs-built_in">window</span>.open(<span class="hljs-string">`/auth/logout?session=expired`</span>, <span class="hljs-string">"_self"</span>)
      : <span class="hljs-built_in">window</span>.open(<span class="hljs-string">`/auth/logout`</span>, <span class="hljs-string">"_self"</span>);
    handleNotAuthenticated();
  };

  <span class="hljs-keyword">const</span> handleNotAuthenticated = <span class="hljs-function">() =&gt;</span> {
    socket.disconnect();
    setAuthenticatedUser({ <span class="hljs-attr">authenticated</span>: <span class="hljs-literal">false</span> });
  };
</code></pre>
<h3 id="heading-job-queue">Job Queue</h3>
<p>The concept of job queue was new to me and I would have probably never thought of it if the app was for my use alone. But as I started thinking about Twiginity being used by multiple users, a lot of questions started to surface.</p>
<p>One of those questions being "How can I handle servicing multiple users?" knowing that if just one person decided to delete thousands of tweets, she would block the app's use for everyone else.</p>
<p>I needed to make the deletion process async but more importantly, I needed to respect the hierarchy by queuing upcoming tweets. Some googling lead me to discover job queues, and that's how I ended up using <a target="_blank" href="https://github.com/OptimalBits/bull">Bull</a>.</p>
<h4 id="heading-issue-1">⚠️ Issue 1</h4>
<p>I set up my queue processor function to console.log and broadcast through a socket connection the index of each tweet, just to check if everything was working. But to my surprise, some tweet indexes were skipped. Upon checking the queue, I found out that those tweets were processed, but that no event was emitted.</p>
<p>For instance out of 20 tweets, here is the output I'd get:</p>
<pre><code class="lang-bash">tweet 1
tweet 3
tweet 5
tweet 7
tweet 9
tweet 11
tweet 13
tweet 15
tweet 17
tweet 19
</code></pre>
<p>Which was very problematic, because my frontend was expecting to receive the last tweet event to trigger the frontend's state update, which meant that for that to happen, I needed events to be emitted reliably.</p>
<h4 id="heading-solution-1-1">✅ Solution 1</h4>
<p>I looked up the issue online but to no avail. During my troubleshooting, I disabled any dependency I thought could be the culprit: <code>nodemon</code>, <code>socket.io</code>, etc... same result.</p>
<p>I decided to give up on Bull and to try another queue manager, <code>bee-queue</code>. The syntax and requirements were almost identical, which made replacing bull very easy. And TADA! it worked. All the job events were properly and reliably emitted.</p>
<h4 id="heading-issue-2">⚠️ Issue 2</h4>
<p>When working on transmitting updates to the frontend through the use of sockets, I wrapped a setTimeout function inside a promise to simulate an async operation.</p>
<p>Concurrency on Twiginity was set to 1 which meant that the queue was processing one job at a time and progress was reported correctly.</p>
<p>Progress was calculated this way <code>Math.round(((index + 1) / numberOfTweets) * 100)</code> and sent to the frontend to update the progress bar.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> awaitTimeout = <span class="hljs-function">(<span class="hljs-params">delay</span>) =&gt;</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =&gt;</span> <span class="hljs-built_in">setTimeout</span>(resolve, delay));

 <span class="hljs-keyword">const</span> deletionProcess = <span class="hljs-keyword">async</span> (
   { <span class="hljs-attr">data</span>: { tweetId, tokens, twitterId, numberOfTweets, index, socketId } },
   done
 ) =&gt; {
   <span class="hljs-keyword">await</span> awaitTimeout(<span class="hljs-number">1000</span>);
   <span class="hljs-keyword">try</span> {
     <span class="hljs-built_in">console</span>.log(index + <span class="hljs-number">1</span>);
     io.to(socketId).emit(<span class="hljs-string">"deleting"</span>, {
       <span class="hljs-attr">type</span>: <span class="hljs-string">"deleting"</span>,
       <span class="hljs-attr">progress</span>: <span class="hljs-built_in">Math</span>.round(((index + <span class="hljs-number">1</span>) / numberOfTweets) * <span class="hljs-number">100</span>),
       <span class="hljs-attr">tweetNumber</span>: index + <span class="hljs-number">1</span>,
     });

     done(<span class="hljs-literal">null</span>, index + <span class="hljs-number">1</span>);
   } <span class="hljs-keyword">catch</span> (error) {
     io.to(socketId).emit(<span class="hljs-string">"deleting"</span>, {
       <span class="hljs-attr">type</span>: <span class="hljs-string">"deleting"</span>,
       <span class="hljs-attr">progress</span>: <span class="hljs-built_in">Math</span>.round(((index + <span class="hljs-number">1</span>) / numberOfTweets) * <span class="hljs-number">100</span>),
       <span class="hljs-attr">tweetNumber</span>: index + <span class="hljs-number">1</span>,
       <span class="hljs-attr">deleteError</span>: <span class="hljs-string">`Tweet ID -&gt; <span class="hljs-subst">${tweetId}</span> could not be deleted.`</span>,
       <span class="hljs-attr">error</span>: error.message,
     });

     done(error);
   }
 };
</code></pre>
<p>Since we're dealing with requests here, I upped bee's concurrency to 10 and replaced the setTimeout function with the real Twitter API call.</p>
<p>The result was that sometimes the progress bar would never reach 100%, which was odd because all jobs were processed when I checked my Redis queue. And since I was still logging the index of each tweet to the console, I realized that since these operations are async, each one was returning at a different time, and not necessarily in order. which meant that I could get 100% as a progress value and then 90% just after.</p>
<h4 id="heading-solution-2">✅ Solution 2</h4>
<p>I needed a way to calculate the progress made, whether the tweet was deleted or not. Since all the jobs were being reported correctly now, and the only remaining issue was order, I decided to transfer the progress calculations to the frontend.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> awaitTimeout = <span class="hljs-function">(<span class="hljs-params">delay</span>) =&gt;</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =&gt;</span> <span class="hljs-built_in">setTimeout</span>(resolve, delay));

<span class="hljs-keyword">const</span> deletionProcess = <span class="hljs-keyword">async</span> (
  { <span class="hljs-attr">data</span>: { tweetId, tokens, twitterId, numberOfTweets, index, socketId, username } },
  done
) =&gt; {
  <span class="hljs-keyword">const</span> twitterClient = <span class="hljs-keyword">new</span> TwitterApi({
    <span class="hljs-attr">appKey</span>: process.env.API_KEY,
    <span class="hljs-attr">appSecret</span>: process.env.API_SECRET_KEY,
    <span class="hljs-attr">accessToken</span>: tokens.accessToken,
    <span class="hljs-attr">accessSecret</span>: tokens.accessTokenSecret,
  });
  <span class="hljs-keyword">try</span> {
    <span class="hljs-built_in">console</span>.log(index + <span class="hljs-number">1</span>);
    <span class="hljs-keyword">await</span> twitterClient.v1.deleteTweet(<span class="hljs-string">"1498397214393122823"</span>);
    io.to(socketId).emit(<span class="hljs-string">"deleting"</span>, {
      <span class="hljs-attr">type</span>: <span class="hljs-string">"deleting"</span>,
      numberOfTweets,
      <span class="hljs-attr">increment</span>: <span class="hljs-number">1</span>,
    });

    done(<span class="hljs-literal">null</span>, index + <span class="hljs-number">1</span>);
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.log(error.code);
    <span class="hljs-keyword">if</span> (error?.code === <span class="hljs-number">404</span>) {
      io.to(socketId).emit(<span class="hljs-string">"deleting"</span>, {
        <span class="hljs-attr">type</span>: <span class="hljs-string">"deleting"</span>,
        numberOfTweets,
        <span class="hljs-attr">increment</span>: <span class="hljs-number">1</span>,
        tweetId,
        <span class="hljs-attr">deleteError</span>: <span class="hljs-string">"notFound"</span>,
        <span class="hljs-attr">error</span>: error.message,
      });
      <span class="hljs-keyword">return</span> done(error);
    }
    io.to(socketId).emit(<span class="hljs-string">"deleting"</span>, {
      <span class="hljs-attr">type</span>: <span class="hljs-string">"deleting"</span>,
      numberOfTweets,
      <span class="hljs-attr">increment</span>: <span class="hljs-number">1</span>,
      tweetId,
      username,
      <span class="hljs-attr">deleteError</span>: <span class="hljs-string">"anotherError"</span>,
      <span class="hljs-attr">error</span>: error.message,
    });

    done(error);
  }
};
</code></pre>
<pre><code class="lang-javascript">&lt;ProgressBar
               messages={state?.deleteError}
               tweetsProcessed={state.increment}
               numberOfTweets={state.numberOfTweets}
/&gt;
</code></pre>
<pre><code class="lang-javascript">&lt;LinearProgressWithLabel
         value={<span class="hljs-built_in">Math</span>.round((tweetsProcessed / numberOfTweets) * <span class="hljs-number">100</span>)}
/&gt;
</code></pre>
<h3 id="heading-progress-bar-and-different-states">Progress bar and different states</h3>
<p>As the features started taking shape, I started thinking more and more from a user's POV. Again, if the app was for my use alone, I could have gotten away with many things, but I wanted Twiginity to be used by anyone with a Twitter account, and that meant making it as user-friendly possible.</p>
<p>When the user clicks on "Delete tweets", a backdrop shows up indicating how many tweets are about to be processed. If another user's tweets are already queued, then the app will let you know that you can safely close the window as Twiginity will process your tweets when the time comes.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1647942105843/QXUhO5tLb.png" alt="Twiginity's progress bar" /></p>
<p>Once the queue starts processing your tweets, updates are received through the socket connection, and progress is reflected on the progress bar.</p>
<p>If any error occurs, a field will display the error as well as the tweet where the error originated from.</p>
<p>Errors fall into two types:</p>
<ol>
<li><p>tweet cannot be found because it might have already been deleted.</p>
</li>
<li><p>tweet could not be deleted because of some unknown issue (connectivity, rate limit, etc...) in which case, a clickable link to the tweet is displayed.</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1647954206422/bLO4-Osij.png" alt="some tweets that failed to be deleted" /></p>
<p>If you're trying to delete some of your recent tweets and none are found that correspond to your criteria, then this message shows up:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1647954928836/LJb2BNHY3.png" alt="no results corresponding to search criteria" /></p>
<h3 id="heading-file-upload">File upload</h3>
<h4 id="heading-frontend-1">Frontend</h4>
<p>I always found drop zones intuitive. And that's how I ended up using <code>filepond</code>. The package was <em>packed</em> with useful options.</p>
<p>I set up filepond to accept only JS files not exceeding 100mb and the whole page can be used to drop the file instead of just the drop zone.</p>
<h4 id="heading-backend-1">Backend</h4>
<p>In the backend, I used a packaged called <code>express-fileupload</code> and configured it with the following options</p>
<pre><code class="lang-javascript">fileUpload({
      <span class="hljs-attr">useTempFiles</span>: <span class="hljs-literal">true</span>, <span class="hljs-comment">// use temp files instead of RAM</span>
      <span class="hljs-attr">tempFileDir</span>: <span class="hljs-string">"../../tmp/"</span>,
      <span class="hljs-attr">parseNested</span>: <span class="hljs-literal">true</span>, <span class="hljs-comment">// parse the whole req.files object</span>
      <span class="hljs-attr">createParentPath</span>: <span class="hljs-literal">true</span>, <span class="hljs-comment">// create directory if it doesn't exist</span>
      <span class="hljs-attr">debug</span>: <span class="hljs-literal">true</span>,
})
</code></pre>
<p>Filepond starts uploading the file as soon as it is dropped or selected and once the upload is finished, the user can click on the "Delete tweets" button.</p>
<p>The file size and file type checks happen in the frontend before the file is sent.</p>
<h4 id="heading-issue-3">Issue</h4>
<p>Later when Twignity was published, I open it on Safari to show it to a friend, and as I was trying to delete my own tweets using a <code>tweet.js</code> file, filepond returned an error saying the file type was not valid. (going through the same steps on Chrome worked as expected)</p>
<p>I learned through some googling that some browsers fail to detect file type correctly.</p>
<h4 id="heading-solution-3">Solution</h4>
<p>Thankfully, filepond comes with a plugin <code>FilePondPluginFileValidateType</code> that allows you to set up custom filetype checks:</p>
<pre><code class="lang-javascript">fileValidateTypeDetectType={<span class="hljs-function">(<span class="hljs-params">source, type</span>) =&gt;</span>
        <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
          <span class="hljs-keyword">if</span> (<span class="hljs-regexp">/\.js$/</span>.test(source.name)) {
            <span class="hljs-keyword">return</span> resolve(<span class="hljs-string">"text/javascript"</span>);
          }
        })
      }
</code></pre>
<p>This allows the FileUploader component to perform its own check and provide the browser with the correct filetype.</p>
<h3 id="heading-twitter-client-as-middleware">Twitter Client as middleware</h3>
<ul>
<li>twitter-api-v2 as middleware To make requests to the Twitter API, I resorted to an awesome package called <code>twitter-api-v2</code>, to use it, you just have to instantiate a client with the API KEYS and ACCESS TOKENS.</li>
</ul>
<p>Those access tokens are only available for use inside routes because <code>passport</code> loads the user data inside <code>req.user</code>. All I had to do was create a middleware function.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> { TwitterApi } = <span class="hljs-built_in">require</span>(<span class="hljs-string">"twitter-api-v2"</span>);

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">twitterClient</span>(<span class="hljs-params">req, res, next</span>) </span>{
  req.twitterClient = <span class="hljs-keyword">new</span> TwitterApi({
    <span class="hljs-attr">appKey</span>: process.env.API_KEY,
    <span class="hljs-attr">appSecret</span>: process.env.API_SECRET_KEY,
    <span class="hljs-attr">accessToken</span>: req.user.tokens.accessToken,
    <span class="hljs-attr">accessSecret</span>: req.user.tokens.accessTokenSecret,
  });

  next();
}
</code></pre>
<p>And add it to my routes</p>
<pre><code class="lang-javascript">tweetsRouter.delete(<span class="hljs-string">"/delete-tweet-js"</span>, isAuthenticated, twitterClient, deleteTweetJs);
</code></pre>
<h3 id="heading-sockets">Sockets</h3>
<p>The idea of using sockets came to me when I was trying to find a way to send updates to the frontend. With Node/Express once a response was sent, it was final... but I needed to update the user on the progress of the operation 🥺</p>
<p>That's how I stumbled initially on server-sent events which I quickly discarded because besides the fact that they only work with <code>GET</code> requests, most of my updates were going to be send from inside jobs in the queue and not from within the route.</p>
<p>Socket.io ended up being the perfect solution to my problem, here is how I set it up:</p>
<ol>
<li><p>when the user logs in, a socket is created on the frontend but no connection is made.</p>
</li>
<li><p>when the user navigates to "Most Recent" or "Everything", the socket instance establishes a connection with the backend.</p>
</li>
<li><p>once a connection is established, an entry is created under the <code>user</code> hash in the Redis database associating the user's Twitter ID with the socket ID.</p>
</li>
<li><p>this socket ID is fetched inside the express routes based on the Twitter ID initiating the operation and then sent as part of the job data to the job queue, so that when each job/tweet is processed, the update is sent to the right user.</p>
</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addArrayOfTweetsToJobQueue</span>(<span class="hljs-params">
  arrayOfTweets,
  tokens,
  twitterId,
  username,
  socketId,
  addToQueueFunction
</span>) </span>{
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> [index, tweet] <span class="hljs-keyword">of</span> arrayOfTweets.entries()) {
    <span class="hljs-keyword">const</span> id = tweet?.tweet?.id === <span class="hljs-literal">undefined</span> ? tweet.id : tweet.tweet.id;

    <span class="hljs-keyword">const</span> jobData = {
      <span class="hljs-attr">tweetId</span>: id,
      tokens,
      twitterId,
      username,
      <span class="hljs-attr">numberOfTweets</span>: arrayOfTweets.length,
      index,
      socketId,
    };
    addToQueueFunction(jobData);
  }
}
</code></pre>
<h3 id="heading-deleting-recent-tweets">Deleting recent tweets</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1647726448500/MofYCgJUt.png" alt="&quot;Most Recent&quot; screen" /></p>
<h4 id="heading-what-happens-when-the-delete-tweets-button-is-pressed">What happens when the <code>Delete tweets</code> button is pressed ?</h4>
<ol>
<li><p>Twiginity grabs the current time and subtracts the duration chosen by the user which results in a new date that gets converted to ISO format.</p>
</li>
<li><p>the date along with a keyword (if provided) are sent to the backend.</p>
</li>
<li><p>Inside the route, we then fetch the Twitter API and retrieve the tweets starting from the provided date.</p>
</li>
<li><p>Once that's done, we transform both the keyword and the tweets to lowercase and then filter the array of tweets keeping only the ones containing the keyword.</p>
</li>
<li><p>we loop through the array adding each tweet to the job queue.</p>
</li>
<li><p>we inform the user that his request has been processed successfully.</p>
</li>
</ol>
<h3 id="heading-deleting-all-tweets">Deleting all tweets</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1647727806824/L7Af5MBOl.png" alt="&quot;Everything&quot; screen" /></p>
<ol>
<li>The user drops the file into the file uploader which instantly starts the upload process. In the backend, this translates into the file being uploaded and then renamed with the user's Twitter ID before getting moved to a specific folder.</li>
</ol>
<h4 id="heading-what-happens-when-the-delete-tweets-button-is-pressed-1">What happens when the <code>Delete tweets</code> button is pressed ?</h4>
<ol>
<li><p>the form checks if a file was provided and uploaded before sending the request.</p>
</li>
<li><p>If somehow, the file got deleted in between the upload and pressing the <code>Delete tweets</code>button, another check inside the route makes sure the file exists before proceeding or throws an error.</p>
</li>
<li><p>Once we make sure the file exists, the app checks whether it's the right file by searching for a specific string found in the first line.</p>
</li>
<li><p>This file contains an array of all the tweets about to be deleted, and to use it, we replace this string <code>window.YTD.tweet.part0 =</code> with this one <code>module.exports =</code> enabling us to import the contents of the file.</p>
</li>
<li><p>We can then loop through the array adding each tweet to the job queue.</p>
</li>
<li><p>Then, we inform the user that his request has been processed successfully.</p>
</li>
</ol>
<h2 id="heading-code-and-demo">Code and Demo 💻</h2>
<ul>
<li><p>If you'd like to check out the app, feel free to visit: <a target="_blank" href="https://twiginity.onrender.com/">https://twiginity.onrender.com/</a>.</p>
</li>
<li><p>If you want to check out the code or run it locally, you can all the info and steps on my <a target="_blank" href="https://github.com/othmanelamnabhi/twiginity">repo</a>.</p>
</li>
</ul>
<p>I'd appreciate all the feedback I can get about the app or anything really. 🙏 This app was months in the making, and with this article, I hopefully close this chapter and move on to the next. 😊</p>
]]></content:encoded></item></channel></rss>