<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Mister Singh</title>
    <description>The latest articles on DEV Community by Mister Singh (@mistersingh179).</description>
    <link>https://dev.to/mistersingh179</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F335201%2F4f5d8e6c-012a-4ef9-856d-3dc7a0fbf2e1.png</url>
      <title>DEV Community: Mister Singh</title>
      <link>https://dev.to/mistersingh179</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/mistersingh179"/>
    <language>en</language>
    <item>
      <title>let's convert between bytes32 &amp; string &amp; vice-versa</title>
      <dc:creator>Mister Singh</dc:creator>
      <pubDate>Thu, 05 Jan 2023 15:51:53 +0000</pubDate>
      <link>https://dev.to/mistersingh179/lets-convert-between-bytes32-string-vice-versa-44o4</link>
      <guid>https://dev.to/mistersingh179/lets-convert-between-bytes32-string-vice-versa-44o4</guid>
      <description>&lt;h2&gt;
  
  
  Why
&lt;/h2&gt;

&lt;p&gt;Before we talk about how to convert between bytes32 &amp;amp; string, let us first know the reason why we may want to do this.&lt;/p&gt;

&lt;p&gt;So bytes32 has a fixed size and strings are dynamically sized. This produces some interesting cases like a contract can't return another contract a string or a contract can't call another contract with a string. &lt;/p&gt;

&lt;p&gt;So a reasonable alternative is to use bytes32 instead of strings. This makes our code composable.&lt;/p&gt;

&lt;h2&gt;
  
  
  string -&amp;gt; bytes32
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;string memory input = "hicksville"
bytes32 output = bytes32(abi.encodePacked(input))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdsnhsrv1t8ojn6ym837w.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdsnhsrv1t8ojn6ym837w.png" alt="string to bytes32" width="800" height="503"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  bytes32 -&amp;gt; string
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;string memory reversedInput = string(abi.encodePacked(output))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbz5hh8ubphuf7mfu3b1j.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbz5hh8ubphuf7mfu3b1j.png" alt="bytes32 to string" width="800" height="518"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>aws</category>
      <category>cloudcomputing</category>
      <category>serverless</category>
      <category>softwaredevelopment</category>
    </item>
    <item>
      <title>Let's dive a little in to function selectors in solidity</title>
      <dc:creator>Mister Singh</dc:creator>
      <pubDate>Sat, 31 Dec 2022 18:46:30 +0000</pubDate>
      <link>https://dev.to/mistersingh179/lets-dive-a-little-in-to-function-selectors-in-solidity-2e11</link>
      <guid>https://dev.to/mistersingh179/lets-dive-a-little-in-to-function-selectors-in-solidity-2e11</guid>
      <description>&lt;p&gt;Function selector is how we tell them smart contract which function to run. It is the first 4 bytes which we get from the functions name and it is used when calling low level functions like &lt;code&gt;call&lt;/code&gt; on a contract and asking it to run a function.&lt;/p&gt;

&lt;p&gt;For example &lt;code&gt;function foo(){ }&lt;/code&gt; has selector &lt;code&gt;0xc2985578&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Side Note: The function selector is most probably unique for a contract. It is just 4 bytes and that is not a lot of data and thus there can exist another function which has a totally different name but same selector. But that is neither here nor there, so let's move on.&lt;/p&gt;

&lt;p&gt;To build a selector in solidity:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;convert the function name to bytes&lt;/li&gt;
&lt;li&gt;then get its keccak256. this gives us a 1 way hash which has fixed size&lt;/li&gt;
&lt;li&gt;now take the first 4 bytes of that hash.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;bytes4(keccak256(bytes("foo()")))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Faz5gxz1y1g5br178dx72.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Faz5gxz1y1g5br178dx72.png" alt="bytes4(keccak256(bytes()))"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now, this is good, but most likely the function also takes input params and the values of the input also need to be encoded in to bytes and added to the selector.&lt;/p&gt;

