<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Swapnil S on Medium]]></title>
        <description><![CDATA[Stories by Swapnil S on Medium]]></description>
        <link>https://medium.com/@swapnilsuman65?source=rss-2ffd6033becf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*-cvykw1pc7HXX5yC</url>
            <title>Stories by Swapnil S on Medium</title>
            <link>https://medium.com/@swapnilsuman65?source=rss-2ffd6033becf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 03:34:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@swapnilsuman65/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Justice is Fluid]]></title>
            <link>https://medium.com/@swapnilsuman65/justice-is-fluid-90269543fdd5?source=rss-2ffd6033becf------2</link>
            <guid isPermaLink="false">https://medium.com/p/90269543fdd5</guid>
            <dc:creator><![CDATA[Swapnil S]]></dc:creator>
            <pubDate>Mon, 16 Mar 2026 19:58:55 GMT</pubDate>
            <atom:updated>2026-03-16T19:58:55.301Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Note:</em> <em>This article was originally published on Mon Jan 22 2024 on a self-hosted blogging platform and has been migrated to Medium with the help of Comet AI.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*itn4T7C91M6m3zsVoqmRSw.jpeg" /></figure><p>How justice adapts to cultural changes, ethical challenges, and diverse viewpoints, advocating for embracing its fluidity towards a more equitable world.</p><p>The concept of justice has long been a cornerstone of human society, serving as a guiding principle for maintaining order and fairness. However, in a world marked by diverse perspectives and evolving values, the notion of justice is far from static. In this blog, we embark on a thought-provoking exploration of how justice is fluid, adapting to societal changes, cultural shifts, and ethical dilemmas.</p><h3>The Shifting Sands of Morality</h3><p>The idea that justice is fluid stems from the realization that what is considered just in one context or era may not hold true in another. Moral standards evolve over time, reflecting changes in societal norms, technological advancements, and a deeper understanding of human rights. As a result, what may have been accepted as fair and just in the past may be reevaluated in light of new information and perspectives.</p><h3>Cultural Relativism and Justice</h3><p>Cultural diversity adds another layer of complexity to the fluidity of justice. Different societies and cultures hold distinct beliefs and values, often leading to varying interpretations of what constitutes justice. Cultural relativism challenges us to question whether there can be a universal standard of justice or if justice is inherently tied to the cultural context in which it is applied.</p><h3>The Intersection of Law and Ethics</h3><p>The legal system often serves as a formal framework for administering justice, but it too is subject to change and reinterpretation. Laws are shaped by societal norms, political agendas, and evolving ethical standards. The fluidity of justice becomes evident as legal codes are revised to reflect shifts in public opinion and to address new ethical challenges, such as advancements in technology or debates over individual liberties.</p><h3>Social Justice and Activism</h3><p>The pursuit of social justice highlights the dynamic nature of justice itself. Movements advocating for equality, inclusivity, and the protection of marginalised groups illustrate how justice is a constantly evolving concept. Activism brings attention to systemic injustices and prompts society to reexamine existing structures in order to create a more equitable future.</p><h3>Ethical Dilemmas and Decision-Making</h3><p>Ethical quandaries often require us to grapple with the fluid nature of justice. Situations that involve conflicting rights, interests, or values force us to consider the balance between individual autonomy and the greater good. As we make difficult decisions, we must navigate the ever-changing landscape of justice, taking into account both immediate consequences and long-term societal impact.</p><h3>Conclusion</h3><p>In a world marked by cultural diversity, technological progress, and evolving values, the concept of justice is undeniably fluid. It adapts to the shifting sands of morality, transforming to address new challenges and insights. As individuals and societies, we are tasked with the responsibility of continually reevaluating our understanding of justice, staying open to new perspectives, and working towards a more just and equitable world. Embracing the fluidity of justice invites us to engage in meaningful dialogues, challenge our assumptions, and participate in shaping a future where fairness and equality prevail.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90269543fdd5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Beautiful Spiti Valley!]]></title>
            <link>https://medium.com/@swapnilsuman65/the-beautiful-spiti-valley-da7149cd1dc8?source=rss-2ffd6033becf------2</link>
            <guid isPermaLink="false">https://medium.com/p/da7149cd1dc8</guid>
            <category><![CDATA[india]]></category>
            <category><![CDATA[spiti-valley]]></category>
            <category><![CDATA[travel]]></category>
            <category><![CDATA[camping]]></category>
            <dc:creator><![CDATA[Swapnil S]]></dc:creator>
            <pubDate>Mon, 16 Mar 2026 18:45:40 GMT</pubDate>
            <atom:updated>2026-03-16T18:45:40.302Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Note:</em> <em>This article was originally published on Mon Jan 22 2024 on a self-hosted blogging platform and has been migrated to Medium with the help of Comet AI.</em></p><p>Spiti Valley really came in as a huge surprise. I am guilty of keeping my expectations low. In a span of 7 days, my homies and I embarked on a 800km road journey from Delhi, driving through picturesque landscapes, camping under the starlit skies, and immersing ourselves in the serenity that Spiti Valley had to offer. In the following section, I will try to convince you to do the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3IP6jiSc7-_MUwhBJl-tXA.jpeg" /></figure><h4>What I like about Himachal Pradesh</h4><p>I have been to quite a few of mountains from Uttarakhand to Sikkim to Nepal.<br>What I felt in Uttarakhand was everything was really really far. So travelling consumes a lot of time and money. Nepal could easily scare even daring people. No Safety barriers and extremely steep mountains. Sikkim is good but everything requires a permission due to border security reasons. We camped at literally anywhere we liked and we were not bothered by anyone. Only once in our 7 day trip we took a hotel.</p><h3>People are beyond hospitable in HP</h3><p>People will smile at you for no reason and you can feel the positive energy. One of my friends Jatin from Gurugram was overwhelmed on seeing this. (A Rare sight in Gurugram I guess). He went on talking randomly with aunties in Gue as they would laugh at literally everything. Also, one of our group member is an army martyred son, so we got an invite for a breakfast with the army at the gue base camp.</p><h3>Camping and Cooking under the stars is beyond mesmerising</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*brFwvRaGZJS79KhOlUiGEQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7JaDtiWDCNoxuiT8zpop4w.jpeg" /></figure><p>We had carried raw items for cooking with us from Delhi. On the way we bought other raw items such as chicken as required. Cooked dinner under the stars with a bon fire and everyone dancing to the music playing was the best part of the whole trip for me. Our tasks were divided as driving, pitching tent, cooking, washing utensils etc. So you will need a good team to pull off the camping thing. Or you could pay the locals for camping but thats not fun trust me.</p><p>Its not like any other high altitude mountain district</p><p>If you didn’t know already the Spiti district of Himachal Pradesh is a cold desert. So there’s no vegetation around in summer and for winters its snow ridden. So the visuals are very very different from other places. The roads can vary from very curvy to straights, from flat to very steep. The views are phenomenal. If you are lucky enough you might spot a snow leopard as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FSsH05JMCts5i6kwu3x6aA.jpeg" /></figure><p><em>Few tips I would like to share</em></p><p>1. LPG doesn’t freeze till -10°C (tried and tested). Manufactured myth to boost butane sales.<br>2. Carry an axe for cutting down woods from jungle for fire<br>3. Throw leftovers from dinner far away from your camp as it attracts animals.<br>4. Keep strong people in team not cry babies<br>5. LPG might be stopped in Atal Tunnel<br>6. Don’t send letters from Hikkim. None of ours reached. Instead write and bring it to the person yourself like one of our friends did lol<br>7. Skip Nako Lake its not worth it</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da7149cd1dc8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Random technical things I learned while writing backends for the last 1.5+ years.]]></title>
            <link>https://medium.com/@swapnilsuman65/random-technical-things-i-learned-while-writing-backends-for-the-last-1-5-years-e1a57a1b4917?source=rss-2ffd6033becf------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1a57a1b4917</guid>
            <category><![CDATA[backend-engineering]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Swapnil S]]></dc:creator>
            <pubDate>Thu, 05 Feb 2026 22:59:41 GMT</pubDate>
            <atom:updated>2026-02-05T22:59:41.717Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ML9eNXi7_8IWi0ZgHY2tvg.jpeg" /></figure><p>I have been very busy with work lately and was away from writing blogs for quite some time now. However, I was scribbling down things whenever I felt I should have known this already or when I had a eureka moment at work, i.e., when what I believed about how something works (or should work) turned out to be absolutely false.</p><ol><li><strong>Do not let the database (or an ORM) auto-generate names (for indices, constraints, etc).</strong></li></ol><blockquote>We want to keep things similar on the dev, staging, and prod branches so that the behavior of migrations is predictable. I have written a whole blog on this. Check my previous blog.</blockquote><p><strong>2. Singleton behavior across environments</strong></p><p>We have all read the definition of a singleton class, something along the lines of <em>“A </em><strong><em>singleton</em></strong><em> means only </em><strong><em>one instance of a class</em></strong><em> is created and reused every time it’s needed.”</em><br>But in reality, the <em>meaning of “one instance”</em> depends on how the backend runtime works. See, the thing is there are two kinds of backend environments (mainly).</p><blockquote>long-running environments (Example: Node.js / NestJS / Java Spring) — Here, the server starts once and stays alive, so singleton objects stay in memory and are reused every time (just as expected).</blockquote><blockquote>In request-based environments (Example: Laravel / PHP) — Here, each HTTP request starts a fresh execution. So, Singleton exists only during that request, and after the response is sent, memory is cleared.</blockquote><blockquote>Note: there are some other kinds of environments as well, which you can read for yourself. Keywords are multi-worker server runtime and actor-based runtime. Also, NestJS is pretty cool in providing very easy ways to be able to make use of the best of both. So try using it sometime.</blockquote><p><strong>3.</strong> I realized this one too late, but <strong>observers, event emitter-listeners, and publisher-subscribers are all the same thing.</strong></p><blockquote>The idea is one will act and the other will react. ‘Observers’ is usually used in the context of ORMs where we are listening for db events. ‘Event Emitter’ is used where we (the programmers) define an event. (e.g., an image upload just finished), and ‘Pub-Sub’ is the same as an event emitter but at a large scale, where the emitter and listeners are probably on different machines talking to each other over a network.</blockquote><p>4. I hate to admit it, but I really thought CORS policy was to protect my backend from bad actors, but actually <strong>CORS policy is for the protection of client-side machines.</strong></p><blockquote><em>Problem:</em> Browsers store session variables by domain. This means multiple tabs opened of the same website (bank.com) would share session variables. Now any requests being made to this website in any of the tabs, the browser automatically attaches all the latest session variables. Here’s the catch now: assume a website (evil.com) triggers an XHR request to bank.com from your machine. The browser would again attach the same session variables, and the bank would process the request. Note that Evil.com did not itself read the variables, but it just caused your browser to use them. Congrats, you have now understood Cross-Site Request Forgery Attacks (CSRF).</blockquote><blockquote>Solution: CORS attaches the “host:evil.com” key-value pair header in the request. This is similar to a browser saying to a server, ‘Hey, this request is coming from evil.com.’ .” The server sends a response about the CORS policy, saying who all are allowed to read the response I am sending. So this does not prevent evil.com from sending that request, but instead it prevents evil.com from reading the response of the server.</blockquote><blockquote>But how does the server know whether the request is from the server or the browser? It doesn’t — not reliably. CORS is based on <strong>trust</strong>, not verification. Even the browser can break these norms if it decides to. Like it can decide to be a bad actor and tell it the responses of bank.com no matter what the server says.</blockquote><p>5. <strong>STOP using booleans in DB. </strong>Trust me, they almost never make sense.</p><blockquote>You ll often find people using it in db column names like is_approved.By doing this you are missing out on storing some extra info. Instead replace it with Datetime and name the columns as approved_at (nullable). If null, it is not approved; else, you get extra info on when it was approved.</blockquote><blockquote><em>Other examples could be storing </em><em>is_adminin db. Just replace it with enums so when you define more roles and permissions. You don’t have to update half of the codebase.</em></blockquote><p>6. <strong>JWT refresh tokens are supposed to be stored in db (with corresponding user details)</strong></p><blockquote>Have you ever thought, “Why do we send refresh tokens during login when we can just send the JWT token with a longer expiry (as clients are going to refresh and get new ones anyways? )” Well, this is because JWT tokens, due to their stateless nature, have an issue; the refresh token thing is just a workaround for it. The issue is that there is no way to force logout a user. Yes, think of it. Once a bad actor has that JWT token, he can keep sending requests until that expiry is reached. So what we do is we give the JWT tokens a very short expiry (~5 mins) and the refresh token a long expiry (~1 week). We store the refresh token in the db. On each refresh token request, we validate if that request token is allowed to do so. Now imagine we somehow detected that it was a bad actor, or we just want to force logout users after some changes to the system. We just expire/remove all the stored refresh tokens in the DB. When the bad actor/user tries to refresh, now they are forced to log out. The idea is they get the access for at most 5 mins once we have detected an intrusion.</blockquote><p>Since the blog is already quite big, I’ll stop here for now, but I’ve already scribbled down many more such learnings. Comment if you want them sooner (I am going to write about them anyways :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1a57a1b4917" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[ FIX ] TypeORM not detecting changes in constraints]]></title>
            <link>https://medium.com/@swapnilsuman65/fix-typeorm-not-detecting-changes-in-constraints-40d41c80a6b3?source=rss-2ffd6033becf------2</link>
            <guid isPermaLink="false">https://medium.com/p/40d41c80a6b3</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[migration]]></category>
            <category><![CDATA[typeorm]]></category>
            <category><![CDATA[constraints]]></category>
            <category><![CDATA[naming]]></category>
            <dc:creator><![CDATA[Swapnil S]]></dc:creator>
            <pubDate>Sun, 06 Jul 2025 12:52:26 GMT</pubDate>
            <atom:updated>2025-07-06T12:58:23.585Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve worked with <a href="https://typeorm.io/">TypeORM</a> long enough, you’ve probably hit this frustrating wall: <strong>you change a foreign key’s cascading rule (like </strong><strong>onDelete or </strong><strong>onUpdate) and run </strong><strong>typeorm migration:generate — but nothing happens.</strong></p><p>The migration file is empty, and you’re left wondering if you did something wrong. Spoiler: you didn’t. It’s a known limitation in how TypeORM compares schema differences.</p><p>But there’s a simple, clean solution — and it also improves CI/CD reliability: <strong>custom naming strategy + disabling auto-generated DB constraint names.</strong></p><h3>🔍 The Problem</h3><p>TypeORM relies on introspecting your current schema and comparing it to what’s defined in your entity metadata. However, when foreign key rules like ON DELETE CASCADE change, <strong>TypeORM often doesn’t recognize the change as a diff</strong> — especially when constraint names are auto-generated by the database.</p><p>This is particularly problematic because these rules matter for data integrity and app behavior, yet you may never know the migration didn’t apply unless you inspect the DB directly.</p><h3>✅ The Solution</h3><p><strong>Define a custom naming strategy</strong> in your TypeORM configuration, and ensure <strong>all foreign key constraints have predictable, consistent names.</strong> This ensures:</p><ul><li>TypeORM can <strong>detect differences</strong> between entity metadata and DB schema.</li><li>You get <strong>consistent naming across environments</strong> (e.g., dev, staging, production).</li><li>Your <strong>CI/CD pipelines</strong> become more stable and predictable.</li></ul><h3>🛠️ Implementation</h3><p>Here’s how you can do it:</p><ol><li><strong>Create a custom naming strategy file</strong></li></ol><p><em>source:</em> <a href="https://dev.to/emtiajium/a-journey-to-simplify-debugging-automate-generating-human-friendly-database-constraints-using-typeorm-kap"><em>https://dev.to/emtiajium/a-journey-to-simplify-debugging-automate-generating-human-friendly-database-constraints-using-typeorm-kap</em></a></p><pre>// naming-strategy.ts<br>import { DefaultNamingStrategy, Table } from &#39;typeorm&#39;;<br><br>export class DatabaseNamingStrategy extends DefaultNamingStrategy {<br>  primaryKeyName(tableOrName: Table | string, columnNames: string[]): string {<br>    return `PK_${this.getTableName(tableOrName)}_${this.joinColumns(columnNames)}`;<br>  }<br><br>  private joinColumns(columnNames: string[]): string {<br>    return columnNames.join(&#39;_&#39;);<br>  }<br><br>  uniqueConstraintName(<br>    tableOrName: Table | string,<br>    columnNames: string[],<br>  ): string {<br>    return `UQ_${this.getTableName(tableOrName)}_${this.joinColumns(columnNames)}`;<br>  }<br><br>  foreignKeyName(<br>    referencingTableOrName: Table | string,<br>    referencingColumnNames: string[],<br>    referencedTablePath?: string,<br>    referencedColumnNames?: string[],<br>  ): string {<br>    const referencingTableName = this.getTableName(referencingTableOrName);<br><br>    const referencingReferencedGroup = referencingColumnNames.map(<br>      (referencingColumn, index) =&gt; {<br>        return `${referencingTableName}_${referencingColumn}_${referencedTablePath}_${referencedColumnNames[index]}`;<br>      },<br>    );<br><br>    return `FK_${referencingReferencedGroup.join(&#39;_&#39;)}`;<br>  }<br><br>  indexName(<br>    tableOrName: Table | string,<br>    columnNames: string[],<br>    where?: string,<br>  ): string {<br>    let indexName = `IDX_${this.getTableName(tableOrName)}_${this.joinColumns(columnNames)}`;<br><br>    if (where) {<br>      const suffix = this.getPartialIndexNameSuffix(<br>        tableOrName,<br>        columnNames,<br>        where,<br>      );<br>      indexName = `${indexName}_${suffix}`;<br>    }<br><br>    return indexName;<br>  }<br>  private getPartialIndexNameSuffix(<br>    tableOrName: Table | string,<br>    columnNames: string[],<br>    where: string,<br>  ): string {<br>    const whereClauseMap: Record&lt;string, string&gt; = {<br>      &#39;&quot;deletedAt&quot; IS NULL&#39;: `deletedAt_IS_NULL`,<br>    };<br><br>    if (whereClauseMap[where]) {<br>      return `WHERE_${whereClauseMap[where]}`;<br>    }<br><br>    const generatedIndexName = super.indexName(tableOrName, columnNames, where);<br>    const { 1: hash } = generatedIndexName.split(&#39;IDX_&#39;);<br><br>    return `WHERE_${hash}`;<br>  }<br>}</pre><p><strong>2. Update your </strong><strong>DataSource to use the naming strategy</strong></p><blockquote>pass a new instance of DatabaseNamingStrategy to the typeorm config.</blockquote><pre>import &#39;dotenv/config&#39;;<br>import path from &#39;path&#39;;<br>import &#39;reflect-metadata&#39;;<br>import { DataSource, DataSourceOptions } from &#39;typeorm&#39;;<br>import { DatabaseNmingStrategy } from &#39;./naming-strategy&#39;;<br>const resolvePath = (pattern: string) =&gt; {<br>  const isProd = process.env.ENV === &#39;production&#39;;<br><br>  return path.join(__dirname, isProd ? `${pattern}.js` : `${pattern}.ts`);<br>};<br><br>export const AppDataSource = new DataSource({<br>  type: &#39;postgres&#39;,<br>  url: process.env.DATABASE_URL,<br>  host: process.env.DATABASE_HOST || &#39;localhost&#39;,<br>  port: process.env.DATABASE_PORT<br>    ? parseInt(process.env.DATABASE_PORT, 10)<br>    : 5432,<br>  username: process.env.POSTGRES_USER || &#39;root&#39;,<br>  password: process.env.POSTGRES_PASSWORD || &#39;password@root&#39;,<br>  database: process.env.POSTGRES_DB || &#39;postgres&#39;,<br>  synchronize: process.env.DATABASE_SYNCHRONIZE === &#39;true&#39;,<br>  dropSchema: false,<br>  keepConnectionAlive: true,<br>  logging: false,<br>  entities: [resolvePath(&#39;../**/*.entity&#39;)],<br>  migrations: [resolvePath(&#39;migrations/**/*&#39;), resolvePath(&#39;rls-policy&#39;)],<br>  cli: {<br>    entitiesDir: &#39;src&#39;,<br>    migrationsDir: path.join(__dirname, &#39;migrations&#39;),<br>    subscribersDir: &#39;subscriber&#39;,<br>  },<br>  extra: {<br>    // based on https://node-postgres.com/api/pool<br>    // max connection pool size<br>    max: process.env.DATABASE_MAX_CONNECTIONS<br>      ? parseInt(process.env.DATABASE_MAX_CONNECTIONS, 10)<br>      : 100,<br>    ssl:<br>      process.env.DATABASE_SSL_ENABLED === &#39;true&#39;<br>        ? {<br>            rejectUnauthorized:<br>              process.env.DATABASE_REJECT_UNAUTHORIZED === &#39;true&#39;,<br>            ca: process.env.DATABASE_CA ?? undefined,<br>            key: process.env.DATABASE_KEY ?? undefined,<br>            cert: process.env.DATABASE_CERT ?? undefined,<br>          }<br>        : undefined,<br>  },<br>  namingStrategy: new DatabaseNamingStrategy(), // &lt;-- add this line<br>} as DataSourceOptions);</pre><p>3. DONE !! now when you generate the migrations you’ll see that typeorm now detects cascading rule changes and also generate migrations to change the constraint names.</p><p>You can also check the constraint names using this query ( postgres only )</p><pre>SELECT<br>    con.conname AS constraint_name,<br>    con.contype AS constraint_type,<br>    rel.relname AS table_name,<br>    att.attname AS column_name,<br>    nsp.nspname AS schema_name<br>FROM<br>    pg_constraint con<br>JOIN<br>    pg_class rel ON rel.oid = con.conrelid<br>JOIN<br>    pg_namespace nsp ON nsp.oid = rel.relnamespace<br>JOIN<br>    LATERAL unnest(con.conkey) AS colnum(attnum) ON true<br>JOIN<br>    pg_attribute att ON att.attrelid = rel.oid AND att.attnum = colnum.attnum<br>WHERE<br>    nsp.nspname NOT IN (&#39;pg_catalog&#39;, &#39;information_schema&#39;)<br>ORDER BY<br>    nsp.nspname, rel.relname, con.conname LIMIT 100</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NJXm86dBzMjdM2MEM4ZRkQ.png" /><figcaption>constraint names after using naming strategy</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40d41c80a6b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generate PDFs dynamically in NodeJs/NestJs]]></title>
            <link>https://medium.com/@swapnilsuman65/generate-pdfs-dynamically-in-nodejs-nestjs-398fe3617a4a?source=rss-2ffd6033becf------2</link>
            <guid isPermaLink="false">https://medium.com/p/398fe3617a4a</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[pdf-generation]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[Swapnil S]]></dc:creator>
            <pubDate>Wed, 17 Apr 2024 05:25:29 GMT</pubDate>
            <atom:updated>2024-04-17T06:03:04.077Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*ydHZuujz7gr4-VoC.jpg" /></figure><p>During my internship, I was given a task to figure out how we could dynamically generate PDFs in the backend. I was informed that the frontend team already tried and failed. My first thought was this seems a very normal use case and a lot of libraries must exist. But looks like I was wrong.</p><p>These were the things which I was told should be dynamically generated in the pdf : <br>-&gt; <strong>Graphs &amp; Charts</strong><br>-&gt; <strong>Tables</strong><br>-&gt; <strong>Add Images</strong><br>-&gt; <strong>Generate TOC (Table of Contents) and Automatic Page numbers</strong></p><p>I went on &amp; tried multiple libraries (pdfkit etc). All of them had problems. They did not have simplest features that you would expect from a PDF generation library.<br> <br>My final choice was <a href="https://www.npmjs.com/package/jspdf"><strong>jsPDF</strong></a>. Thats because of two things :</p><p>1. One just does not write only text in a PDF (saying bcz other lib lacked so much)<br>2. It has an extension library called <a href="https://www.npmjs.com/package/jspdf-autotable"><strong>jspdf-autotable</strong></a> which lets you generate actual tables (and not add image of a table in the pdf)</p><p>Add the following libraries using yarn/npm.</p><pre>yarn add jspdf @types/jspdf tjspdf-autotable canvas</pre><p>IF CANVAS INSTALL FAILS: <br>canvas was throwing some errors during installation.I googled and found out that there are some compatibility issues for canvas with M-series Apple chips. The solution : Build from source. Read the <a href="https://www.npmjs.com/package/canvas"><strong>doc</strong></a> on how you can build from source.Also, canvas was not able to detect puppeteer path correctly. So I had to make changes for it as well. For me i was using docker and after some tinkering around i was able to build from source like this :</p><pre><br>...<br><br># Install necessary system dependencies for canvas compilation<br>RUN apt-get update &amp;&amp; \<br>    apt-get install -y \<br>        build-essential \<br>        libcairo2-dev \<br>        libpango1.0-dev \<br>        libjpeg-dev \<br>        libgif-dev \<br>        librsvg2-dev \<br>        python3 \<br>        python3-pip \<br>        chromium \<br>        git &amp;&amp; \<br>    rm -rf /var/lib/apt/lists/*<br><br># Check if setuptools is installed for Python<br>RUN pip3 show setuptools || true<br><br># Install setuptools if not already installed<br>RUN apt-get install python3-setuptools<br><br>ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD true<br>ENV CHROMIUM_PATH /usr/bin/chromium<br><br>...</pre><p>The following code is of NestJs and should be easily replicable in any NodeJs Environment</p><pre>// pdf.module.ts <br><br>import { Module } from &#39;@nestjs/common&#39;;<br>import { PdfService } from &#39;./pdf.service&#39;;<br><br>@Module({<br>  providers: [PdfService],<br>  exports: [PdfService],<br>})<br>export class PdfModule {}</pre><p>Brief Explanation of everything thats happening:<br>1. We keep track of the pointer manually.<br>2. Altho I have hardcoded margins , You can easily make them dynamic<br>3. When the client requests on GET /pdf route, All the details of his org are fetched from a DB and a report is generated.<br>4. The PDF is generated, saved, sent to the client and then deleted from memory.</p><pre>// pdf.interface.ts<br><br>import { TextOptionsLight } from &#39;jspdf&#39;;<br>import { UserOptions } from &#39;jspdf-autotable&#39;;<br><br>export interface index {<br>  Index: string;<br>  Page: number;<br>}<br><br>export interface TableOptions extends UserOptions {<br>  ignoreFields?: string[];<br>  tableName: string;<br>  addToIndex?: boolean;<br>}<br><br>export interface TextOptions extends TextOptionsLight {<br>  x?: number;<br>  y?: number;<br>  addToIndex?: boolean;<br>}</pre><p>Function &amp; Instance Variables definition:<br>-&gt; <strong>xMargin, yMargin</strong> : Horizontal &amp; Vertical Margin Respectively<br>-&gt; <strong>indexData</strong> : saves info about things to be added to TOC<br>-&gt; <strong>x, y</strong> : current pointer coordinates in the 2d sheet</p><ul><li><strong>updatePointer(): </strong>After adding each thing ( text, image etc) we move the pointer to correct new location (i.e to new x and y).</li><li><strong>addNewPage()</strong>: adds a new page in pdf and moves the pointer to start of margins.</li><li><strong>addImage(imageData: Buffer, options?: any): </strong>takes an image as a buffer and adds it to pdf. Can be Resized using options. Default is taking up whole width &amp; height of pdf. Exact position of image can also be specified using options.x and options.y; Default is the current pointer position.</li><li><strong>addGenericTable&lt;T&gt;(dataArr: T[], options: TableOptions): </strong>Takes and array of objects and generates table. TableOptions is interesting. You get three new options other than default ones: <br><em>ignoreFields?</em>: fields that you donot want to be included in the table. For example : I am printing a table of users. I have an array of User obj: User[]. but user also has a password field which i dont want to include in the table. So I ll pass [‘password’] in this field.<br><em>tableName</em>: The name of the table<br><em>addToIndex?</em>: Whether you want this to be mentioned in TOC page.</li><li><strong>addText(text: string, options?: TextOptions) </strong>: Self Explanatory. Options has <em>addToIndex?</em> field similar to addGenericTable()</li><li><strong>addNewLine() : </strong>add new empty Line. May be to change paragraphs.</li><li><strong>render() : </strong>Finish writing the pdf &amp; render it.</li></ul><pre>// pdf.service.ts<br><br>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { TextOptionsLight, jsPDF } from &#39;jspdf&#39;;<br>import autoTable, { UserOptions } from &#39;jspdf-autotable&#39;;<br>import { TableOptions, TextOptions, index } from &#39;./pdf.interface&#39;;<br><br>@Injectable()<br>export class PdfService {<br>  private doc: jsPDF;<br>  private readonly filePath = &#39;./output.pdf&#39;;<br>  private readonly xMargin = 20;<br>  private readonly yMargin = 30;<br>  private indexData: index[] = [];<br>  private x: number<br>  private y: number<br><br>  private defaultTableOptions: TableOptions = {<br>    tableName: &#39;default table name&#39;,<br>    ignoreFields: [],<br>    addToIndex: false,<br>  };<br><br>  constructor() {<br>    this.doc = new jsPDF({ orientation: &#39;p&#39;, unit: &#39;pt&#39;, format: &#39;a4&#39; });<br>    this.resetXandY()<br>    this.updatePointer();<br>  }<br><br>  private resetXandY(){<br>    this.x = this.xMargin<br>    this.y = this.yMargin<br>  }<br><br>  private updatePointer(){<br>    this.doc.moveTo(this.x,this.y)<br>  }<br><br>  async addNewPage() {<br>    this.doc.addPage();<br>    this.resetXandY()<br>    this.updatePointer()<br>  }<br><br>  // Adds image at position (x, y) with width and height<br>  async addImage(imageData: Buffer, options?: any) {<br>    this.doc.addImage(<br>      imageData,<br>      &#39;JPEG&#39;,<br>      options?.x || this.x,<br>      options?.y || this.y,<br>      options?.width || this.doc.internal.pageSize.getWidth(),<br>      options?.height || this.doc.internal.pageSize.getHeight(),<br>    );<br><br>    this.y = options?.height || this.doc.internal.pageSize.getHeight() + this.doc.getLineHeight()<br>    this.updatePointer()<br>  }<br><br>  async addGenericTable&lt;T&gt;(dataArr: T[], options: TableOptions) {<br>    if (dataArr.length === 0) {<br>      console.error(&#39;Data array is empty&#39;);<br>      return;<br>    }<br><br>    const mergedOptions: TableOptions = {<br>      ...this.defaultTableOptions,<br>      ...options,<br>      startY : this.y + this.doc.getLineHeight()<br>    };<br><br>    this.addText(`${mergedOptions.tableName}`);<br><br>    if (mergedOptions.addToIndex) {<br>      this.indexData.push({<br>        Index: mergedOptions.tableName,<br>        Page: this.doc.getCurrentPageInfo().pageNumber,<br>      });<br>    }<br><br>    const headers = Object.keys(dataArr[0]).filter(<br>      (key) =&gt; !mergedOptions.ignoreFields?.includes(key),<br>    );<br><br>    const transformedData = dataArr.map((item: any, index) =&gt;<br>      headers.map((key: string) =&gt;<br>        item[key] instanceof Date ? item[key].toISOString() : item[key],<br>      ),<br>    );<br><br>    autoTable(this.doc, {<br>      head: [headers],<br>      body: transformedData,<br>      didDrawCell: (data) =&gt; {},<br>      ...mergedOptions,<br>    });<br>    this.y = (this.doc as any).lastAutoTable.finalY + this.doc.getLineHeight();<br>    this.updatePointer()<br>  }<br><br>  async addText(text: string, options?: TextOptions) {<br>    const lines = this.doc.splitTextToSize(<br>      text,<br>      this.doc.internal.pageSize.width - this.xMargin * 2,<br>    );<br>    <br>    if(options?.addToIndex){<br>      this.indexData.push({<br>        Index: text,<br>        Page: this.doc.getCurrentPageInfo().pageNumber,<br>      });<br>    }<br><br>    console.log(`posi before writing TEXT &#39;${text}&#39; is ${this.x} &amp; ${this.y}`)<br>    this.doc.text(<br>      lines,<br>      options?.x || this.x,<br>      options?.y || this.y,<br>    );<br>    this.y = this.doc.getTextDimensions(lines).h + this.doc.getLineHeight();<br>    this.updatePointer()<br>  }<br><br>  async addNewLine(){<br>    this.y += this.doc.getLineHeight()<br>    this.x = this.xMargin;<br>    this.updatePointer();<br>  }<br><br>  async render(): Promise&lt;string&gt; {<br>    await this.addPageNumbers();<br>    await this.index();<br>    return new Promise&lt;string&gt;((resolve, reject) =&gt; {<br>      this.doc.save(this.filePath);<br>      resolve(this.filePath);<br>    });<br>  }<br><br>  private async addPageNumbers() {<br>    const pageCount = (this.doc as any).internal.getNumberOfPages(); //Total Page Number<br>    for (let i = 0; i &lt; pageCount; i++) {<br>      this.doc.setPage(i);<br>      const pageCurrent = (this.doc as any).internal.getCurrentPageInfo()<br>        .pageNumber; //Current Page<br>      this.doc.setFontSize(12);<br>      this.doc.text(<br>        &#39;page: &#39; + pageCurrent + &#39;/&#39; + pageCount,<br>        this.xMargin,<br>        this.doc.internal.pageSize.height - this.yMargin/2,<br>      );<br>    }<br>  }<br><br>  private async index() {<br>    this.doc.setPage(2);<br>    this.resetXandY();<br>    this.updatePointer();<br>    await this.addGenericTable(this.indexData, {<br>      tableName: `Table of Contents`,<br>      theme: &#39;grid&#39;,<br>    });<br>  }<br>}</pre><pre>// org.controller.ts (only a part is shown)<br><br>@ApiTags(&#39;Organization&#39;)<br>@UseInterceptors(ClassSerializerInterceptor)<br>@UseGuards(AuthGuard(&#39;jwt&#39;), RolesGuard)<br>@ApiBearerAuth(&#39;jwt&#39;)<br>@Controller(&#39;org&#39;)<br>export class OrgController {<br>  constructor(private readonly orgService: OrgService) {}<br><br>  @Get(&#39;pdf&#39;)<br>  @ApiOperation({ summary: &#39;Mail Reports&#39; })<br>  async generatePdf(@GetOrg() org: Org, @Res() res: Response) {<br>    let filePath: any;<br>    try {<br>      filePath = await this.orgService.createPdfInOneFile(org.id);<br><br>      res.setHeader(&#39;Content-disposition&#39;, &#39;attachment; filename=output.pdf&#39;);<br>      res.setHeader(&#39;Content-type&#39;, &#39;application/pdf&#39;);<br><br>      res.sendFile(filePath, { root: process.cwd() }, (err) =&gt; {<br>        if (err) {<br>          console.error(err);<br>        }<br>        fs.unlinkSync(filePath); // Remove the temporary PDF file<br>      });<br>    } catch (err) {<br>      console.log(&#39;Error generating PDF:&#39;, err);<br>      throw err;<br>    }<br>  }<br>}</pre><pre>//org.service.ts (only a part is shown)<br><br>@Injectable()<br>export class OrgService {<br>  constructor(<br>    @InjectRepository(Org)<br>    private orgRepository: Repository&lt;Org&gt;,<br>    private userService: UserService,<br>    private pdfService: PdfService,<br>    private visualizationService: VisualizationService,<br>  ) {}<br><br>  async createPdfInOneFile(orgId: string): Promise&lt;any&gt; {<br>    const usersData = await this.findAllUsersOfOrg(orgId);<br><br>    const chart = await this.visualizationService.createChart();<br><br>    await this.pdfService.addText(`Heading`);<br>    await this.pdfService.addNewLine(); // Leave an empty Line<br>    await this.pdfService.addText(`SubHeading`);<br>    await this.pdfService.addNewLine();<br><br>    //one page left empty for TOC<br>    await this.pdfService.addNewPage();<br><br>    await this.pdfService.addNewPage();<br>    await this.pdfService.addGenericTable(usersData, {<br>      ignoreFields: [&#39;password&#39;, &#39;otp&#39;, &#39;otpCreatedAt&#39;, &#39;lastPasswordUpdateAt&#39;],<br>      tableName: &#39;Users Table&#39;,<br>      addToIndex: true, //add to TOC<br>      theme: &#39;grid&#39;,<br>    });<br>     <br>    //changed ignoreFields.Table resizes automatically. Look in pdf images<br>    await this.pdfService.addGenericTable(usersData, {<br>      ignoreFields: [&#39;password&#39;, &#39;otp&#39;, &#39;otpCreatedAt&#39;, &#39;lastPasswordUpdateAt&#39;, &#39;createdAt&#39;],<br>      tableName: &#39;Users2 Table&#39;,<br>      addToIndex: true , // add to TOC<br>      theme: &#39;grid&#39;,<br>    });<br><br>    await this.pdfService.addNewPage();<br>    await this.pdfService.addText(`TRAILING PAGE`, {<br>      align: &#39;center&#39;,<br>      <br>    });<br>       this.pdfService.addImage(chart,{width : 200 ,height : 200})<br>    return await this.pdfService.render();<br>  }<br>}</pre><p>Thats it for pdf generation. Now Lets see how we can generate chart as an image and add it to the pdf. I wrote a visualisation service for the same. It uses canvas which uses pupeeter. How it works is it starts a pupeeter instance generates chart &amp; takes a screenshot. I know this sounds clumsy but this is the only way possible as of now.</p><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { createCanvas } from &#39;canvas&#39;;<br>import * as echarts from &#39;echarts&#39;;<br>import puppeteer from &#39;puppeteer&#39;;<br><br>@Injectable()<br>export class VisualizationService {<br>  // Currently I am not using any data to generate chart just harcoded values.<br>  async createChart(data?): Promise&lt;Buffer&gt; {<br>    const echartOption = {<br>      tooltip: {<br>        trigger: &#39;axis&#39;,<br>        axisPointer: {<br>          type: &#39;shadow&#39;,<br>        },<br>      },<br>      grid: {<br>        left: &#39;3%&#39;,<br>        right: &#39;4%&#39;,<br>        bottom: &#39;3%&#39;,<br>        containLabel: true,<br>      },<br>      xAxis: [<br>        {<br>          type: &#39;category&#39;,<br>          data: [&#39;Mon&#39;, &#39;Tue&#39;, &#39;Wed&#39;, &#39;Thu&#39;, &#39;Fri&#39;, &#39;Sat&#39;, &#39;Sun&#39;],<br>          axisTick: {<br>            alignWithLabel: true,<br>          },<br>        },<br>      ],<br>      yAxis: [<br>        {<br>          type: &#39;value&#39;,<br>        },<br>      ],<br>      series: [<br>        {<br>          name: &#39;Direct&#39;,<br>          type: &#39;bar&#39;,<br>          barWidth: &#39;60%&#39;,<br>          data: [10, 52, 200, 334, 390, 330, 220],<br>        },<br>      ],<br>    };<br><br>    const canvas = createCanvas(600, 600);<br>    const chart = echarts.init(canvas as any);<br><br>    chart.setOption(echartOption);<br><br>    return canvas.toBuffer(&#39;image/png&#39;);<br>  }<br>}</pre><p>Sample Images from generated PDF:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rr2POpq0oHS-XlQ5Mq9w6g.png" /></figure><figure><img alt="await this.pdfService.addNewLine();" src="https://cdn-images-1.medium.com/max/1024/1*Pu3AXg6lkfaIloPbEgKwjg.png" /><figcaption>TOC generated automatically. And page numbers also add correctly</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bx5G3WVoZl9DCndxLongqA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HX8zn1g1smkCpKraASTH5w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-om5kzL508630QYx4w7vkQ.png" /><figcaption>We could also change chart size dynamically using this.doc.internal.pageSize.getHeight() &amp; getWidth() methods of jsPDF.</figcaption></figure><p>Final Words.</p><p>I count this as a decent implementation but far from best. One immediate problem i can think of is we leave 1 page empty for TOC initially what if all the TOCs don’t fit? I haven’t yet done that bcz this fulfils my requirements as of now but doing that also wont be very tough.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=398fe3617a4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>