&lt;p&gt;So let's say we have a function like &lt;code&gt;foo(uint256)&lt;/code&gt; which we want to call with value of &lt;code&gt;1&lt;/code&gt;. then we can get the encoded value like this&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;bytes4 prefix = bytes4(keccak256(bytes("foo(uint256)")))
uint a = 1;
bytes32 suffix = bytes32(a);
bytes memory ans = abi.encodePacked(prefix, suffix);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and this gives us &lt;code&gt;0x2fbebd380000000000000000000000000000000000000000000000000000000000000001&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;So this worked, but there is &lt;code&gt;abi.encodeWithSignature&lt;/code&gt; which is an easier way to get the selector with values all encoded in bytes for us to use.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8usv7m19szgjdi80kv5p.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8usv7m19szgjdi80kv5p.png" alt="abi.encodeWithSignature"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;And there is another helper function &lt;code&gt;abi.encodeWithSelector&lt;/code&gt; which takes the selector from us and just encodes and appends the inputs for us.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2fktur75wrilslojl0b7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2fktur75wrilslojl0b7.png" alt="abi.encodeWithSelector"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;And finally the same can be done in javascript using &lt;code&gt;ethers.js&lt;/code&gt;. We can build an &lt;code&gt;interface&lt;/code&gt; with just the function whose selector we want and call &lt;code&gt;getSigHash&lt;/code&gt; to get the selector&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fznzrmauy7uf7y2m9kz5q.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fznzrmauy7uf7y2m9kz5q.png" alt="getSigHash"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Ethers also supports encoding input values as well&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fuz2fgnrn8y0t8kxsrk6e.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fuz2fgnrn8y0t8kxsrk6e.png" alt="encodeFunctionData"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So thats it. now you know how to encode &amp;amp; build function selectors with &amp;amp; without inputs, from solidity &amp;amp; from the frontend.&lt;/p&gt;

</description>
      <category>solidity</category>
      <category>web3</category>
      <category>programming</category>
      <category>blockchain</category>
    </item>
    <item>
      <title>How I used web workers to make my react app stop freezing</title>
      <dc:creator>Mister Singh</dc:creator>
      <pubDate>Thu, 08 Dec 2022 19:12:04 +0000</pubDate>
      <link>https://dev.to/mistersingh179/how-i-used-web-workers-to-make-my-react-app-stop-freezing-1481</link>
      <guid>https://dev.to/mistersingh179/how-i-used-web-workers-to-make-my-react-app-stop-freezing-1481</guid>
      <description>&lt;h2&gt;
  
  
  The Problem:
&lt;/h2&gt;

&lt;p&gt;I have been working on this site – &lt;a href="https://app.sidekik.xyz" rel="noopener noreferrer"&gt;app.sidekik.xyz&lt;/a&gt;. It polls the users hard-drive every few seconds and reads their code, detects changes &amp;amp; then rebuilds the UI to interact with that code. As you can imagine that reading large files is heavy work and the app started to become slow when reading a large number of large sized files 🐢.&lt;/p&gt;

&lt;h2&gt;
  
  
  The why?
&lt;/h2&gt;

&lt;p&gt;In the browser there is only 1 thread, the main thread, which is the only thing taking user inputs and updating the UI. Now, if you run JS code which is eating up too much of its resources, then the app's UI will start to suffer. So yea 😬.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Solution:
&lt;/h2&gt;

&lt;p&gt;With web workers, we get setup another thread, then offload any amount of work to this thread, thus reducing the load on the main thread and making it not hang 🚀.&lt;/p&gt;

&lt;h2&gt;
  
  
  Basis Code:
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;First&lt;/strong&gt; get &lt;code&gt;npm i workerize-loader&lt;/code&gt;.  This enables loading any es6 module as a worker and then call the functions it exports. It also supports async/await, which makes it much easier to interact with the worker functions.&lt;/p&gt;

&lt;p&gt;Here is my worker file: src/workers/bg.js&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import md5 from "md5";
import readJsonObjFromFileHandle from "../helpers/readJsonObjFromFileHandle";

export async function getFileMd5(fileHandle) {
  const fileJsonObj = await readJsonObjFromFileHandle(fileHandle);
  const fileStringObj = JSON.stringify(fileJsonObj);
  const fileMd5 = md5(fileStringObj);
  return fileMd5;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Then&lt;/strong&gt; i load this worker in my app like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useEffect } from "react";
import worker from "workerize-loader?name=bg!../workers/bg";
import worker from "../workers/bg";

const workerRef = useRef();

useEffect(() =&amp;gt; {
  workerRef.current = worker();
  return () =&amp;gt; {
    workerRef.current.terminate();
  };
}, []);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; Here I am setting up 1 worker to run when the app starts up and then letting it run as long as the app is there. &lt;strong&gt;I found this to perform better&lt;/strong&gt; than creating a then terminating the worker, on a need only basis.&lt;/p&gt;

&lt;p&gt;Upon loading the App now, we can see there is a worker.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fo3xcz20v66smrmt1te2q.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fo3xcz20v66smrmt1te2q.png" alt="Image description" width="800" height="550"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Next,&lt;/strong&gt; we just have to use this worker in my polling function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const readFiles = () =&amp;gt; {
  const fileMd5 = await workerRef.current.getFileMd5(fileHandle);
// rest of application logic here to use the files md5
}
setInterval(readFiles, 2000);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  The result:
&lt;/h2&gt;

&lt;p&gt;Now the app is no longer slow, as the main thread is no longer running code to read files &amp;amp; check their md5's.&lt;/p&gt;

&lt;p&gt;🎉🥳🎉🥳&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>performance</category>
    </item>
    <item>
      <title>Get a head start with badass hardhat workflow</title>
      <dc:creator>Mister Singh</dc:creator>
      <pubDate>Mon, 21 Nov 2022 04:49:28 +0000</pubDate>
      <link>https://dev.to/mistersingh179/get-a-head-start-with-badass-hardhat-workflow-5hnd</link>
      <guid>https://dev.to/mistersingh179/get-a-head-start-with-badass-hardhat-workflow-5hnd</guid>
      <description>&lt;p&gt;In this article I will first show you what a badass hardhat setup looks like and then second I will teach you so you can have the same.&lt;/p&gt;

&lt;h2&gt;
  
  
  The 5 things a badass hardhat setup has:
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Auto compile &amp;amp; deployment of code in development&lt;/li&gt;
&lt;li&gt;Auto builds &amp;amp; maintains a file with every contracts address &amp;amp; abi.&lt;/li&gt;
&lt;li&gt;A generic UI for your contracts, which hot reloads as contract code changes.&lt;/li&gt;
&lt;li&gt;A single command to deploy contracts to testnet &amp;amp; mainnet&lt;/li&gt;
&lt;li&gt;A single command to verify contracts.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Now, let's take a look  at this setup IRL:
&lt;/h2&gt;

&lt;p&gt;&lt;iframe width="710" height="399" src="https://www.youtube.com/embed/LA2EZPCyLZI"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/mistersingh179/badass-hardhat-setup"&gt;The code for this badass hardhat setup is here.&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Here are the steps for you to have this same setup:
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Clone this repo &amp;amp; install dependencies
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;git clone https://github.com/mistersingh179/badass-hardhat-setup
npm i
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Then in a terminal window run the hardhat chain locally
&lt;code&gt;npm run chain&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;Next, in another terminal window run the deployment script
&lt;code&gt;npm run deploy&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;That's it. You should now have your chain running locally and code deploying to it in real-time.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Let's test our setup.
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Open your favorite IDE and you should see &lt;code&gt;*.sol&lt;/code&gt; files in the contracts directory.&lt;/li&gt;
&lt;li&gt;There should also be a file called &lt;code&gt;contract-addresses.json&lt;/code&gt;being auto built everytime you change code.&lt;/li&gt;
&lt;li&gt;Go ahead, change the code in the IDE and you should see in terminal that it is auto deploying and the &lt;code&gt;contract-addresses.json&lt;/code&gt; has been updated.&lt;/li&gt;
&lt;li&gt;For a UI, browse to &lt;a href="https://app.sidekick.xyz"&gt;sidekick.xyz&lt;/a&gt;, upload &lt;code&gt;contract-addresses.json&lt;/code&gt; and press continue. You should have a UI for your contracts.&lt;/li&gt;
&lt;li&gt;Make changes to your contracts now, you should see them also being updated in UI.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Deploy to testnet &amp;amp; mainnet
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;When you are ready to deploy your code run npm run deploy-goerli or npm run deploy-mainnet&lt;/li&gt;
&lt;li&gt;Then to verify the contracts do &lt;code&gt;npm run verify-goerli&lt;/code&gt; or &lt;code&gt;npm run verify-mainnet&lt;/code&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Writing new contracts
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;To add a new contract, just add a &lt;code&gt;*.sol&lt;/code&gt; file in the contracts directory.&lt;/li&gt;
&lt;li&gt;Then add a deployment script for that contract in deploy directory. Copy paste existing deployment scripts and just change the contract name. This way it is less prone to errors.&lt;/li&gt;
&lt;li&gt;The contract should get auto-deployed now.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This is it. You too now have a badass hardhat setup. 🥳🎉&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;FYI&lt;/strong&gt; – In case you want to see how all this is setup, just take look at the hardhat.config.js file and read the documentation of hardhat &amp;amp; its plugin hardhat-deploy&lt;/p&gt;

</description>
      <category>hardhat</category>
      <category>web3</category>
      <category>solidity</category>
      <category>programming</category>
    </item>
    <item>
      <title>Rails like scope methods in Objection.js (NodeJS ORM)</title>
      <dc:creator>Mister Singh</dc:creator>
      <pubDate>Tue, 10 Mar 2020 02:54:41 +0000</pubDate>
      <link>https://dev.to/mistersingh179/rails-like-scope-methods-in-objection-js-nodejs-orm-dgj</link>
      <guid>https://dev.to/mistersingh179/rails-like-scope-methods-in-objection-js-nodejs-orm-dgj</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--HYqE1Jzx--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://miro.medium.com/max/832/1%2AxoIcN0IG7F9EV4IJIxb4ag.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--HYqE1Jzx--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://miro.medium.com/max/832/1%2AxoIcN0IG7F9EV4IJIxb4ag.png" alt="Objection.js (NodeJS ORM)"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let say we have a model called &lt;code&gt;Label&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const { Model } = require('objection')
class Label extends Model {
    static get tableName() {
        return "labels"
    }
    static get jsonSchema () {
        return {
            type: 'object',
            required: [],
            properties: {
                id: { type: 'integer' },
                name: { type: 'string' }
            }
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Now we want to get the last Label in the model.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const label = await Label.query().orderby('id', 'desc').limit(1).first()
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Although this gets us the last label, it has a few shortcomings:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;It is verbose&lt;/li&gt;
&lt;li&gt;It requires too much repeated typing and thus prone to errors&lt;/li&gt;
&lt;li&gt;Its harder to test&lt;/li&gt;
&lt;li&gt;It doesn't read well&lt;/li&gt;
&lt;li&gt;And things only get worse when its used in conjunction with other methods&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Here are 3 ways to approach this:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Modifiers&lt;/li&gt;
&lt;li&gt;A Regular Class Method&lt;/li&gt;
&lt;li&gt;Custom QueryBuilder Object&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Lets dive into each of these one-by-one. &lt;/p&gt;

&lt;h2&gt;
  
  
  Approach 1: Modifiers
&lt;/h2&gt;

&lt;p&gt;Modifiers is my preferred way to solve this. We specify a function on the modifiers object which:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;receives the &lt;code&gt;query&lt;/code&gt; as a param&lt;/li&gt;
&lt;li&gt;it then modifies the query by adding its filters etc.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Label.modifiers.last = query =&amp;gt; {
    query.orderby('id', 'desc').limit(1).first()
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Now lets get the last record by using this modifier&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const label = await Label.query().modify('last')
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;This reads so much better, encapsulates all logic under one function and we can test that one function easily.&lt;/p&gt;

&lt;p&gt;The logs show that it ran:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;select "labels".* from "labels" order by "id" DESC limit 1
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h3&gt;
  
  
  With params
&lt;/h3&gt;

&lt;p&gt;Lets build another modifier which gets all labels which start with the passed in letters&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Label.modifiers.startsWith = (query, letters) =&amp;gt; {
    query.where('name', 'like', `${letters}%`)
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Now lets run it&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;labels = await Label.query().modify('startsWith', 'XYYZ')
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;And logs show:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;select "labels".* from "labels" where "name" like "AC%"
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h3&gt;
  
  
  Combining multiple modifier functions
&lt;/h3&gt;

&lt;p&gt;This is where i think modifier functions start to shine, just like scopes do in Rails.&lt;/p&gt;

&lt;p&gt;So lets say we need the last label which starts with 'A'. We can achieve this by using our &lt;code&gt;startsWith&lt;/code&gt; &amp;amp; &lt;code&gt;last&lt;/code&gt; modifier functions together.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const label = await Label.query().modify('startsWith','A').modify('last') 
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;And our logs have:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;select "labels".* from "labels" where "name" like "A%" order by "id" DESC limit 1
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h2&gt;
  
  
  Approach 2: Class method on Label
&lt;/h2&gt;

&lt;p&gt;A regular static method on Label class. We can have this method return the last record:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Label.last = () =&amp;gt; {
    return await Label.orderby('id', 'desc').limit(1).first()
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;This gets the job done, but not as good as a modifier function. Yes it reads good and encapsulates the work but it doesn't return the query object and thus can't be chained&lt;/p&gt;

&lt;h2&gt;
  
  
  Approach 3: Custom QueryBuilder
&lt;/h2&gt;

&lt;p&gt;We can build our custom query object and have label class use our query object. On our custom query object we can define a custom methods which modify the  &lt;code&gt;query()&lt;/code&gt; object directly.&lt;/p&gt;

&lt;p&gt;This will allow us to modify the query by calling an internal method of the query object, without writing the words &lt;code&gt;modify&lt;/code&gt; and explicitly making it clear that we are modifying the query.&lt;/p&gt;

&lt;p&gt;Lets see an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class MyQueryBuilder extends QueryBuilder {
  last () {
    logger.info('inside last')
    this.orderBy('id', 'desc').limit(1).first()
    return this
  }
}

class Label exteds Model {
    static get QueryBuilder () {
        return MyQueryBuilder
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Now to use it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cons label = await Label.query().last()
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;I think this approach is an abuse of power. It works, but we have a cleaner way of modifying the query and we should do that instead of defining a custom query object which has special internal methods. &lt;/p&gt;

&lt;p&gt;I think this custom query class might have good use cases though for other things like logging, making some other service calls etc.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;modifiers&lt;/code&gt; are great. the ability to chain them make them an asset.&lt;/p&gt;

&lt;h2&gt;
  
  
  What's Next
&lt;/h2&gt;

&lt;p&gt;Use modifiers with complex queries which use:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;join&lt;/li&gt;
&lt;li&gt;graphFetch (eager loading)&lt;/li&gt;
&lt;li&gt;use &lt;code&gt;ref&lt;/code&gt; where we have ambiguous table names&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>node</category>
      <category>javascript</category>
      <category>orm</category>
      <category>rails</category>
    </item>
  </channel>
</rss>
