<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><title>Daniel Boll</title><description>A tech enthusiast from Brazil</description><link>https://daniel-boll.me/</link><language>en</language><item><title>Inferring the Primary Key of an Entity in a TypeScript Scylla ORM</title><link>https://daniel-boll.me/posts/primary-key-inference/</link><guid isPermaLink="true">https://daniel-boll.me/posts/primary-key-inference/</guid><description>Inferring the primary key of an entity in the charydbis.js ScyllaORM</description><pubDate>Wed, 03 Jul 2024 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import Trivia from &quot;@components/mdx/Trivia.astro&quot;;
import MessageBubble from &quot;@components/mdx/MessageBubble.astro&quot;;&lt;/p&gt;
&lt;p&gt;So ultimately I have been working on an unofficial version of the &lt;a href=&quot;https://www.scylladb.com/&quot;&gt;ScyllaDB&lt;/a&gt; driver for the Node.JS environment.
For those who are not aware, ScyllaDB is a highly performant, low-latency NoSQL database compatible with Apache Cassandra.
It offers features like Shard Awareness and superior scalability. For more information on how awesome it is, you can check out this &lt;a href=&quot;https://discord.com/blog/how-discord-stores-trillions-of-messages&quot;&gt;Discord blog post&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&amp;lt;MessageBubble speaker=&quot;reader&quot;&amp;gt;
Wait, Daniel, even their tutorials include a &lt;a href=&quot;https://cloud-getting-started.scylladb.com/stable/build-with-javascript.html&quot;&gt;Javascript driver
guide&lt;/a&gt;,
why would you be working on another one?
&amp;lt;/MessageBubble&amp;gt;&lt;/p&gt;
&lt;p&gt;&amp;lt;MessageBubble speaker=&quot;me&quot;&amp;gt;
Well, you may be right, but actually the driver in these guides is related to
the Cassandra one. It works with Scylla easily as it&apos;s compatible, thankfully.
The problem is that, of course, Scylla-specific features won&apos;t be available,
such as &lt;a href=&quot;https://python-driver.docs.scylladb.com/stable/scylla-specific.html#shard-awareness&quot;&gt;Shard
Awareness&lt;/a&gt;.
&amp;lt;/MessageBubble&amp;gt;&lt;/p&gt;
&lt;p&gt;All things considered, the development of the ScyllaDB driver is going pretty well, wrapping the Rust driver through a native module integration.
If you are not aware of how this stuff works, I have an in-depth &lt;a href=&quot;/archive/series/Going%20Native%20On%20JS/&quot;&gt;series on native modules&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;::github{repo=&quot;daniel-boll/scylla-javascript-driver&quot;}&lt;/p&gt;
&lt;p&gt;And to test its capabilities, I decided to implement a project using it. Thankfully, Scylla already has a showcase project, which is also
written in multiple other drivers, which is good from a comparison standpoint. The project is &lt;a href=&quot;https://iot.scylladb.com/stable/&quot;&gt;care-pet&lt;/a&gt;, a step-by-step guide to building an IoT project connected to Scylla Cloud.&lt;/p&gt;
&lt;p&gt;::github{repo=&quot;scylladb/care-pet&quot;}&lt;/p&gt;
&lt;p&gt;But even though the driver itself provides a lot of flexibility and power, it&apos;s usually pretty cumbersome to work directly with the barebones driver. Hence why so many ORMs exist. So
I thought to myself, why not create an ORM for ScyllaDB in the Node.JS environment too? We already have the awesome &lt;a href=&quot;https://github.com/nodecosmos/charybdis&quot;&gt;charydbis&lt;/a&gt; with the Rust gang.&lt;/p&gt;
&lt;p&gt;::github{repo=&quot;nodecosmos/charybdis&quot;}&lt;/p&gt;
&lt;p&gt;&amp;lt;MessageBubble speaker=&quot;reader&quot;&amp;gt;
Bro, but why would you come up with an ORM only for ScyllaDB? Why don&apos;t you
extend something like TypeORM or even Prisma?
&amp;lt;/MessageBubble&amp;gt;&lt;/p&gt;
&lt;p&gt;&amp;lt;MessageBubble speaker=&quot;me&quot;&amp;gt;
TLDR: Sowwy, skill issue. 😔&lt;/p&gt;
&lt;p&gt;The thing is that it&apos;s not trivial to extend those guys, even more considering the particular constraints of Scylla as it&apos;s a &lt;a href=&quot;https://www.scylladb.com/glossary/wide-column-database/&quot;&gt;NoSQL wide-column database&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&amp;lt;/MessageBubble&amp;gt;&lt;/p&gt;
&lt;p&gt;&amp;lt;MessageBubble speaker=&quot;reader&quot;&amp;gt;
Yeah, but Prisma supports MongoDB which is also NoSQL! 😠
&amp;lt;/MessageBubble&amp;gt;&lt;/p&gt;
&lt;p&gt;&amp;lt;MessageBubble speaker=&quot;me&quot;&amp;gt;
I&apos;m aware, but creating a new engine for Prisma is not that easy. It took them
a lot of effort, and as a matter of fact, there is already a &lt;a href=&quot;https://github.com/prisma/prisma/issues/2879&quot;&gt;feature request
for ScyllaDB support&lt;/a&gt; from 4
years ago on which a lot of these details are discussed.
&amp;lt;/MessageBubble&amp;gt;&lt;/p&gt;
&lt;p&gt;So the shorter path is to straight up just get my decorators going on and try something, as I&apos;ve already experienced &lt;a href=&quot;/posts/a-breakfest-with-expressots-and-bun/&quot;&gt;reflection in TS&lt;/a&gt; before. It can&apos;t be that hard, right?&lt;/p&gt;
&lt;p&gt;&amp;lt;Trivia emoji=&quot;🕵️&quot;&amp;gt;
It shouldn&apos;t take a detective to know that these are the famous last words of
those who went down a rabbit hole.
&amp;lt;/Trivia&amp;gt;&lt;/p&gt;
&lt;h2&gt;Decorating the entities&lt;/h2&gt;
&lt;p&gt;Okay, so roughly the API I want to achieve here is something along the lines of the following:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { Uuid } from &quot;@lambda-group/scylladb&quot;;

@Entity(&quot;users&quot;)
class User extends BaseEntity {
  @Column({ partitionKey: true })
  id: Uuid;

  @Column()
  name: string;

  @Column()
  email: string;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Not too shabby, am I right? Now let&apos;s get to the steps needed to achieve something like this. I will be omitting some code, so if you happen to be curious you can just check the repo.&lt;/p&gt;
&lt;p&gt;::github{repo=&quot;daniel-boll/charydbis.js&quot;}&lt;/p&gt;
&lt;h3&gt;The &lt;code&gt;@Entity(){:ts}&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;Okay, so the job of this decorator is mainly to store the name of the table to be generated as of now.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export function Entity(tableName?: string) {
  return (entity: Function) =&amp;gt; {
    entity.prototype.tableName = tableName ?? snakeCaseTransform(entity.name);
  };
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here, the parameter is optional because we may just infer the table name from the class name itself. We quickly transform the string into snake_case because JavaScript classes
are usually in PascalCase, which doesn&apos;t align with most database patterns.&lt;/p&gt;
&lt;p&gt;&amp;lt;Trivia emoji=&quot;⁉️&quot;&amp;gt;
We are even considering adding something like a transform to plural and other
modifications, which would require a library because of irregular forms. If
you have an opinion on this, please leave a comment on this post.
&amp;lt;/Trivia&amp;gt;&lt;/p&gt;
&lt;h3&gt;The &lt;code&gt;Column{:ts}&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;Now the hard work begins, as we need to collect and store a lot of data about the attribute.&lt;/p&gt;
&lt;p&gt;&amp;lt;MessageBubble speaker=&quot;reader&quot;&amp;gt;
Wait, that was it for the Entity decorator?
&amp;lt;/MessageBubble&amp;gt;&lt;/p&gt;
&lt;p&gt;&amp;lt;MessageBubble speaker=&quot;me&quot;&amp;gt;
Well, mostly yes. Keep in mind we don&apos;t even have the migration step in a CLI or anything like this. This is more of a POC than a full-blown project.&lt;/p&gt;
&lt;p&gt;At least when this post goes to air.&lt;/p&gt;
&lt;p&gt;&amp;lt;/MessageBubble&amp;gt;&lt;/p&gt;
&lt;p&gt;Continuing with the column, we will get something like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export function Column(options?: ColumnOptions | string) {
  return (target: BaseEntity, key: string) =&amp;gt; {
    const constructor_ = target.constructor as BaseEntityConstructor;

    if (!constructor_.columns) constructor_.columns = [];

    const propType = Reflect.getMetadata(&quot;design:type&quot;, target, key);
    const propColumnType = getColumnType(propType.name);

    let columnName = snakeCaseTransform(key);
    let columnType = propColumnType;
    let isPartitionKey = false;
    let isClusteringKey = false;
    let clusteringKeySequence = 0;

    if (typeof options === &quot;string&quot;) columnName = options;
    else if (typeof options === &quot;object&quot;) {
      columnName = options.name || key;
      columnType = options.type || propColumnType;
      if (options.partitionKey) isPartitionKey = options.partitionKey;
      if (options.clusteringKey) {
        isClusteringKey = options.clusteringKey;
        clusteringKeySequence = options.clusteringKeySequence || 0;
      }
    }

    constructor_.columns.push({
      key,
      columnName,
      columnType,
      ...(isPartitionKey &amp;amp;&amp;amp; { partitionKey: true }),
      ...(isClusteringKey &amp;amp;&amp;amp; { clusteringKey: true }),
      ...(isClusteringKey &amp;amp;&amp;amp; { clusteringKeySequence }),
    });
  };
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Don&apos;t mind the efficiency of this code, it hasn&apos;t even seen the light of refactoring yet. Here it mainly tries to collect data about the attribute&apos;s type automatically through the [G]old &lt;code&gt;import &quot;reflect-metadata&quot;{:ts}&lt;/code&gt; with &lt;code&gt;Reflect.getMetadata(&quot;design:type&quot;, target, key){:ts}&lt;/code&gt; and then coerces it to the types we support:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const getColumnType = (type?: string): ColumnType =&amp;gt; {
  const lowerType = type?.toLowerCase();
  switch (lowerType) {
    case &quot;string&quot;:
      return ColumnType.TEXT;
    case &quot;number&quot;:
      return ColumnType.FLOAT;
    case &quot;date&quot;:
      return ColumnType.DATE;
    case &quot;uuid&quot;:
      return ColumnType.UUID;
    default:
      return ColumnType.TEXT;
  }
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;and then stores the information in the class&apos;s &lt;code&gt;columns&lt;/code&gt; field.&lt;/p&gt;
&lt;h3&gt;Repository&lt;/h3&gt;
&lt;p&gt;Okay, now how do we interact with this entity? The idea is to have a repository that implement base methods for the class, so I can use like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { Uuid } from &quot;@lambda-group/scylladb&quot;;

@Entity(&quot;users&quot;)
class User extends BaseEntity {
  @Column({ partitionKey: true })
  id: Uuid;

  @Column()
  name: string;

  @Column()
  email: string;
}

using scyllaDataSource = await new DataSource({ nodes: [&quot;localhost:9042&quot;], }).initialize(&quot;example&quot;);
const userRepository = scyllaDataSource.getRepository(User);

const user = new User();
user.id = Uuid.randomV4();
user.name = &quot;John Doe&quot;;
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Save&lt;/h4&gt;
&lt;p&gt;To be able to save this entity shouldn&apos;t be that hard having the informations we already have:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export class Repository&amp;lt;T&amp;gt; {
  private dataSource: DataSource;
  private tableName: string;
  private columns: ColumnDefinition[];
  private entityClass: BaseEntityConstructor;

  constructor(dataSource: DataSource, entityClass: BaseEntityConstructor) {
    this.dataSource = dataSource;
    this.tableName = entityClass.prototype.tableName;
    this.columns = entityClass.columns ?? [];
    this.entityClass = entityClass;
  }

  async save(entity: T): Promise&amp;lt;void&amp;gt; {
    const session = this.dataSource.getSession();

    const columnNames = this.columns.map((col) =&amp;gt; col.columnName).join(&quot;, &quot;);
    const values = this.columns.map((col) =&amp;gt; entity[col.key]);
    const placeholders = this.columns.map(() =&amp;gt; &quot;?&quot;).join(&quot;, &quot;);

    const query = `INSERT INTO ${this.tableName} (${columnNames}) VALUES (${placeholders})`;
    await session.execute(query, values);
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;So now we can straight up do the following:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const user = new User();
user.id = Uuid.randomV4();
user.name = &quot;John Doe&quot;;

await userRepository.save(user);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Okay cool, this must be familiar to many readers as it&apos;s very common syntax in ORMs. What about when we want to select a field then?&lt;/p&gt;
&lt;h4&gt;Find&lt;/h4&gt;
&lt;pre&gt;&lt;code&gt;export class Repository&amp;lt;T&amp;gt; {
  // ...

  async findByPartitionKey&amp;lt;U extends string | number | Uuid&amp;gt;(
    id: U
  ): Promise&amp;lt;T[]&amp;gt; {
    const session = this.dataSource.getSession();
    const columnNames = this.columns.map((col) =&amp;gt; col.columnName).join(&quot;, &quot;);
    const partitionKey = this.columns.find((col) =&amp;gt; col.partitionKey);
    if (!partitionKey) {
      throw new Error(&quot;Primary key not found&quot;);
    }

    const query = `SELECT ${columnNames} FROM ${this.tableName} WHERE ${partitionKey.columnName} = ?`;

    return (await session.execute(query, [id])).map((row: unknown) =&amp;gt; {
      const entity = new this.entityClass();
      for (const col of this.columns) {
        entity[col.key] = this.columnToValue(col, row);
      }

      return entity;
    });
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&amp;lt;MessageBubble speaker=&quot;reader&quot;&amp;gt;
I think I got it, we are in a good track using this pattern
&amp;lt;/MessageBubble&amp;gt;&lt;/p&gt;
&lt;p&gt;&amp;lt;MessageBubble speaker=&quot;me&quot;&amp;gt;
Well, yeah, except that queries can be a little bit more complex considering
clustering keys and composite partition keys, there are a bunch of rules, for
instance having three clustering keys the order of their definitions matters,
so when querying by the third clustering key we &lt;strong&gt;NEED&lt;/strong&gt; to specify the
previous two and always the partition key.
&amp;lt;/MessageBubble&amp;gt;&lt;/p&gt;
&lt;p&gt;&amp;lt;MessageBubble speaker=&quot;reader&quot;&amp;gt;
Hey, but we have the power of the decorators in our side, why don&apos;t you just do this you silly?&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { Uuid } from &quot;@lambda-group/scylladb&quot;;

@Entity(&quot;users&quot;)
class User extends BaseEntity {
  @Column({ partitionKey: true })
  id: Uuid;

  @Column({ clusteringKey: 1 })
  name: string;

  @Column({ clusteringKey: 2 })
  email: string;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And then figure out the type from there, achieving something like:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;type FindQuery&amp;lt;User&amp;gt; =
  | { id: Uuid }
  | { id: Uuid; name: string }
  | { id: Uuid; name: string; email: string };
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Which guarantee the order of clustering key and the presence of the partition key. Thank me later 😘.&lt;/p&gt;
&lt;p&gt;&amp;lt;/MessageBubble&amp;gt;&lt;/p&gt;
&lt;p&gt;&amp;lt;MessageBubble speaker=&quot;me&quot;&amp;gt;
Oh, dear reader, I wished so hard for this, the problem is that decorators
cannot &lt;a href=&quot;https://github.com/Microsoft/TypeScript/issues/4881&quot;&gt;augment types&lt;/a&gt; up
until TS 5.0.
&amp;lt;/MessageBubble&amp;gt;&lt;/p&gt;
&lt;p&gt;&amp;lt;MessageBubble speaker=&quot;reader&quot;&amp;gt;Nooooooooooo 😭😭 so we give up?&amp;lt;/MessageBubble&amp;gt;&lt;/p&gt;
&lt;p&gt;&amp;lt;MessageBubble speaker=&quot;me&quot;&amp;gt;
Don&apos;t you worry kitten, I&apos;ve got a couple of plans, let&apos;s get to them.
&amp;lt;/MessageBubble&amp;gt;&lt;/p&gt;
&lt;h3&gt;Infering the Type System&lt;/h3&gt;
&lt;p&gt;Wandering the interwebs searching for a solution I stumbled upon mikrorm solution for &lt;a href=&quot;https://mikro-orm.io/docs/composite-keys&quot;&gt;composite keys&lt;/a&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;@Entity()
export class Car {
  @PrimaryKey()
  name: string;

  @PrimaryKey()
  year: number;

  // this is needed for proper type checks in `FilterQuery`
  [PrimaryKeyProp]?: [&quot;name&quot;, &quot;year&quot;];

  constructor(name: string, year: number) {
    this.name = name;
    this.year = year;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Wait wait wait, so we can try to figure the type of composite keys through this syntax that stores the info in a Symbol instead of the decorators.
I got working from their types onwards to the rules we need to fulfill.&lt;/p&gt;
&lt;h4&gt;Step 1&lt;/h4&gt;
&lt;p&gt;The first step is to be able to extract from the entity the fields annotated with PrimaryKeyProp.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;@Entity(&quot;users&quot;)
class User extends BaseEntity {
  @Column({ partitionKey: true })
  id: Uuid;

  @Column()
  name: string;

  @Column()
  email: string;

  [PrimaryKeyProp]?: [[&quot;id&quot;], [&quot;name&quot;, &quot;email&quot;]];
}

type Step1 = PrimaryKeys&amp;lt;User&amp;gt;; // [[&quot;id&quot;], [&quot;name&quot;, &quot;email&quot;]]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Okay, so first we need to find a type that has this attribute PrimaryKeyProp.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export type PrimaryKeys&amp;lt;T&amp;gt; = T extends { [PrimaryKeyProp]?: any }
  ? any
  : unknown;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here if we find this PrimaryKeyProp with anything we will return any otherwise unknown. The problem is that we don&apos;t know the type of this damn property.
Thankfully we can &lt;code&gt;infer&lt;/code&gt; it.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export type PrimaryKeys&amp;lt;T&amp;gt; = T extends { [PrimaryKeyProp]?: infer PK }
  ? PK
  : unknown;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;There we go, we already have collected the keys. Now we want to merge them into a single array so we can iterate on it easily next.&lt;/p&gt;
&lt;h4&gt;Step 2&lt;/h4&gt;
&lt;p&gt;Now the plan is to obtain the type &lt;code&gt;[&quot;id&quot;, &quot;name&quot;, &quot;email&quot;]{:ts}&lt;/code&gt;. It must preserve the order as for the clustering keys it is very important.&lt;/p&gt;
&lt;p&gt;To achieve this we simply create a Flatten type that will recursivelly reduce the dimension of the list.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;type Flatten&amp;lt;T&amp;gt; = T extends [infer F, ...infer R]
  ? [...(F extends any[] ? F : [F]), ...Flatten&amp;lt;R&amp;gt;]
  : [];

type Step2 = Flatten&amp;lt;Step1&amp;gt;; // [&quot;id&quot;, &quot;name&quot;, &quot;email&quot;]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;Flatten&amp;lt;T&amp;gt;{:ts}&lt;/code&gt; type recursively deconstructs an array T by checking each element: if the element is an array, it spreads its contents;
if not, it treats it as a single-element array, then combines these elements into a single-level array until the entire structure is flattened.&lt;/p&gt;
&lt;h4&gt;Step 3&lt;/h4&gt;
&lt;p&gt;Now we need to create the result type which is from the original type get the valid queries, in this case &lt;code&gt;type _ = { id: Uuid; } | { id: Uuid; name: string; } | { id: Uuid; name: string; address: string }{:ts}&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;type Step3 = Something&amp;lt;User&amp;gt;;
// | { id: Uuid; }
// | { id: Uuid; name: string; }
// | { id: Uuid; name: string; address: string }
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To that we, in the most trivial way (🤓👆), do the following:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export type UnionCombinations&amp;lt;
  T,
  Keys extends Array&amp;lt;keyof T&amp;gt;,
  AccumulatedKeys extends Array&amp;lt;keyof T&amp;gt; = []
&amp;gt; = Keys extends [infer First, ...infer Rest]
  ? First extends keyof T
    ? Rest extends Array&amp;lt;keyof T&amp;gt;
      ?
          | StrictPick&amp;lt;T, First | AccumulatedKeys[number]&amp;gt;
          | UnionCombinations&amp;lt;T, Rest, [First, ...AccumulatedKeys]&amp;gt;
      : never
    : never
  : never;

export type StrictPick&amp;lt;T, K extends keyof T&amp;gt; = Pick&amp;lt;T, K&amp;gt; &amp;amp; {
  [P in keyof T as P extends K ? never : P]?: never;
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here &lt;code&gt;type UnionCombinations{:ts}&lt;/code&gt; recursively forms combinations of object properties by picking the current key, accumulating it, and
combining it with the results of further recursive calls on the remaining keys. While &lt;code&gt;type StrictPick{:ts}&lt;/code&gt; picks specified keys from
an object and creates a type where these keys are required while all other keys are explicitly set to never, ensuring they cannot exist
in the resulting type.&lt;/p&gt;
&lt;h4&gt;Step 4&lt;/h4&gt;
&lt;p&gt;Now we just need to wrap the steps in a single easy to use type, we&apos;re gonna call this one &lt;code&gt;type FilterQuery{:ts}&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&amp;lt;MessageBubble speaker=&quot;reader&quot;&amp;gt;
Ayo bro, wait wait. The last one was still too much to me to digest, I mean, look at that &lt;code&gt;type UnionCombinations{:ts}&lt;/code&gt; monstrosity dude, do you
expect me to simply get it?
&amp;lt;/MessageBubble&amp;gt;&lt;/p&gt;
&lt;p&gt;&amp;lt;MessageBubble speaker=&quot;me&quot;&amp;gt;
Well, to be fair I haven&apos;t designed this type either, I&apos;ve got some help (🤖),
but once it&apos;s done and you know what is trying to achieve is not that hard to
grasp, I will leave this one to you as exercise to understand fully that type
😉.
&amp;lt;/MessageBubble&amp;gt;&lt;/p&gt;
&lt;p&gt;Now to the wrapper:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export type FilterQuery&amp;lt;T&amp;gt; = UnionCombinations&amp;lt;T, Flatten&amp;lt;Primary&amp;lt;T&amp;gt;&amp;gt;&amp;gt;;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The only problem here is some constraints needed to this to work, is that T must be have the &lt;code&gt;[PrimaryKeyProp]&lt;/code&gt;, so we need to guard that.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export type FilterQuery&amp;lt;T extends { [PrimaryKeyProp]?: AnyArray }&amp;gt; =
  UnionCombinations&amp;lt;T, Flatten&amp;lt;Primary&amp;lt;T&amp;gt;&amp;gt;&amp;gt;;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now we have the type strictness needed to not have to define a &lt;code&gt;async findBy(query: any){:ts}&lt;/code&gt; anymore and be able to define based on all this hassle we went through.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export class Repository&amp;lt;T extends { [PrimaryKeyProp]?: AnyArray }&amp;gt; {
  // ...

  async findBy(query: FilterQuery&amp;lt;T&amp;gt;) {
    // ...
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;The end&lt;/h2&gt;
&lt;p&gt;&amp;lt;MessageBubble speaker=&quot;reader&quot;&amp;gt;
So I guess our type journey ends here 🥹. It was good while it lasted, I&apos;ve got
to say man even though the last year has been tough for me you stood by side
at all times and ...
&amp;lt;/MessageBubble&amp;gt;&lt;/p&gt;
&lt;p&gt;&amp;lt;MessageBubble speaker=&quot;me&quot;&amp;gt;
Yo yo yo, chill. You don&apos;t have to worry bro, we got so many things to explore
yet. Scylla got some cool stuff we need to deal with still, for instance
&lt;a href=&quot;https://university.scylladb.com/courses/data-modeling/lessons/materialized-views-secondary-indexes-and-filtering/topic/filtering-in-depth/&quot;&gt;filtering&lt;/a&gt;
on which we can query by fields that are not in the PrimaryKey, and we will
have to deal with this in a way that it&apos;s clear to the user that they are deciding to use it, perhaps through a &lt;code&gt;{ withFiltering: true }{:ts}&lt;/code&gt; field in the query
that will unlock the ability to do so.
&amp;lt;/MessageBubble&amp;gt;&lt;/p&gt;
&lt;p&gt;&amp;lt;MessageBubble speaker=&quot;me&quot; small&amp;gt;
...
&amp;lt;/MessageBubble&amp;gt;&lt;/p&gt;
&lt;p&gt;&amp;lt;MessageBubble speaker=&quot;me&quot;&amp;gt;
Okay, not only that I still have some other paths I want to explore, such as
&lt;code&gt;env.d.ts&lt;/code&gt; allowing to generate much powerful types.
&lt;a href=&quot;https://astro.build&quot;&gt;Astro&lt;/a&gt; generates this in their CLI, so we&apos;ve got some
things up or sleeves to try.
&amp;lt;/MessageBubble&amp;gt;&lt;/p&gt;
&lt;p&gt;&amp;lt;MessageBubble speaker=&quot;reader&quot;&amp;gt;🥹 Okay&amp;lt;/MessageBubble&amp;gt;&lt;/p&gt;
&lt;p&gt;So yall, stay tuned for the next steps of this journey, leave a comment, consider contributing to the repo and have a nice one. See ya 👋&lt;/p&gt;
&lt;p&gt;::github{repo=&quot;daniel-boll/charydbis.js&quot;}&lt;/p&gt;
</content:encoded></item><item><title>Feature Flags at the Nginx Level</title><link>https://daniel-boll.me/posts/feature-flags-at-the-nginx-level/</link><guid isPermaLink="true">https://daniel-boll.me/posts/feature-flags-at-the-nginx-level/</guid><description>Let&apos;s explore the potential of feature flags with Nginx: from setup to real-world transitions between Next.js and Nuxt</description><pubDate>Mon, 23 Oct 2023 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import { Image } from &quot;astro:assets&quot;;&lt;/p&gt;
&lt;p&gt;import firstPageSrc from &quot;./config_cat_first_page.png&quot;;
import configuringFlagSrc from &quot;./configuring_flag.png&quot;;
import flagSpecSrc from &quot;./flag_spec.png&quot;;
import showcaseSrc from &quot;./showcase.mp4&quot;;&lt;/p&gt;
&lt;p&gt;Hello, fellow developers and tech enthusiasts! Today, in this posts we will tinker Nginx, wield the power of feature flags, and orchestrate controlled rollouts of our web pages. Sit tight; it&apos;s going to be a thrilling ride! 🎢&lt;/p&gt;
&lt;h2&gt;Prelude to Innovation: Why This Matters 🤔&lt;/h2&gt;
&lt;p&gt;Before we dive into the technical nitty-gritty, let&apos;s pause and ponder why this endeavor matters. In the fast-paced world of web development, deploying new features is a double-edged sword 🗡️. It&apos;s exhilarating yet perilous. One tiny bug, and boom! You&apos;re trending on social media for all the wrong reasons.&lt;/p&gt;
&lt;p&gt;That&apos;s where feature flags come in, acting as our safety nets. They give us the power to toggle features on or off with the flick of a switch. But, what if we took it up a notch and implemented these toggles at the Nginx level? That&apos;s the voyage I embarked upon, and spoiler alert: it&apos;s possible, and I&apos;m going to show you how!&lt;/p&gt;
&lt;h2&gt;Setting the Stage: Nginx and Feature Flags 🎬&lt;/h2&gt;
&lt;p&gt;First things first, let&apos;s talk about our main actor, Nginx. This high-performance HTTP server is a star in its own right, but not all setups are created equal. For our purposes, we need Nginx compiled with the &lt;code&gt;http_auth_request_module&lt;/code&gt;. Fear not, for verifying this is a piece of cake 🍰! Just whip open your terminal and run:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;nginx -V 2&amp;gt;&amp;amp;1 | rg &apos;http_auth_request_module&apos;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you see &lt;code&gt;--with-http_auth_request_module{:bash}&lt;/code&gt; in the output, congratulations! 🎉 You&apos;re good to go.
If not, well, it&apos;s time for a little recompilation side quest.&lt;/p&gt;
&lt;h2&gt;&quot;Auth&quot; You Ready? Configuring Nginx 🛠️&lt;/h2&gt;
&lt;p&gt;With the preliminaries out of the way, we&apos;re delving into the heart of our journey - Nginx configuration.
Our goal here is to create a sort of &quot;fork in the road&quot; for incoming requests, directing them towards either our new
shiny feature or the reliable old page, based on our feature flag&apos;s status.&lt;/p&gt;
&lt;p&gt;Here&apos;s a sneak peek of what the configuration looks like:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;server {
  listen &amp;lt;port&amp;gt;;

  location = /auth {
    internal;
    proxy_pass &amp;lt;auth_server&amp;gt;;
    proxy_pass_request_body off;
    proxy_set_header Content-Length &quot;&quot;;
    proxy_set_header X-Original-URI $request_uri;
  }

  location / {
    auth_request /auth;
    error_page 401 = @deny;
    proxy_pass &amp;lt;app_a&amp;gt;;
  }

  location @deny {
    proxy_pass &amp;lt;app_b&amp;gt;;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Looks neat, right? But there&apos;s a lot going on here, so let&apos;s unpack it 🧳:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;/auth&lt;/strong&gt;: Our internal checkpoint. It&apos;s not accessible to the outside world but is pivotal for our setup. It proxies the request to an external authentication server, which will give the thumbs up 👍 (or down 👎) based on the feature flag status.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;/&lt;/strong&gt;: The standard route. It&apos;s like the main entrance 🚪, where every request first knocks. Using the &lt;code&gt;auth_request{:nginx}&lt;/code&gt;,
it consults the &lt;code&gt;location = /auth{:nginx}&lt;/code&gt;. If &lt;code&gt;location = /auth{:nginx}&lt;/code&gt; returns a &lt;code&gt;200{:javascript}&lt;/code&gt; status, the gates open wide
to the promised land of &lt;code&gt;app_a{:nginx}&lt;/code&gt;. A &lt;code&gt;401{:javascript}&lt;/code&gt;, though? They&apos;re diverted to the &lt;code&gt;@deny{:nginx}&lt;/code&gt; route.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;@deny&lt;/strong&gt;: Our plan B, the alternative route. If &lt;code&gt;/auth{:nginx}&lt;/code&gt; gives a &lt;code&gt;401{:javascript}&lt;/code&gt;, this is where requests get rerouted,
landing them in the realm of &lt;code&gt;app_b{:nginx}&lt;/code&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;Authenticating Like a Boss: The Auth Server 🕵️&lt;/h2&gt;
&lt;p&gt;Now, onto our authentication server, the unsung hero of this setup. This server&apos;s task is straightforward yet crucial:
check the feature flag and give a green or red light 🚦.&lt;/p&gt;
&lt;p&gt;Here&apos;s a stripped-down version of what the server might look like, written in TypeScript with the help of 🍞 &lt;a href=&quot;https://bun.sh&quot;&gt;Bun&lt;/a&gt; using &lt;code&gt;&quot;configcat-js-ssr&quot;{:javascript}&lt;/code&gt;
for feature flag magic:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { PollingMode, getClient } from &quot;configcat-js-ssr&quot;;

const client = getClient(&quot;SDK_KEY&quot;, PollingMode.AutoPoll);

async function getKey() {
  await client.forceRefreshAsync();

  const key = await client.getValueAsync(&quot;&amp;lt;key&amp;gt;&quot;, false);

  return new Response(&quot;&quot;, {
    status: key ? 200 : 401,
  });
}

Bun.serve({
  port: 5000,
  async fetch(request) {
    const url = new URL(request.url);

    if (url.pathname === &quot;/auth&quot;) return await getKey();

    return new Response(&quot;Not found&quot;, { status: 404 });
  },
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It refreshes the feature flag values and responds with the appropriate status code, all based on the majestic power of feature flags.&lt;/p&gt;
&lt;h2&gt;Switching Scenes: From Next.js to Nuxt 🏡➡️🏰&lt;/h2&gt;
&lt;p&gt;After setting the stage with Nginx and our auth server, it&apos;s time for a real-world rehearsal:
transitioning from a default Next.js 13 home page to a Nuxt home page. This switcheroo is not just about flaunting fresh features;
it&apos;s a testament to the flexibility our setup offers. So, let&apos;s roll up our sleeves and get our hands dirty with some code! 👨‍💻👩‍💻&lt;/p&gt;
&lt;h3&gt;Nuxt&apos;s Grand Entrance&lt;/h3&gt;
&lt;p&gt;Let&apos;s kick things off by orchestrating a Nuxt application into existence with Bun:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;bunx nuxi@latest init project-a
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;After which, a quick saunter into the directory and a chant of:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;bun dev
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;summons Nuxt to grace my port &lt;code&gt;3001{:js}&lt;/code&gt; with its presence.&lt;/p&gt;
&lt;h3&gt;Next.js 13&apos;s Encore&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;bunx create-next-app@latest
✔ What’s the name of your masterpiece? … project-b
✔ Fancy a bit of TypeScript magic? … No / Yes
✔ How about the keen eye of ESLint? … No / Yes
✔ Craving the finesse of Tailwind CSS? … No / Yes
✔ Seeking refuge in a `src/` directory haven? … No / Yes
✔ Embarking on a journey with the App Router? (wise choice) … No / Yes
✔ Dream of customizing the default import alias (@/*)? … No / Yes
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;A hop, skip, and jump into the directory followed by the incantation:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;bun dev
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;ushers Next back for an encore on my port &lt;code&gt;3002{:js}&lt;/code&gt;.&lt;/p&gt;
&lt;h3&gt;The Art of Flag Waving&lt;/h3&gt;
&lt;p&gt;Next, I enlist the prowess of &lt;a href=&quot;https://configcat.com/&quot;&gt;ConfigCat&lt;/a&gt; to choreograph the flags. Sure, feature flags can be as simple as a hidden rabbit in a hat, but a maestro like ConfigCat orchestrates a ballet, like enabling only a select 10% of my audience to preview the new act, with the elegance of a seasoned conductor.&lt;/p&gt;
&lt;p&gt;The auditorium&apos;s first view should resemble this:&lt;/p&gt;
&lt;p&gt;&amp;lt;Image
src={firstPageSrc}
alt=&quot;The opening view of ConfigCat&quot;
class=&quot;self-center md:h-1/2 md:w-full&quot;
/&amp;gt;&lt;/p&gt;
&lt;p&gt;&amp;lt;figcaption class=&quot;text-center text-xs italic&quot;&amp;gt;
&amp;lt;strong&amp;gt;Figure 1:&amp;lt;/strong&amp;gt; Your initial glimpse upon entering the ConfigCat
auditorium
&amp;lt;/figcaption&amp;gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;./config_cat_first_page.png&quot; alt=&quot;ALT&quot; title=&quot;Your initial glimpse upon entering the ConfigCat auditorium&quot; /&gt;&lt;/p&gt;
&lt;p&gt;I then proceed to craft a new flag for this theatrical:&lt;/p&gt;
&lt;p&gt;&amp;lt;Image
src={configuringFlagSrc}
alt=&quot;The crafting of the feature flag&quot;
class=&quot;self-center md:h-1/2 md:w-full&quot;
/&amp;gt;&lt;/p&gt;
&lt;p&gt;&amp;lt;figcaption class=&quot;text-center text-xs italic&quot;&amp;gt;
&amp;lt;strong&amp;gt;Figure 2:&amp;lt;/strong&amp;gt; The art of feature flag configuration
&amp;lt;/figcaption&amp;gt;&lt;/p&gt;
&lt;p&gt;Upon the final curtain of setup, the stage reveals:&lt;/p&gt;
&lt;p&gt;&amp;lt;Image
src={flagSpecSrc}
alt=&quot;The feature flag’s final form&quot;
class=&quot;self-center md:h-1/2 md:w-full&quot;
/&amp;gt;&lt;/p&gt;
&lt;p&gt;&amp;lt;figcaption class=&quot;text-center text-xs italic&quot;&amp;gt;
&amp;lt;strong&amp;gt;Figure 3:&amp;lt;/strong&amp;gt; The full splendor of the feature flag
&amp;lt;/figcaption&amp;gt;&lt;/p&gt;
&lt;p&gt;Don’t forget to secure your SDK key from the &apos;View SDK Key&apos; button.&lt;/p&gt;
&lt;h3&gt;The Conductor: Our Server&lt;/h3&gt;
&lt;p&gt;A slight tweak in the server&apos;s score, conducted with Bun&apos;s baton, harmonizes our composition:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import {
  LogLevel,
  PollingMode,
  createConsoleLogger,
  getClient,
} from &quot;configcat-js-ssr&quot;;

const maestro = createConsoleLogger(LogLevel.Info);

const client = getClient(&quot;&amp;lt;YOUR-SDK-KEY&amp;gt;&quot;, PollingMode.AutoPoll, {
  logger: maestro,
});

async function getKey() {
  await client.forceRefreshAsync();

  const key = await client.getValueAsync(&quot;viewPageFromNuxt&quot;, false);

  return new Response(&quot;&quot;, { status: key ? 200 : 401 });
}

Bun.serve({
  port: 5000,
  async fetch(request) {
    const url = new URL(request.url);

    if (url.pathname === &quot;/auth&quot;) return await getKey();

    return new Response(&quot;Not found&quot;, { status: 404 });
  },
});
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Nginx: The Stage Manager&lt;/h3&gt;
&lt;p&gt;With our actors (ports, really) in place, the script remains much the same:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;server {
  listen 8081;

  location = /auth {
    internal;
    proxy_pass http://localhost:5000;
    proxy_pass_request_body off;
    proxy_set_header Content-Length &quot;&quot;;
    proxy_set_header X-Original-URI $request_uri;
  }

  location / {
    auth_request /auth;
    error_page 401 = @deny;
    proxy_pass http://localhost:3001;
  }

  location @deny {
    proxy_pass http://localhost:3002;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;By tuning in to the rather obscure frequency of port 8081, my production now seamlessly alternates between a Next.js encore and a Nuxt debut, depending on the &lt;code&gt;viewPageFromNuxt&lt;/code&gt; flag&apos;s whims. The audience, none the wiser, revels in the performance, oblivious to the magic unfurling backstage. 🎭✨&lt;/p&gt;
&lt;h2&gt;The Grand Reveal: Feature Flag in Action! 🎬✨&lt;/h2&gt;
&lt;p&gt;Words are compelling, but seeing is believing, right? After all this backstage hustle, it&apos;s time for the spotlight moment. Below, you&apos;ll find a real-time performance of our feature flag directing the show. With a simple flick of the switch, watch the stage as it alternates between our Next.js and Nuxt setups. No smoke and mirrors here; it&apos;s all the magic of well-orchestrated tech! 🪄&lt;/p&gt;
&lt;p&gt;&amp;lt;video controls&amp;gt;
&amp;lt;source src={showcaseSrc} type=&quot;video/mp4&quot; /&amp;gt;
&amp;lt;/video&amp;gt;&lt;/p&gt;
&lt;p&gt;&amp;lt;figcaption class=&quot;text-center text-xs italic&quot;&amp;gt;
&amp;lt;strong&amp;gt;Figure 4:&amp;lt;/strong&amp;gt; The seamless transition between Next.js and Nuxt,
directed live by our feature flag.
&amp;lt;/figcaption&amp;gt;&lt;/p&gt;
&lt;p&gt;Witnessing the live transition, you can appreciate the fluidity and control this setup grants us. Whether it&apos;s for A/B testing, phased rollouts, or safe migrations, feature flags have proven to be the discreet stage managers of our productions. They empower us to put on a seamless show, where the audience gets to experience only the best performances!&lt;/p&gt;
&lt;h2&gt;To Infinity and Beyond: Next Steps 🚀&lt;/h2&gt;
&lt;p&gt;While our current setup is nothing short of awesome, it&apos;s just the tip of the iceberg ❄️. Scaling this logic to support multiple pages and flags? That&apos;s our next Everest. And though it&apos;s beyond today&apos;s tale, rest assured, it&apos;s a challenge I&apos;m ready to tackle head-on.&lt;/p&gt;
&lt;h2&gt;Curtain Call: Final Thoughts 🎭&lt;/h2&gt;
&lt;p&gt;Navigating the tumultuous seas of feature releases can be daunting, but with our Nginx-level feature flags, we&apos;ve got a robust new vessel 🚢. This approach isn&apos;t just about fancy tech—it&apos;s about control, confidence, and the courage to innovate without fear of capsizing.&lt;/p&gt;
&lt;p&gt;So, to my fellow tech adventurers, I say: Set sail. Explore. And may your feature releases always be smooth sailing! 🌊&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Until our next tech odyssey!&lt;/em&gt; ✨&lt;/p&gt;
</content:encoded></item><item><title>Native Node.js Addons with node-addon-api</title><link>https://daniel-boll.me/posts/going-native-on-javascript/node-gyp/</link><guid isPermaLink="true">https://daniel-boll.me/posts/going-native-on-javascript/node-gyp/</guid><description>Learn how to build native Node.js addons effortlessly using node-addon-api, from basic setup to basic OpenCV functionalities.</description><pubDate>Fri, 29 Sep 2023 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import Trivia from &quot;@components/mdx/Trivia.astro&quot;;&lt;/p&gt;
&lt;h2&gt;Introduction&lt;/h2&gt;
&lt;p&gt;Welcome to the second installment of our deep dive into native Node.js modules! If you&apos;ve been following along, you&apos;ve already learned the basics of
what native modules are, how they work, and why they are such a vital part of the Node.js ecosystem. If you missed it, you might want to
check out the first post in the series: &lt;code&gt;&quot;Unlocking the Power of Native Modules in JavaScript: An Introductory Guide&quot;{:javascript}&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;{/&lt;em&gt;&amp;lt;SeeAlso slug=&quot;going-native-on-javascript-1&quot; /&amp;gt;&lt;/em&gt;/}&lt;/p&gt;
&lt;p&gt;Today, we&apos;re rolling up our sleeves to get into the nitty-gritty: &lt;strong&gt;building a real-world native module from scratch&lt;/strong&gt;.
But we&apos;re not just going to build any module — we&apos;re creating a &lt;code&gt;&quot;Fast Image Resizer&quot;{:javascript}&lt;/code&gt; using &lt;code&gt;C++&lt;/code&gt; and integrating
it into a &lt;code&gt;Node.js&lt;/code&gt; application. The primary objective here is to offer a hands-on demonstration of the performance benefits
that native modules can bring to computationally intensive tasks.&lt;/p&gt;
&lt;p&gt;Now, you might be asking, &lt;code&gt;&quot;Why image resizing?&quot;{:javascript}&lt;/code&gt; The answer lies in its practical applicability and the
intense computation it demands, making it a perfect case study for native modules. JavaScript alone can be painfully slow
for such operations, giving us an excellent backdrop against which to showcase the raw speed of a native module.
By the end of this post, you&apos;ll not only have a fully functional image resizer but also a robust understanding of node-gyp,
the build tool that turns our C++ code into a native Node.js module.&lt;/p&gt;
&lt;p&gt;Here&apos;s what we&apos;ll cover:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Setting up your development environment to use node-gyp.&lt;/li&gt;
&lt;li&gt;Writing the C++ code that will form the core of our Fast Image Resizer.&lt;/li&gt;
&lt;li&gt;Crafting the essential &lt;code&gt;binding.gyp&lt;/code&gt; file, the blueprint for our native module.&lt;/li&gt;
&lt;li&gt;Building the module and integrating it into a Node.js application.&lt;/li&gt;
&lt;li&gt;Troubleshooting and overcoming common challenges.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&amp;lt;Trivia emoji=&quot;☕&quot;&amp;gt;
So grab a cup of coffee, fire up your code editor, and let&apos;s get building!
&amp;lt;/Trivia&amp;gt;&lt;/p&gt;
&lt;h2&gt;Setting the Stage: Tools and Environment Setup 🛠️&lt;/h2&gt;
&lt;p&gt;Before diving into the code, it&apos;s essential to ensure that our development environment is well-equipped with the tools we&apos;ll be using
throughout this hands-on tutorial. The right tools not only make the development process smoother but also allow us to focus more on
coding and less on fixing environment-related issues. Here, we&apos;ll cover how to set up everything you need, based on the operating system you&apos;re using.&lt;/p&gt;
&lt;h3&gt;The Tools You&apos;ll Need 🛠️&lt;/h3&gt;
&lt;p&gt;Here&apos;s a list of tools that you&apos;ll require for developing native Node.js modules:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Node.js&lt;/strong&gt;: To run your JavaScript code.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;npm&lt;/strong&gt;: For package management and distribution.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;C/C++ Development Tools&lt;/strong&gt;: For writing native code.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Python&lt;/strong&gt;: Required by node-gyp.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Node and npm&lt;/strong&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Ensure you have Node.js and npm installed on your machine. If you haven&apos;t, download the appropriate installer from
&lt;a href=&quot;https://nodejs.org/&quot;&gt;Node.js website&lt;/a&gt;. It&apos;s recommended to use the LTS (Long Term Support) version for stability.
The installer will also include npm.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# Verify Node and npm installation
node --version
npm --version
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&amp;lt;Trivia emoji=&quot;🥸&quot;&amp;gt;
I will actually be using &lt;code&gt;pnpm&lt;/code&gt; as a personal preference. You can use &lt;code&gt;npm&lt;/code&gt; or
&lt;code&gt;yarn&lt;/code&gt; as well. (Or even bun 🍞 if you are feeling adventurous!)
&amp;lt;/Trivia&amp;gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;C/C++ Development Tools and Python&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The requirements for C/C++ development tools and Python differ based on your operating system:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Windows&lt;/strong&gt;: Use npm to install &lt;code&gt;windows-build-tools&lt;/code&gt; which includes the required C/C++ compilers and Python.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;npm install --global --production windows-build-tools
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Mac&lt;/strong&gt;: Use &lt;code&gt;xcode-select&lt;/code&gt; to install the necessary C/C++ tools.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;xcode-select --install
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;Python usually comes pre-installed on macOS.&lt;/em&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Linux&lt;/strong&gt;: The required C/C++ and Python tools are generally pre-installed. If not, consult your distribution&apos;s package manager for installation.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code&gt;# Verify Python installation
python --version

# Verify C/C++ compiler
cc --version

# Verify make utility
make --version
&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Other Tools&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;You&apos;ll also need a shell program and a code editor of your choice. macOS and Linux generally come with a shell pre-installed.
For Windows, you might consider using PowerShell.&lt;/p&gt;
&lt;h3&gt;Initializing Your Project 🚀&lt;/h3&gt;
&lt;p&gt;Create a new directory for your project and initialize it with pnpm:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;mkdir fast-image-resizer
cd fast-image-resizer
pnpm init # npm init -y
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This action will generate a &lt;code&gt;package.json&lt;/code&gt; file, your project&apos;s manifest.&lt;/p&gt;
&lt;h3&gt;Setting Up node-gyp 🛠️🔧&lt;/h3&gt;
&lt;p&gt;Before we dive into the actual setup, it&apos;s crucial to understand what node-gyp is and why it&apos;s an essential tool for native
Node.js module development. Node-gyp is a build automation tool used to compile native addon modules for Node.js.
It provides a cross-platform interface for native module compilation and takes care of the heavy lifting around configuring
the build environment for various operating systems. Node-gyp uses &lt;code&gt;binding.gyp&lt;/code&gt; files written in JSON format to describe
the configuration for building your native addons.&lt;/p&gt;
&lt;p&gt;Now that you have an idea of what node-gyp is, let&apos;s get it set up so we can proceed with creating a native module.&lt;/p&gt;
&lt;h4&gt;Installation 💾&lt;/h4&gt;
&lt;p&gt;Installing node-gyp is straightforward. You can either install it globally on your machine or as a development dependency in your specific project.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;pnpm i -D node-gyp # npm install --save-dev node-gyp
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Verifying Installation ✅&lt;/h4&gt;
&lt;p&gt;To ensure that node-gyp is correctly installed, run the following command:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;pnpm node-gyp --version # Mine is v9.4.0
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you see the version number displayed, you are good to go.&lt;/p&gt;
&lt;p&gt;That&apos;s it for the setup! You&apos;re now well-equipped to tackle native Node.js module development.&lt;/p&gt;
&lt;h3&gt;Your First Native Module: Hello, World! 🌍&lt;/h3&gt;
&lt;p&gt;Before we start with the actual implementation, let&apos;s create a basic &lt;code&gt;&quot;Hello, World!&quot;{:javascript}&lt;/code&gt; native module to get a taste of the process.
This simple example will demonstrate the basics of setting up, compiling, and importing a native module.&lt;/p&gt;
&lt;h4&gt;The C++ Code 📝&lt;/h4&gt;
&lt;p&gt;Create a file named &lt;code&gt;hello.cc&lt;/code&gt; and add the following C++ code:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#include &amp;lt;node.h&amp;gt;

void HelloWorld(const v8::FunctionCallbackInfo&amp;lt;v8::Value&amp;gt;&amp;amp; args) {
  v8::Isolate* isolate = args.GetIsolate();
  args.GetReturnValue().Set(v8::String::NewFromUtf8(isolate, &quot;Hello, world from C++!&quot;).ToLocalChecked());
}

void Initialize(v8::Local&amp;lt;v8::Object&amp;gt; exports) {
  NODE_SET_METHOD(exports, &quot;hello&quot;, HelloWorld);
}

NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize)
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;The Binding Configuration 📐&lt;/h4&gt;
&lt;p&gt;Create a &lt;code&gt;binding.gyp&lt;/code&gt; file with the following content:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
  &quot;targets&quot;: [
    {
      &quot;target_name&quot;: &quot;hello&quot;,
      &quot;sources&quot;: [&quot;hello.cc&quot;]
    }
  ]
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Compilation 🔨&lt;/h4&gt;
&lt;p&gt;Navigate to your project folder and run:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
  &quot;scripts&quot;: {
    &quot;build&quot;: &quot;node-gyp configure build&quot;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If everything goes as planned, you should see a &lt;code&gt;build/&lt;/code&gt; directory containing your compiled native module.&lt;/p&gt;
&lt;h4&gt;Using the Module in Node.js 📦&lt;/h4&gt;
&lt;p&gt;Finally, let&apos;s use this native module in a Node.js script. Create a &lt;code&gt;test.js&lt;/code&gt; file with the following content:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const addon = require(&quot;./build/Release/hello.node&quot;);
console.log(addon.hello()); // Outputs &quot;Hello, world from C++!&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Run the script:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
  &quot;scripts&quot;: {
    &quot;build&quot;: &quot;node-gyp configure build&quot;,
    &quot;dev&quot;: &quot;node test.js&quot;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You should see &lt;code&gt;&quot;Hello, world from C++!&quot;&lt;/code&gt; printed to the console. Congratulations, you&apos;ve just created and used your first native Node.js module!&lt;/p&gt;
&lt;h3&gt;Setting Up Language Server Protocol (LSP) 🧝&lt;/h3&gt;
&lt;p&gt;When developing native modules, it&apos;s extremely beneficial to have an IDE or text editor that understands C/C++ for features like IntelliSense, refactoring, and error checking. LSP can help with this, and luckily, we can generate a &lt;code&gt;compile_commands.json&lt;/code&gt; file to make this happen. Below is a helper script that can automate this process for you. This script is adapted from a &lt;a href=&quot;https://github.com/nodejs/node-gyp/issues/1526#issuecomment-610670026&quot;&gt;GitHub issue discussion&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;First, create a script named &lt;code&gt;lsp.sh&lt;/code&gt; and paste the following code into it:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#!/bin/bash

# Configure node-gyp with pnpm
if ! pnpm node-gyp configure --release -- -f gyp.generator.compile_commands_json.py &amp;gt;/dev/null 2&amp;gt;&amp;amp;1; then
 echo &quot;Error configuring node-gyp.&quot;
 exit 1
fi

# Move compile_commands.json and remove &apos;Release&apos; directory
if ! mv Release/compile_commands.json ./ &amp;gt;/dev/null 2&amp;gt;&amp;amp;1 || ! rm -r Release &amp;gt;/dev/null 2&amp;gt;&amp;amp;1; then
 echo &quot;Error moving compile_commands.json or removing &apos;Release&apos; directory.&quot;
 exit 1
fi

# Remove extra compile_commands.json and their directories
EXTRA=$(find . -mindepth 2 -name &apos;compile_commands.json&apos;)
if ! echo &quot;$EXTRA&quot; | xargs rm -f &amp;gt;/dev/null 2&amp;gt;&amp;amp;1; then
 echo &quot;Error removing extra compile_commands.json files.&quot;
 exit 1
fi

# Remove empty directories
echo &quot;$EXTRA&quot; | xargs -n1 dirname | while read -r dir; do
 if [ -z &quot;$(ls -A &quot;$dir&quot;)&quot; ]; then
  if ! rm -r &quot;$dir&quot; &amp;gt;/dev/null 2&amp;gt;&amp;amp;1; then
   echo &quot;Error removing empty directory: $dir&quot;
   exit 1
  fi
 fi
done

# Retrieve and escape compiler flags
ESCAPED_FLAGS=$(echo | cc -Wp,-v -x c++ - -fsyntax-only 2&amp;gt;&amp;amp;1 |
 grep -E &apos;^ /&apos; | sed &apos;s/^ /-isystem /&apos; | sed &apos;s/\//\\\//g&apos; | tr &apos;\n&apos; &apos; &apos;)

if [ -z &quot;$ESCAPED_FLAGS&quot; ]; then
 echo &quot;Error retrieving compiler flags.&quot;
 exit 1
fi

# Update compile_commands.json
if ! awk -i inplace -v flags=&quot;$ESCAPED_FLAGS&quot; &apos;{gsub(/ -c /, &quot; &quot; flags &quot; -c &quot;); print}&apos; compile_commands.json &amp;gt;/dev/null 2&amp;gt;&amp;amp;1; then
 echo &quot;Error updating compile_commands.json.&quot;
 exit 1
fi
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Make sure to give execute permission to the script:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;chmod +x lsp.sh
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now, add the following line to your &lt;code&gt;package.json&lt;/code&gt; under the &quot;scripts&quot; section:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
  &quot;scripts&quot;: {
    &quot;build&quot;: &quot;node-gyp configure build &amp;amp;&amp;amp; ./lsp.sh&quot;,
    &quot;dev&quot;: &quot;node test.js&quot;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This way, the &lt;code&gt;lsp.sh&lt;/code&gt; script will run automatically when you execute &lt;code&gt;npm run build{:bash}&lt;/code&gt; or &lt;code&gt;pnpm run build{:bash}&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;With this setup, you can enjoy a more interactive and responsive development environment while working on your native Node.js modules. Feel free to integrate this with your favorite text editor or IDE that supports LSP for C/C++.&lt;/p&gt;
&lt;p&gt;This can be a boon for your productivity, especially if you&apos;re already accustomed to such features while working in TypeScript or Rust.&lt;/p&gt;
&lt;p&gt;This LSP setup will provide you with rich coding features such as autocompletion, go to definition, and real-time error checking, making your development process much smoother. 🌟&lt;/p&gt;
&lt;h3&gt;The Complexity of Direct Node API 😵‍💫&lt;/h3&gt;
&lt;p&gt;The Direct Node API, often referred to as Node-API or N-API, is robust and extremely flexible but can be verbose and intricate.
It exposes a set of primitive APIs that deal directly with JavaScript objects and values. Though it allows for high customization and
deep integration, it requires you to handle several underlying complexities like object lifetimes, scopes, and type conversions manually.
This can be cumbersome for those accustomed to more abstracted or user-friendly interfaces, especially when you just want to get a project
off the ground.&lt;/p&gt;
&lt;p&gt;For example, the previous allegedly simple &lt;code&gt;&quot;Hello, World!&quot;{:javascript}&lt;/code&gt; example using the Direct Node API would look like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#include &amp;lt;node.h&amp;gt;

void HelloWorld(const v8::FunctionCallbackInfo&amp;lt;v8::Value&amp;gt;&amp;amp; args) {
  v8::Isolate* isolate = args.GetIsolate();
  args.GetReturnValue().Set(v8::String::NewFromUtf8(isolate, &quot;Hello, World!&quot;));
}

void Initialize(v8::Local&amp;lt;v8::Object&amp;gt; exports) {
  NODE_SET_METHOD(exports, &quot;hello&quot;, HelloWorld);
}

NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see, even for a simple &lt;code&gt;&quot;Hello, World!&quot;{:javascript}&lt;/code&gt;, the code has a fair bit of boilerplate.&lt;/p&gt;
&lt;h3&gt;Why I Prefer node-addon-api 🌟&lt;/h3&gt;
&lt;p&gt;For better usability, we will use &lt;a href=&quot;https://github.com/nodejs/node-addon-api&quot;&gt;&lt;strong&gt;node-addon-api&lt;/strong&gt;&lt;/a&gt;, an abstraction layer on top of the Direct Node API.
It provides an object-oriented C++ API, which considerably simplifies the complexity and makes it easier to manage.
It&apos;s essentially the C++ sugar on top of the Direct Node API&apos;s C-based interface.&lt;/p&gt;
&lt;p&gt;To give you a contrast, let&apos;s rewrite our &lt;code&gt;&quot;Hello, World!&quot;{:javascript}&lt;/code&gt; example using &lt;code&gt;node-addon-api&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#include &amp;lt;napi.h&amp;gt;

Napi::String HelloWorld(const Napi::CallbackInfo&amp;amp; info) {
  Napi::Env env = info.Env();
  return Napi::String::New(env, &quot;Hello, World from C++ [with NAPI]!&quot;);
}

Napi::Object Init(Napi::Env env, Napi::Object exports) {
  exports.Set(&quot;hello&quot;, Napi::Function::New(env, HelloWorld));
  return exports;
}

NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see, this version of &lt;code&gt;&quot;Hello, World!&quot;{:javascript}&lt;/code&gt; is cleaner and more straightforward.
This is why we&apos;ll proceed with &lt;code&gt;node-addon-api&lt;/code&gt; for our deeper exploration and for building our example application.
With its simplified API and user-friendly features, &lt;code&gt;node-addon-api&lt;/code&gt; is an excellent choice for developers looking to create native Node.js
addons without diving deep into the intricacies of the Direct Node API.&lt;/p&gt;
&lt;h3&gt;Required Packages and Adapted &lt;code&gt;binding.gyp&lt;/code&gt; 📦&lt;/h3&gt;
&lt;p&gt;Before diving into the code, let&apos;s first install the necessary package for &lt;code&gt;node-addon-api&lt;/code&gt;. Run the following command in your project directory:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;pnpm add node-addon-api
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Adapted &lt;code&gt;binding.gyp&lt;/code&gt; 🛠️&lt;/h4&gt;
&lt;p&gt;You&apos;ll also need to modify your &lt;code&gt;binding.gyp&lt;/code&gt; file to include &lt;code&gt;node-addon-api&lt;/code&gt;&apos;s header files. Here&apos;s how your &lt;code&gt;binding.gyp&lt;/code&gt; should look:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
  &quot;targets&quot;: [
    {
      &quot;target_name&quot;: &quot;hello&quot;,
      &quot;sources&quot;: [&quot;hello.cc&quot;],
      &quot;include_dirs&quot;: [&quot;&amp;lt;!@(node -p \&quot;require(&apos;node-addon-api&apos;).include\&quot;)&quot;],
      &quot;dependencies&quot;: [&quot;&amp;lt;!(node -p \&quot;require(&apos;node-addon-api&apos;).gyp\&quot;)&quot;],
      &quot;cflags!&quot;: [&quot;-fno-exceptions&quot;],
      &quot;cflags_cc!&quot;: [&quot;-fno-exceptions&quot;],
      &quot;defines&quot;: [&quot;NAPI_DISABLE_CPP_EXCEPTIONS&quot;]
    }
  ]
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;There is always cases of platform specific configurations like the following, but I wont be covering them here:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
  &quot;targets&quot;: [
    {
      &quot;target_name&quot;: &quot;hello&quot;,
      &quot;sources&quot;: [&quot;hello.cc&quot;],
      &quot;include_dirs&quot;: [&quot;&amp;lt;!@(node -p \&quot;require(&apos;node-addon-api&apos;).include\&quot;)&quot;],
      &quot;dependencies&quot;: [&quot;&amp;lt;!(node -p \&quot;require(&apos;node-addon-api&apos;).gyp\&quot;)&quot;],
      &quot;cflags!&quot;: [&quot;-fno-exceptions&quot;],
      &quot;cflags_cc!&quot;: [&quot;-fno-exceptions&quot;],
      &quot;defines&quot;: [&quot;NAPI_DISABLE_CPP_EXCEPTIONS&quot;],
      &quot;xcode_settings&quot;: {
        &quot;GCC_ENABLE_CPP_EXCEPTIONS&quot;: &quot;YES&quot;,
        &quot;CLANG_CXX_LIBRARY&quot;: &quot;libc++&quot;,
        &quot;MACOSX_DEPLOYMENT_TARGET&quot;: &quot;10.7&quot;
      },
      &quot;msvs_settings&quot;: {
        &quot;VCCLCompilerTool&quot;: {
          &quot;ExceptionHandling&quot;: 1
        }
      }
    }
  ]
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Understanding the &lt;code&gt;&amp;lt;!@(){:bash}&lt;/code&gt; and &lt;code&gt;&amp;lt;!(){:bash}&lt;/code&gt; Syntax in &lt;code&gt;binding.gyp&lt;/code&gt; 🔍&lt;/h3&gt;
&lt;p&gt;In your &lt;code&gt;binding.gyp&lt;/code&gt; file, you might have noticed some unfamiliar syntax: &lt;code&gt;&amp;lt;!@(){:bash}&lt;/code&gt; and &lt;code&gt;&amp;lt;!(){:bash}&lt;/code&gt;. These are special directives that help with dynamic evaluation within the &lt;code&gt;.gyp&lt;/code&gt; files. Let&apos;s break down what each does:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;&amp;lt;!(){:bash}&lt;/code&gt;: This directive allows you to execute a shell command. The output of this command is then captured and used in the &lt;code&gt;.gyp&lt;/code&gt; file.&lt;/p&gt;
&lt;p&gt;For instance, &lt;code&gt;&amp;lt;!(node -p &quot;require(&apos;node-addon-api&apos;).gyp&quot;){:bash}&lt;/code&gt; executes the node command that fetches the path to the &lt;code&gt;.gyp&lt;/code&gt; file of the &lt;code&gt;node-addon-api&lt;/code&gt; package.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;&amp;lt;!@(){:bash}&lt;/code&gt;: Similar to the previous one, this directive also executes a shell command. However, the output is tokenized by whitespace, allowing you to capture multiple output entries.&lt;/p&gt;
&lt;p&gt;In &lt;code&gt;&amp;lt;!@(node -p &quot;require(&apos;node-addon-api&apos;).include&quot;){:bash}&lt;/code&gt;, the command fetches the include directories for &lt;code&gt;node-addon-api&lt;/code&gt;,
and because we use &lt;code&gt;&amp;lt;!@(){:bash}&lt;/code&gt;, multiple directories would be handled correctly if present.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Understanding these directives gives you the flexibility to perform more complex operations dynamically, right within your &lt;code&gt;binding.gyp&lt;/code&gt; configuration.&lt;/p&gt;
&lt;h3&gt;Re-Structuring the File Structure for Better Organization 🗂️&lt;/h3&gt;
&lt;p&gt;Now that we&apos;ve got a basic &lt;code&gt;&quot;Hello World&quot;{:javascript}&lt;/code&gt; example up and running, let&apos;s go a step further and reorganize our project structure
for better maintainability and scalability.&lt;/p&gt;
&lt;h4&gt;Target Structure&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;./addon/src&lt;/code&gt;: This is where all your C++ &lt;code&gt;.cc&lt;/code&gt; files will reside.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;./addon/include&lt;/code&gt;: This folder will contain all your header &lt;code&gt;.hpp&lt;/code&gt; files.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;./lib/binding.js&lt;/code&gt;: A JavaScript wrapper around the native node bindings.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;./tests&lt;/code&gt;: This will contain all your test files.&lt;/li&gt;
&lt;/ul&gt;
&lt;hr /&gt;
&lt;pre&gt;&lt;code&gt;#pragma once

#include &amp;lt;napi.h&amp;gt;

namespace fast_image_resizer {
  Napi::String hello_world(const Napi::CallbackInfo &amp;amp;info);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;#pragma once

#include &amp;lt;napi.h&amp;gt;

namespace fast_image_resizer {
  void exports(Napi::Env env, Napi::Object exports);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;hr /&gt;
&lt;pre&gt;&lt;code&gt;#include &amp;lt;fast-image-resizer/hello.hpp&amp;gt;

namespace fast_image_resizer {
  Napi::String hello_world(const Napi::CallbackInfo &amp;amp;info) {
    Napi::Env env = info.Env();
    return Napi::String::New(env, &quot;Hello, World from C++ [with NAPI]!&quot;);
  }
}  // namespace fast_image_resizer
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;#include &amp;lt;fast-image-resizer/exports.hpp&amp;gt;
#include &amp;lt;fast-image-resizer/hello.hpp&amp;gt;

namespace fast_image_resizer {
  void exports(Napi::Env env, Napi::Object exports) {
    exports.Set(&quot;helloWorld&quot;, Napi::Function::New(env, fast_image_resizer::hello_world));
  }
}  // namespace fast_image_resizer
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;#include &amp;lt;napi.h&amp;gt;

#include &amp;lt;fast-image-resizer/exports.hpp&amp;gt;

Napi::Object Init(Napi::Env env, Napi::Object exports) {
  fast_image_resizer::exports(env, exports);

  return exports;
}

NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Resulting in the following tree:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;tree addon
addon
├── include
│   └── fast-image-resizer
│       ├── exports.hpp
│       └── hello.hpp
└── src
    ├── entrypoint.cc
    └── fast-image-resizer
        ├── exports.cc
        └── hello.cc

5 directories, 5 files
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Updated &lt;code&gt;binding.gyp&lt;/code&gt;&lt;/h4&gt;
&lt;p&gt;To facilitate this restructured file hierarchy, we&apos;ll need to modify our &lt;code&gt;binding.gyp&lt;/code&gt; file. We&apos;ll configure it to automatically detect all &lt;code&gt;.cc&lt;/code&gt; and &lt;code&gt;.hpp&lt;/code&gt; files in their respective directories. Here is how to do it:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
  &quot;targets&quot;: [
    {
      &quot;target_name&quot;: &quot;fast-image-resizer&quot;,
      &quot;sources&quot;: [&quot;&amp;lt;!@(find addon/src -name *.cc)&quot;],
      &quot;include_dirs&quot;: [
        &quot;&amp;lt;!(node -p \&quot;require(&apos;node-addon-api&apos;).include_dir\&quot;)&quot;,
        &quot;/usr/local/include/&quot;,
        &quot;&amp;lt;(module_root_dir)/addon/include&quot;
      ],
      &quot;dependencies&quot;: [&quot;&amp;lt;!(node -p \&quot;require(&apos;node-addon-api&apos;).gyp\&quot;)&quot;],
      &quot;cflags!&quot;: [&quot;-fno-exceptions&quot;],
      &quot;cflags_cc!&quot;: [&quot;-fno-exceptions&quot;],
      &quot;defines&quot;: [&quot;NAPI_DISABLE_CPP_EXCEPTIONS&quot;]
    }
  ]
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here, the &lt;code&gt;find{:bash}&lt;/code&gt; shell command recursively looks for &lt;code&gt;.cc&lt;/code&gt; and &lt;code&gt;.hpp&lt;/code&gt; files within &lt;code&gt;./addon/src&lt;/code&gt; and &lt;code&gt;./addon/include&lt;/code&gt;, respectively.
This way, as you add more source and header files to these folders, you won&apos;t need to manually update &lt;code&gt;binding.gyp&lt;/code&gt;.&lt;/p&gt;
&lt;h4&gt;JavaScript Wrapper (&lt;code&gt;./lib/binding.ts&lt;/code&gt;)&lt;/h4&gt;
&lt;p&gt;Having a JavaScript wrapper around your native module can provide a cleaner and more JavaScript-friendly API.
You can simply require your native addon and wrap its functionalities in this file.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { helloWorld } from &quot;../build/Release/fast-image-resizer.node&quot;;

export { helloWorld };
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Test Directory (&lt;code&gt;./tests&lt;/code&gt;) 🧪&lt;/h4&gt;
&lt;p&gt;To ensure the reliability of our native module, it&apos;s essential to include automated tests. We&apos;ll be using the Node.js Test API for this purpose.&lt;/p&gt;
&lt;p&gt;First, add the &lt;code&gt;tsx&lt;/code&gt; library as a dev dependency, as we&apos;ll use it to transpile and run our TypeScript test files.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;pnpm i -D tsx
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Next, update your &lt;code&gt;package.json&lt;/code&gt; file to include the following test command:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
  &quot;scripts&quot;: {
    &quot;build&quot;: &quot;node-gyp configure build &amp;amp;&amp;amp; ./scripts/lsp.sh&quot;,
    &quot;test&quot;: &quot;tsx --test tests/*&quot;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;Btw, I just moved lsp.sh to a &lt;code&gt;scripts&lt;/code&gt; directory.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;This command will transpile and execute all test files located in the &lt;code&gt;tests/&lt;/code&gt; directory.&lt;/p&gt;
&lt;p&gt;Now, let&apos;s write our test using the Node.js Test API. Create a TypeScript file in your &lt;code&gt;./tests&lt;/code&gt; directory with the following code:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { describe, it } from &quot;node:test&quot;;
import assert from &quot;node:assert&quot;;

import { helloWorld } from &quot;../lib/binding&quot;;

describe(&quot;helloWorld&quot;, () =&amp;gt; {
  it(&quot;should return &apos;Hello, World from C++ [with NAPI]!&apos;&quot;, () =&amp;gt; {
    assert.strictEqual(helloWorld(), &quot;Hello, World from C++ [with NAPI]!&quot;);
  });
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This test uses the &lt;code&gt;describe&lt;/code&gt; and &lt;code&gt;it&lt;/code&gt; functions from the Node.js Test API along with the &lt;code&gt;assert&lt;/code&gt; module to ensure that the &lt;code&gt;helloWorld&lt;/code&gt; function behaves as expected.&lt;/p&gt;
&lt;p&gt;To run the tests, execute the following command from the root of your project:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;npm test
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;&amp;gt; tsx --test tests/*

▶ helloWorld
  should return &apos;Hello, World from C++ [with NAPI]!&apos; (0.295912ms)
  helloWorld (1.314167ms)

ℹ duration_ms 92.176873
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;tsx --test tests/*&lt;/code&gt; command will take care of transpiling the TypeScript files and running the tests. Ensure that all tests pass to verify the functionality of your native module.&lt;/p&gt;
&lt;p&gt;Profit 📈.&lt;/p&gt;
&lt;h3&gt;Finalizing the Implementation: Image Resizing with OpenCV 🖼️🛠️&lt;/h3&gt;
&lt;p&gt;Having set up the fundamental aspects of our environment, we&apos;re ready to tackle a more intricate
task — building a native module to resize images. In this endeavor, we will employ the powerful OpenCV C++ library.&lt;/p&gt;
&lt;h4&gt;Installing OpenCV Dependency&lt;/h4&gt;
&lt;p&gt;The steps to install OpenCV may vary depending on your operating system:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Ubuntu/Linux&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;sudo apt-get install libopencv-dev
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;&amp;lt;br /&amp;gt;&lt;/h2&gt;
&lt;p&gt;{&quot; &quot;}&lt;/p&gt;
&lt;p&gt;&amp;lt;br /&amp;gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;pacman -S opencv
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; For Arch users, installing &lt;code&gt;hdf5&lt;/code&gt; and &lt;code&gt;vtk&lt;/code&gt; may also be necessary.&lt;/p&gt;
&lt;p&gt;{&quot; &quot;}&lt;/p&gt;
&lt;p&gt;&amp;lt;br /&amp;gt;&lt;/p&gt;
&lt;hr /&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;macOS&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;brew install opencv
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;hr /&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Windows&lt;/strong&gt;
Download and install from &lt;a href=&quot;https://opencv.org/releases/&quot;&gt;OpenCV&apos;s website&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4&gt;Update binding.gyp&lt;/h4&gt;
&lt;p&gt;Next, tweak your binding.gyp file to accommodate OpenCV headers and libraries. Take note that if you encounter issues with
&lt;code&gt;pkg-config --cflags{:bash}&lt;/code&gt;, specifying the full path to the headers might resolve the issue.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
  &quot;targets&quot;: [
    {
      &quot;target_name&quot;: &quot;addon&quot;,
      &quot;sources&quot;: [
        &quot;./addon/src/*.cc&quot;
      ],
      &quot;include_dirs&quot;: [
        &quot;&amp;lt;!(node -p \&quot;require(&apos;node-addon-api&apos;).include_dir\&quot;)&quot;,
        &quot;&amp;lt;(module_root_dir)/addon/include&quot;,
        &quot;/usr/local/include/&quot;,
        &quot;/usr/include/opencv4&quot; # In my case it was located here
        # you can also try `&amp;lt;!@(pkg-config --cflags opencv4)` but
        # for me it was not working properly
      ],
      &quot;libraries&quot;: [
        &quot;&amp;lt;!(pkg-config --libs opencv4 2&amp;gt;/dev/null || echo &apos;&apos;)&quot; # In case of errors
      ],
      &quot;dependencies&quot;: [
        &quot;&amp;lt;!(node -p \&quot;require(&apos;node-addon-api&apos;).gyp\&quot;)&quot;,
      ],
      &quot;cflags!&quot;: [ &quot;-fno-exceptions&quot;, &quot;-std=c++20&quot; ],
      &quot;cflags_cc!&quot;: [ &quot;-fno-exceptions&quot;, &quot;-std=c++20&quot; ],
      &apos;defines&apos;: [ &apos;NAPI_DISABLE_CPP_EXCEPTIONS&apos; ]
    }
  ]
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;C++ Code&lt;/h4&gt;
&lt;p&gt;Start by declaring new functions in &lt;code&gt;addon/include/fast-image-resizer/resize.hpp&lt;/code&gt;.
The &lt;code&gt;Napi::Value get_file_dimensions(const Napi::CallbackInfo &amp;amp;info){:cpp}&lt;/code&gt; function will serve as a helper for testing,
negating the need to worry about its JavaScript implementation.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#pragma once

#include &amp;lt;napi.h&amp;gt;

namespace fast_image_resizer {
  Napi::Value resize(const Napi::CallbackInfo &amp;amp;info);
  Napi::Value get_file_dimensions(const Napi::CallbackInfo &amp;amp;info);
}  // namespace fast_image_resizer
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Then, proceed to flesh out the logic in &lt;code&gt;addon/src/fast-image-resizer/resize.cc&lt;/code&gt;.
First, we import the required headers, followed by parameter validation based on the API we&apos;re targeting.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#include &amp;lt;fast-image-resizer/resize.hpp&amp;gt;

#include &amp;lt;cstdint&amp;gt;
#include &amp;lt;filesystem&amp;gt;

#include &amp;lt;opencv2/core/mat.hpp&amp;gt;
#include &amp;lt;opencv2/imgcodecs.hpp&amp;gt;
#include &amp;lt;opencv2/imgproc.hpp&amp;gt;

namespace fast_image_resizer {

  Napi::Value resize(const Napi::CallbackInfo &amp;amp;info) {
  }

  Napi::Value get_file_dimensions(const Napi::CallbackInfo &amp;amp;info) {
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The API we will create expects an input path and dimensions for width and height.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export function resize(inputPath: string, width: number, height: number): void;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The resize operation will happen in-place — no bells and whistles. If you&apos;re looking to extend this functionality, the ball&apos;s in your court, reader 🤠.
The first order of business is to validate the number and types of arguments passed in.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Napi::Value resize(const Napi::CallbackInfo &amp;amp;info) {
  Napi::Env env = info.Env();

  if (info.Length() &amp;lt; 3) {
    Napi::TypeError::New(env, &quot;Wrong number of arguments&quot;).ThrowAsJavaScriptException();
    return env.Null();
  }

  if (!info[0].IsString() || !info[1].IsNumber() || !info[2].IsNumber()) {
    Napi::TypeError::New(env, &quot;Wrong arguments&quot;).ThrowAsJavaScriptException();
    return env.Null();
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You could consider a more elegant JavaScript API that takes in an object instead of individual parameters.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export function resize(params: {
  inputPath: string;
  width: number;
  height: number;
}): void;
&lt;/code&gt;&lt;/pre&gt;
&lt;hr /&gt;
&lt;p&gt;After validating the basics, the next step is to extract the parameters from the info object and ensure they&apos;re correct — like confirming
the file path actually exists or that the dimensions are positive numbers.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Napi::Value resize(const Napi::CallbackInfo &amp;amp;info) {
  // ...

  std::filesystem::path path = {info[0].As&amp;lt;Napi::String&amp;gt;()};
  int32_t width = info[1].As&amp;lt;Napi::Number&amp;gt;();
  int32_t height = info[2].As&amp;lt;Napi::Number&amp;gt;();

  // Validate path by empty string and by valid file
  if (path.empty() || !std::filesystem::exists(path)) {
    Napi::TypeError::New(env, &quot;Wrong path &quot; + path.string()).ThrowAsJavaScriptException();
    return env.Null();
  }

  // Validate width and height by positive values
  if (width &amp;lt;= 0 || height &amp;lt;= 0) {
    Napi::TypeError::New(env, &quot;Wrong width or height&quot;).ThrowAsJavaScriptException();
    return env.Null();
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Finally, we get to the part where the actual resizing happens. This is a straightforward operation, thanks to OpenCV.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Napi::Value resize(const Napi::CallbackInfo &amp;amp;info) {
  // ...

  // Read image from path
  cv::Mat image = cv::imread(path);

  // Resize image
  cv::resize(image, image, cv::Size(width, height));

  // Write image to path
  cv::imwrite(path, image);

  return env.Null();
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&amp;lt;details&amp;gt;
&amp;lt;summary&amp;gt;&amp;lt;strong&amp;gt;Here&apos;s the full code for the &lt;code&gt;resize&lt;/code&gt; function for your reference.&amp;lt;/strong&amp;gt;&amp;lt;/summary&amp;gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Napi::Value resize(const Napi::CallbackInfo &amp;amp;info) {
  Napi::Env env = info.Env();

  if (info.Length() &amp;lt; 3) {
    Napi::TypeError::New(env, &quot;Wrong number of arguments&quot;).ThrowAsJavaScriptException();
    return env.Null();
  }

  if (!info[0].IsString() || !info[1].IsNumber() || !info[2].IsNumber()) {
    Napi::TypeError::New(env, &quot;Wrong arguments&quot;).ThrowAsJavaScriptException();
    return env.Null();
  }

  std::filesystem::path path = {info[0].As&amp;lt;Napi::String&amp;gt;()};
  int32_t width = info[1].As&amp;lt;Napi::Number&amp;gt;();
  int32_t height = info[2].As&amp;lt;Napi::Number&amp;gt;();

  // Validate path by empty string and by valid file
  if (path.empty() || !std::filesystem::exists(path)) {
    Napi::TypeError::New(env, &quot;Wrong path &quot; + path.string()).ThrowAsJavaScriptException();
    return env.Null();
  }

  // Validate width and height by positive values
  if (width &amp;lt;= 0 || height &amp;lt;= 0) {
    Napi::TypeError::New(env, &quot;Wrong width or height&quot;).ThrowAsJavaScriptException();
    return env.Null();
  }

  // Read image from path
  cv::Mat image = cv::imread(path);

  // Resize image
  cv::resize(image, image, cv::Size(width, height));

  // Write image to path
  cv::imwrite(path, image);

  return env.Null();
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&amp;lt;/details&amp;gt;&lt;/p&gt;
&lt;p&gt;In addition to resizing, it&apos;s often necessary to gather information about an image, like its dimensions.
Let&apos;s explore how this could be implemented. For the dimensions, the approach is quite similar to the resizing logic.
We use OpenCV to read the image and then extract its width and height.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;cv::Mat image = cv::imread(path);

Napi::Object dimensions = Napi::Object::New(env);
dimensions.Set(&quot;width&quot;, image.cols);
dimensions.Set(&quot;height&quot;, image.rows);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&amp;lt;details&amp;gt;
&amp;lt;summary&amp;gt;&amp;lt;strong&amp;gt;Here is the full code for the &lt;code&gt;getFileDimensions&lt;/code&gt; function:&amp;lt;/strong&amp;gt;&amp;lt;/summary&amp;gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Napi::Value get_file_dimensions(const Napi::CallbackInfo &amp;amp;info) {
  Napi::Env env = info.Env();

  if (info.Length() &amp;lt; 1) {
    Napi::TypeError::New(env, &quot;Wrong number of arguments&quot;).ThrowAsJavaScriptException();
    return env.Null();
  }

  if (!info[0].IsString()) {
    Napi::TypeError::New(env, &quot;Wrong arguments&quot;).ThrowAsJavaScriptException();
    return env.Null();
  }

  std::filesystem::path path = {info[0].As&amp;lt;Napi::String&amp;gt;()};

  // Validate path by empty string and by valid filesystem
  if (path.empty() || !std::filesystem::exists(path)) {
    Napi::TypeError::New(env, &quot;Wrong path &quot; + path.string()).ThrowAsJavaScriptException();
    return env.Null();
  }

  // Return dimensions
  cv::Mat image = cv::imread(path);

  Napi::Object dimensions = Napi::Object::New(env);
  dimensions.Set(&quot;width&quot;, image.cols);
  dimensions.Set(&quot;height&quot;, image.rows);

  return dimensions;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&amp;lt;/details&amp;gt;&lt;/p&gt;
&lt;p&gt;Now, we just need to export this functions in &lt;code&gt;addon/src/fast-image-resizer/exports.cc&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#include &amp;lt;fast-image-resizer/exports.hpp&amp;gt;
#include &amp;lt;fast-image-resizer/hello.hpp&amp;gt;
#include &amp;lt;fast-image-resizer/resize.hpp&amp;gt;

namespace fast_image_resizer {
  void exports(Napi::Env env, Napi::Object exports) {
    exports.Set(&quot;helloWorld&quot;, Napi::Function::New(env, fast_image_resizer::hello_world));
    exports.Set(&quot;resize&quot;, Napi::Function::New(env, fast_image_resizer::resize));
    exports.Set(&quot;getFileDimensions&quot;,
                Napi::Function::New(env, fast_image_resizer::get_file_dimensions));
  }
}  // namespace fast_image_resizer
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;JavaScript Wrapper&lt;/h4&gt;
&lt;p&gt;Reflect these changes in the JavaScript wrapper to expose the new functionalities:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import {
  helloWorld,
  resize,
  getFileDimensions,
} from &quot;../build/Release/fast-image-resizer.node&quot;;

export { helloWorld, resize, getFileDimensions };
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Update Tests&lt;/h4&gt;
&lt;p&gt;I just got lazy and generate a random image through &lt;code&gt;convert{:bash}&lt;/code&gt; with &lt;code&gt;convert -size 200x200 xc:skyblue dummy.png{:bash}&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;Now in &lt;code&gt;./tests/resize.test.ts&lt;/code&gt; I added a test to check if the original image was not 100x100 and if the resized image is 100x100:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { describe, it } from &quot;node:test&quot;;
import assert from &quot;node:assert&quot;;

import { resize, getFileDimensions } from &quot;../lib/binding&quot;;

describe(&quot;image&quot;, () =&amp;gt; {
  it(&quot;should have the correct dimensions&quot;, () =&amp;gt; {
    const { width, height } = getFileDimensions(&quot;./dummy.png&quot;);

    assert.notEqual(width, 100);
    assert.notEqual(height, 100);
  });
});

describe(&quot;resize&quot;, () =&amp;gt; {
  it(&quot;should resize the image&quot;, () =&amp;gt; {
    resize(&quot;./dummy.png&quot;, 100, 100);

    const { width, height } = getFileDimensions(&quot;./dummy.png&quot;);

    assert.strictEqual(width, 100);
    assert.strictEqual(height, 100);
  });
});
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Conclusion: The Power of Simplicity and What&apos;s Next 🎉🔮&lt;/h2&gt;
&lt;p&gt;We&apos;ve covered quite a bit of ground in this blog post. Starting from setting up your development environment to diving into the
nitty-gritty details of native modules in Node.js, it&apos;s been a rewarding journey. Let&apos;s recap:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;Tools and Environment Setup&lt;/code&gt;: We discussed the tools needed and initialized the project.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Setting Up node-gyp&lt;/code&gt;: We went through installing and verifying node-gyp for building native addons.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;First Native Module&lt;/code&gt;: Introduced you to the world of C++ for Node.js through a simple &lt;code&gt;&quot;Hello, World!&quot;{:javascript}&lt;/code&gt; example.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Language Server Protocol&lt;/code&gt;: Talked about the benefits of setting up LSP for a smoother development experience.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Direct Node API vs node-addon-api&lt;/code&gt;: We discussed why node-addon-api is the preferred way to interact with the Node.js runtime.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Required Packages and Configuration&lt;/code&gt;: Walked through additional setup steps, including editing binding.gyp.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Project Structure&lt;/code&gt;: We organized our files for better readability and maintainability.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Final Implementation with OpenCV&lt;/code&gt;: Demonstrated how to integrate OpenCV for image resizing.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Surprisingly, it&apos;s not that complex to extend Node.js with native modules, especially when you&apos;re backed by the right tools and community support.&lt;/p&gt;
&lt;h3&gt;A Glimpse into the Future: Crafting Your Own Framework 🛠️🔮&lt;/h3&gt;
&lt;p&gt;In our next blog post, &lt;strong&gt;&quot;Crafting Your Own Framework: A Masterclass on node-addon-api&quot;&lt;/strong&gt;, I&apos;ll introduce you to a more ergonomic way to create native modules in C++.
Imagine having better tooling to manage native modules, their dependencies, and handling the packaging efficiently — sounds exciting, right?&lt;/p&gt;
&lt;h3&gt;Packaging Native Modules 📦&lt;/h3&gt;
&lt;p&gt;Packaging native modules is a topic that&apos;s often glossed over. It&apos;s crucial to manage dependencies and ensure that the compiled
binary can be easily distributed and consumed. We&apos;ll delve into these intricate details and show you how to package your native modules
like a pro in our upcoming post.&lt;/p&gt;
&lt;hr /&gt;
&lt;h3&gt;Share Your Thoughts! 💭&lt;/h3&gt;
&lt;p&gt;We&apos;ve covered a lot, and your opinion matters. What did you find most helpful? Are there areas you&apos;d like more clarity on? Feel free to share your thoughts, questions, and suggestions in the comments section below. Your feedback helps make this a more comprehensive resource for everyone involved. Looking forward to hearing from you! 🌟&lt;/p&gt;
&lt;p&gt;So, stay tuned! This journey is far from over, and the road ahead is filled with opportunities to refine and expand your skill set.
See you in the next blog post!&lt;/p&gt;
</content:encoded></item><item><title>Native Modules in JavaScript: What is it?</title><link>https://daniel-boll.me/posts/going-native-on-javascript/native-modules/</link><guid isPermaLink="true">https://daniel-boll.me/posts/going-native-on-javascript/native-modules/</guid><description>What exactly are native modules? How do they work? How do they differ from JavaScript modules?</description><pubDate>Thu, 28 Sep 2023 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import Trivia from &quot;@components/mdx/Trivia.astro&quot;;&lt;/p&gt;
&lt;h2&gt;Introduction 🚀&lt;/h2&gt;
&lt;p&gt;Welcome to the first installment of our series, &lt;code&gt;&quot;Going Native on JavaScript!&quot;{:javascript}&lt;/code&gt; Whether you&apos;re a seasoned developer or
just getting started with &amp;lt;b&amp;gt;JavaScript&amp;lt;/b&amp;gt;, you&apos;ve likely encountered modules — reusable pieces of code that can be imported into your projects.
But have you ever heard of &amp;lt;b&amp;gt;native modules&amp;lt;/b&amp;gt;?&lt;/p&gt;
&lt;p&gt;Native modules are special types of modules that allow you to execute code written in languages like &amp;lt;b&amp;gt;C++&amp;lt;/b&amp;gt; directly within your Node.js application.
These modules can offer significant performance benefits and access to lower-level APIs that are not readily available in JavaScript.
So why aren&apos;t native modules as commonly discussed as their pure JavaScript counterparts?&lt;/p&gt;
&lt;p&gt;&amp;lt;Trivia emoji=&quot;🌍&quot;&amp;gt;
In this post, we&apos;ll delve deep into the world of native modules. We&apos;ll explore
what they are, why they&apos;re critical for certain applications, and how you can
get started with writing your own. Whether you&apos;re looking to optimize
performance or access unique system-level functionalities, native modules have
a lot to offer.
&amp;lt;/Trivia&amp;gt;&lt;/p&gt;
&lt;h2&gt;What are Native Modules? 🤔&lt;/h2&gt;
&lt;p&gt;You may be wondering, &lt;code&gt;&quot;What exactly are native modules, and how do they differ from the JavaScript modules I&apos;m familiar with?&quot;{:javascript}&lt;/code&gt;
Great questions! Native modules are essentially extensions for Node.js that enable execution of lower-level code, typically written in languages
like &amp;lt;b&amp;gt;C++&amp;lt;/b&amp;gt; or &amp;lt;b&amp;gt;Rust&amp;lt;/b&amp;gt;, directly in your Node.js environment.&lt;/p&gt;
&lt;h3&gt;Definition and Key Characteristics 🔍&lt;/h3&gt;
&lt;p&gt;A native module is a compiled piece of code that acts as a bridge between Node.js and functionalities written in other programming languages.
These modules are generally written in &amp;lt;b&amp;gt;C++&amp;lt;/b&amp;gt; and are loaded dynamically at runtime, allowing them to be used just like any regular &amp;lt;b&amp;gt;JavaScript&amp;lt;/b&amp;gt; module.&lt;/p&gt;
&lt;h3&gt;How Do They Differ From &amp;lt;b&amp;gt;JavaScript&amp;lt;/b&amp;gt; Modules? 🔄&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Performance&lt;/strong&gt;: Native modules often offer performance benefits, especially when it comes to CPU-intensive tasks,
as they run closer to the metal, so to speak.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Capabilities&lt;/strong&gt;: While JavaScript is a powerful language, there are operations it simply cannot perform or can perform only inefficiently.
Native modules fill these gaps by offering functionalities that are not natively available in JavaScript.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Language Interoperability&lt;/strong&gt;: Native modules can be written in multiple languages, giving you the flexibility to integrate codebases in
languages like &amp;lt;b&amp;gt;C++&amp;lt;/b&amp;gt; and &amp;lt;b&amp;gt;Rust&amp;lt;/b&amp;gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;In a Nutshell 🥜&lt;/h3&gt;
&lt;p&gt;&amp;lt;Trivia emoji=&quot;🥜&quot;&amp;gt;
Native modules serve as a gateway, opening up new possibilities beyond what is
achievable using only JavaScript. They act as a bridge between the high-level,
dynamically-typed world of JavaScript and the lower-level, statically-typed
realm of languages like C++ or Rust.
&amp;lt;/Trivia&amp;gt;&lt;/p&gt;
&lt;h2&gt;🎯 Why Use Native Modules?&lt;/h2&gt;
&lt;p&gt;Native modules are a powerful feature that can dramatically affect how you design and implement Node.js applications.
While they add complexity, the trade-offs can often be worth it, especially in performance-critical applications or
those that require low-level system access. In this section, we dive deeper into why you might consider using native modules in your next project.&lt;/p&gt;
&lt;h3&gt;🚀 Performance Benefits&lt;/h3&gt;
&lt;p&gt;One of the most compelling reasons to use native modules is the significant performance boost they offer for CPU-bound tasks.
Let&apos;s look at some key technical aspects:&lt;/p&gt;
&lt;h4&gt;Compiled Languages&lt;/h4&gt;
&lt;p&gt;Native modules often utilize compiled languages like &amp;lt;b&amp;gt;C++&amp;lt;/b&amp;gt; or &amp;lt;b&amp;gt;Rust&amp;lt;/b&amp;gt;. Compiled languages generally outperform interpreted languages like&lt;/p&gt;
&lt;p&gt;&amp;lt;b&amp;gt;JavaScript&amp;lt;/b&amp;gt; because the code is transformed into machine code, which is directly
executable by the computer&apos;s CPU.&lt;/p&gt;
&lt;h4&gt;Direct Memory Access&lt;/h4&gt;
&lt;p&gt;Unlike &amp;lt;b&amp;gt;JavaScript&amp;lt;/b&amp;gt;, which relies on garbage collection and automatic memory management, languages like &amp;lt;b&amp;gt;C++&amp;lt;/b&amp;gt; and &amp;lt;b&amp;gt;Rust&amp;lt;/b&amp;gt; allow for direct memory access.
This enables you to optimize memory usage manually, leading to faster execution times, especially in memory-intensive operations.&lt;/p&gt;
&lt;h4&gt;System-Level Optimizations&lt;/h4&gt;
&lt;p&gt;The closer you are to the hardware, the more room you have for optimization. Native modules enable more efficient CPU instruction sets, cache
optimizations, and other system-level performance improvements that are not accessible or are inefficient in a higher-level language like JavaScript.&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;{/&lt;em&gt;&amp;lt;SvgContainer svg={SystemLevelAPI} /&amp;gt;&lt;/em&gt;/}&lt;/p&gt;
&lt;p&gt;In this diagram, you&apos;ll notice two distinct pathways from your JavaScript code to the &amp;lt;b&amp;gt;System-Level APIs&amp;lt;/b&amp;gt;.
One goes through the Node.js Runtime, while the other proceeds directly through a Native Module.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&amp;lt;b&amp;gt;JavaScript&amp;lt;/b&amp;gt; Code to Node.js Runtime&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;When your &amp;lt;b&amp;gt;JavaScript&amp;lt;/b&amp;gt; code needs to perform an action like reading a file or sending network requests, it calls a function that interacts with the Node.js
Runtime. This runtime environment is a multi-layered construct, consisting of several components that each serve a specific purpose but also add
complexity and overhead.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Event Loop&lt;/strong&gt;: The heart of Node.js&apos;s non-blocking I/O capability. It enables asynchronous operations by queuing up tasks to be executed later.
However, it can also be a bottleneck, especially for CPU-bound tasks that can&apos;t be offloaded and must be executed sequentially.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;V8 Engine&lt;/strong&gt;: This is where your &amp;lt;b&amp;gt;JavaScript&amp;lt;/b&amp;gt; code actually gets executed. While V8 is highly optimized, it still can&apos;t match the speed of
running precompiled code for specific tasks in various cases, adding a layer of latency.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Garbage Collection&lt;/strong&gt;: The built-in memory management mechanism can, paradoxically, introduce delays. Though it relieves you from manual
memory management, the process of identifying and clearing unused memory can stall the execution flow.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;These layers cumulatively make the route through the Node.js Runtime slower, especially for performance-critical tasks.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Node.js Runtime to Native Module&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The second pathway moves from the Node.js Runtime directly to a Native Module, bypassing the complexities of the runtime environment. Native modules interact closely with system-level APIs and are usually written in compiled languages like &amp;lt;b&amp;gt;C++&amp;lt;/b&amp;gt; or &amp;lt;b&amp;gt;Rust&amp;lt;/b&amp;gt;.&lt;/p&gt;
&lt;p&gt;When you initiate a function call to a native module, you are essentially creating a shortcut, bypassing the event loop, the V8 engine, and garbage collection. This results in what the diagram illustrates as &lt;em&gt;&quot;Fast API Calls&quot;&lt;/em&gt;, leading to noticeably quicker interactions with system-level functionalities.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;The Ultimate Destination: System-Level APIs&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Regardless of the route taken, the ultimate objective is to interact with System-Level APIs to execute tasks like file manipulation, network requests, or other I/O operations. The difference lies in the efficiency and speed of reaching this layer. Native modules provide a more direct, unobstructed path, making them a highly advantageous choice for performance-intensive applications.&lt;/p&gt;
&lt;p&gt;By understanding the architecture outlined in this diagram, it becomes evident why native modules can be a game-changer for certain Node.js applications. They offer a more efficient pathway to System-Level APIs, bypassing the latency-inducing layers present within the Node.js Runtime.&lt;/p&gt;
&lt;hr /&gt;
&lt;h3&gt;💡 Access to Low-Level APIs&lt;/h3&gt;
&lt;p&gt;Native modules give you unparalleled access to system-level APIs, offering functionalities that are simply not available or inefficient in Node.js.
Here&apos;s why this is crucial:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;File Systems and I/O Operations&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;While Node.js provides basic file system APIs, they may not be suitable for all use-cases. For instance, you might need to access specific
file attributes or use low-level I/O operations that the Node.js APIs don&apos;t expose.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Networking Protocols&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Need to implement a custom networking protocol or use a less common one that isn&apos;t supported by Node.js? Native modules allow you to do just that.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Hardware Interactions&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;From accessing USB ports to communicating with IoT devices, native modules can provide the low-level access you need to interface directly
with hardware components.&lt;/p&gt;
&lt;h3&gt;🌍 Real-World Applications and Examples&lt;/h3&gt;
&lt;p&gt;The theoretical benefits of native modules are compelling, but let&apos;s ground this discussion with some real-world applications where going
native makes sense.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Data Science and Machine Learning&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Traditional data science languages like &amp;lt;b&amp;gt;Python&amp;lt;/b&amp;gt; have robust ecosystems for statistical analysis and machine learning. However, for real-time
data processing in a Node.js application, native modules can leverage optimized &amp;lt;b&amp;gt;C++&amp;lt;/b&amp;gt; or &amp;lt;b&amp;gt;Rust&amp;lt;/b&amp;gt; libraries to perform complex calculations much faster
than a native &amp;lt;b&amp;gt;JavaScript&amp;lt;/b&amp;gt; implementation.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Video and Audio Processing&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Real-time video and audio processing require high performance and low latency, something that native modules are particularly good at.
By tapping into low-level APIs and system resources, native modules can handle tasks like video encoding and decoding, noise reduction, and more.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Gaming Backends&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Highly interactive, real-time gaming backends require the utmost efficiency in handling numerous simultaneous connections and rapid data exchange.
Native modules can optimize networking protocols and data serialization techniques far beyond what&apos;s possible in plain &amp;lt;b&amp;gt;JavaScript&amp;lt;/b&amp;gt;.&lt;/p&gt;
&lt;p&gt;By understanding the benefits and real-world applications of native modules, you can make a well-informed decision on whether they are the right
choice for your project. They offer a potent combination of performance and functionality, albeit with added complexity. However, in scenarios
where performance, low-level access, or specialized functionalities are paramount, native modules can be a game-changing addition to your tech stack.&lt;/p&gt;
&lt;h2&gt;The Anatomy of a Native Module 🛠️&lt;/h2&gt;
&lt;p&gt;Understanding a native module&apos;s inner workings is paramount to appreciate its advantages fully. In this section, we&apos;ll dissect a native module, looking at its core components and how files are typically organized within it.&lt;/p&gt;
&lt;h3&gt;Core Components of a Native Module ⚙️&lt;/h3&gt;
&lt;p&gt;Native modules are primarily written in lower-level languages like &amp;lt;b&amp;gt;&amp;lt;b&amp;gt;C++&amp;lt;/b&amp;gt;&amp;lt;/b&amp;gt; or &amp;lt;b&amp;gt;&amp;lt;b&amp;gt;Rust&amp;lt;/b&amp;gt;&amp;lt;/b&amp;gt; and serve as a bridge between your Node.js code and system-level functionalities. Here are the core components you&apos;ll often encounter:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Binding Layer&lt;/strong&gt;: This is where the native module interacts with the Node.js runtime. It defines the functions, objects, and properties that your &amp;lt;b&amp;gt;JavaScript&amp;lt;/b&amp;gt; code can access. Typically implemented using Node&apos;s N-API or libraries like &lt;code&gt;node-gyp&lt;/code&gt; or &lt;code&gt;Neon&lt;/code&gt; for &amp;lt;b&amp;gt;Rust&amp;lt;/b&amp;gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Native Code&lt;/strong&gt;: The bulk of the native module, written in a compiled language. This is the part that carries out heavy computations or interacts directly with system-level APIs. Due to being precompiled, this code is highly optimized for performance.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Package Configuration&lt;/strong&gt;: Files like &lt;code&gt;binding.gyp&lt;/code&gt; for &amp;lt;b&amp;gt;C++&amp;lt;/b&amp;gt; or &lt;code&gt;Cargo.toml&lt;/code&gt; for &amp;lt;b&amp;gt;Rust&amp;lt;/b&amp;gt; specify how the module should be built. These files contain metadata and build instructions for the native module.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Exported Functions&lt;/strong&gt;: Functions that are exposed to your &amp;lt;b&amp;gt;JavaScript&amp;lt;/b&amp;gt; code, enabling interaction between the native module and your application.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Understanding these components allows for a deeper grasp of how native modules function and how they can be fine-tuned for optimal performance.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;TIP: Abuse shift+scroll to better visualize the following diagram.&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;{/&lt;em&gt;&amp;lt;SvgContainer svg={Flow} /&amp;gt;&lt;/em&gt;/}&lt;/p&gt;
&lt;h3&gt;File Structure and Organization 📂&lt;/h3&gt;
&lt;p&gt;A well-organized file structure is crucial for efficient development and maintenance of a native module. Although the specific organization can vary depending on the programming language and other requirements, you&apos;ll generally find directories for source code, package configuration, and more.&lt;/p&gt;
&lt;p&gt;For a detailed exploration of how package configurations like &lt;code&gt;binding.gyp&lt;/code&gt; play a vital role in the build process, be sure to check
out my next blog post: &lt;code&gt;&quot;Mastering Native Node.js Addons with node-addon-api: A Comprehensive Guide&quot;{:javascript}&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;{/&lt;em&gt;&amp;lt;SeeAlso slug=&quot;going-native-on-javascript-2&quot; /&amp;gt;&lt;/em&gt;/}&lt;/p&gt;
</content:encoded></item><item><title>Brewing a Full-Stack Breakfast with ExpressoTS, Bun, and Elysia</title><link>https://daniel-boll.me/posts/a-breakfest-with-expressots-and-bun/</link><guid isPermaLink="true">https://daniel-boll.me/posts/a-breakfest-with-expressots-and-bun/</guid><description>Combine the power of ExpressoTS with Bun&apos;s Elysia framework in TypeScript for a mouth-watering full-stack experience.</description><pubDate>Sun, 10 Sep 2023 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import Trivia from &quot;@components/mdx/Trivia.astro&quot;;&lt;/p&gt;
&lt;h2&gt;Introduction&lt;/h2&gt;
&lt;p&gt;Welcome to a hands-on guide focused on integrating ExpressoTS, Bun, and Elysia into a full-stack TypeScript application. Let&apos;s cut to the chase and see what ingredients we&apos;ll be working with.&lt;/p&gt;
&lt;h3&gt;Our Ingredients&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;h4&gt;&lt;a href=&quot;https://expresso-ts.com&quot;&gt;&lt;strong&gt;ExpressoTS&lt;/strong&gt;&lt;/a&gt;&lt;/h4&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This TypeScript framework is designed for server-side applications. It offers flexibility in project structure and supports multiple
architectural patterns, including MVC. If you like your applications like your coffee — robust and versatile — ExpressoTS is your go-to.&lt;/p&gt;
&lt;p&gt;{/&lt;em&gt;&amp;lt;SeeAlso slug=&quot;a-first-project-with-expressots&quot; /&amp;gt;&lt;/em&gt;/}&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;h4&gt;&lt;a href=&quot;https://bun.sh&quot;&gt;&lt;strong&gt;Bun&lt;/strong&gt;&lt;/a&gt;&lt;/h4&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;An all-in-one toolkit that brings speed and efficiency to your JavaScript and TypeScript projects.
Think of Bun as the wholesome bread holding all your stack&apos;s ingredients together.
It&apos;s an entire toolbox in one neat package, and it&apos;s faster than you can say &quot;bun in the oven.&quot;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;h4&gt;&lt;a href=&quot;https://elysiajs.com/&quot;&gt;&lt;strong&gt;ElysiaJS&lt;/strong&gt;&lt;/a&gt;&lt;/h4&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;A Bun web framework that promises performance, simplicity, and flexibility. Designed with TypeScript in mind, Elysia is like that final
touch of seasoning that takes your project from good to great.&lt;/p&gt;
&lt;p&gt;&amp;lt;Trivia emoji=&quot;🍳&quot;&amp;gt;
So, whether you&apos;re into French toast or a classic Eggs Benedict, the aim of
this blog post is to show you how to whip up a dish that&apos;s not just full of
flavor, but also robust and scalable.
&amp;lt;/Trivia&amp;gt;&lt;/p&gt;
&lt;h2&gt;Getting Started: Your First Bite of Elysia&lt;/h2&gt;
&lt;p&gt;Now that we&apos;ve set the table with the ingredients, let&apos;s start cooking. We&apos;ll begin by setting up a basic Elysia application using Bun.&lt;/p&gt;
&lt;h3&gt;1. Install Bun&lt;/h3&gt;
&lt;p&gt;First, you&apos;ll need to download and install Bun. Open your terminal and run the following command:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;curl -fsSL https://bun.sh/install | bash
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This will download and install Bun on your machine, equipping you with a fast and efficient JavaScript runtime.&lt;/p&gt;
&lt;h3&gt;2. Create Your Elysia Project&lt;/h3&gt;
&lt;p&gt;Once Bun is installed, it&apos;s time to create your Elysia project. Run:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;bun create elysia breakfast-ts
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You should see a message like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Created elysia project successfully

# To get started, run:

  cd breakfast-ts
  bun run src/index.ts
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;3. Run Your Application&lt;/h3&gt;
&lt;p&gt;Follow the instructions in the terminal message:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;cd breakfast-ts
bun run src/index.ts
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And just like that, you should see the message, instantaneously 🌪:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;🦊 Elysia is running at localhost:3000
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Voila! You&apos;ve just whipped up your first Elysia app, hot and fresh.&lt;/p&gt;
&lt;h3&gt;4. Verify Your Application&lt;/h3&gt;
&lt;p&gt;To verify Elysia&apos;s functionality, you can perform a health check using the provided endpoint. While I&apos;ll be using &lt;a href=&quot;https://httpie.io/&quot;&gt;httpie&lt;/a&gt; for its straightforward API, you&apos;re welcome to use &lt;code&gt;curl&lt;/code&gt; if you prefer.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;http :3000
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;HTTP/1.1 200 OK
Content-Length: 12
Date: Sun, 10 Sep 2023 20:47:46 GMT
content-type: text/plain;charset=utf-8

Hello Elysia
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Extending Elysia: Crafting a Simple User CRUD&lt;/h2&gt;
&lt;p&gt;With the basic setup out of the way, let&apos;s extend our Elysia app by adding some CRUD functionality for users.
This will serve as a good starting point before we dive into more complex operations in future posts.&lt;/p&gt;
&lt;h3&gt;1. Run Your Application in Watch Mode&lt;/h3&gt;
&lt;p&gt;First, stop the server if it&apos;s running. Then leverage Bun&apos;s watch mode, which will automatically reload the application
when changes are made to the source code:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;bun run --watch src/index.ts
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;2. Add User CRUD Routes&lt;/h3&gt;
&lt;p&gt;Now, let&apos;s define some basic CRUD operations. Open &lt;code&gt;src/index.ts&lt;/code&gt; and add to your existing code the following:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { Elysia } from &quot;elysia&quot;;

// Create a user route group
const user = new Elysia().group(&quot;user&quot;, (app) =&amp;gt;
  app
    .get(&quot;/&quot;, () =&amp;gt; &quot;All users&quot;)
    .get(&quot;/:id&quot;, (context) =&amp;gt; `Hello, ${context.params.id}`)
    .post(&quot;/&quot;, () =&amp;gt; &quot;Create User&quot;)
    .put(&quot;/:id&quot;, (context) =&amp;gt; `Update User ${context.params.id}`)
    .delete(&quot;/:id&quot;, (context) =&amp;gt; `Delete User ${context.params.id}`)
);

// Main app
const app = new Elysia()
  .get(&quot;/&quot;, () =&amp;gt; &quot;Hello Elysia&quot;)
  .use(user)
  .listen(3000);

console.log(
  `🦊 Elysia is running at ${app.server?.hostname}:${app.server?.port}`
);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here, we&apos;ve used Elysia&apos;s &lt;code&gt;group&amp;lt;Prefix extends string = string&amp;gt;(prefix: Prefix, run: (group: Elysia&amp;lt;...&amp;gt;)){:typescript}&lt;/code&gt; method to bundle all user-related routes together. We&apos;ve defined routes for getting all users, getting a single user by ID, creating a user, updating a user, and deleting a user.&lt;/p&gt;
&lt;h3&gt;3. More Advanced Features&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;&lt;em&gt;Note:&lt;/em&gt;&lt;/strong&gt; You can extend this basic setup in various ways. Elysia supports both simple state management within the server and more advanced
dependency injection techniques for robust applications. Check out Elysia&apos;s documentation on
&lt;a href=&quot;https://elysiajs.com/concept/state-decorate.html&quot;&gt;State Decorate&lt;/a&gt; and
&lt;a href=&quot;https://elysiajs.com/patterns/dependency-injection.html&quot;&gt;Dependency Injection&lt;/a&gt; if you&apos;re interested.&lt;/p&gt;
&lt;p&gt;&amp;lt;Trivia emoji=&quot;⌛&quot;&amp;gt;
For the sake of this blog post, we&apos;re keeping it simple. If you are willing to
expand your horizons, however, you are &lt;strong&gt;encouraged&lt;/strong&gt; to check out the &lt;a href=&quot;#call-to-action&quot;&gt;&lt;strong&gt;Call
to Action&lt;/strong&gt;&lt;/a&gt; section at the end of this post, where you may
help the ExpressoTS community in the bun integration.
&amp;lt;/Trivia&amp;gt;&lt;/p&gt;
&lt;h3&gt;4. Test Your User CRUD Endpoints&lt;/h3&gt;
&lt;p&gt;After running your server, you can test each endpoint to make sure they&apos;re working as intended.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;h4&gt;&lt;strong&gt;Get All Users&lt;/strong&gt;&lt;/h4&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code&gt;http :3001/user
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;HTTP/1.1 200 OK
Content-Length: 9
Date: Sun, 10 Sep 2023 20:47:46 GMT
content-type: text/plain;charset=utf-8

All users
&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;h4&gt;&lt;strong&gt;Get a Single User&lt;/strong&gt;&lt;/h4&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Replace &lt;code&gt;{id}&lt;/code&gt; with the ID of the user you&apos;re interested in.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;http :3001/user/42
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;HTTP/1.1 200 OK
Content-Length: 11
Date: Sun, 10 Sep 2023 20:47:46 GMT
content-type: text/plain;charset=utf-8

Hello, 42
&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;h4&gt;&lt;strong&gt;Create a User&lt;/strong&gt;&lt;/h4&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code&gt;http POST :3001/user
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;HTTP/1.1 200 OK
Content-Length: 11
Date: Sun, 10 Sep 2023 20:47:46 GMT
content-type: text/plain;charset=utf-8

Create User
&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;h4&gt;&lt;strong&gt;Update a User&lt;/strong&gt;&lt;/h4&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Again, replace &lt;code&gt;{id}&lt;/code&gt; with the ID of the user you want to update.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;http PUT :3001/user/42
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;HTTP/1.1 200 OK
Content-Length: 16
Date: Sun, 10 Sep 2023 20:47:46 GMT
content-type: text/plain;charset=utf-8

Update User 42
&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;h4&gt;&lt;strong&gt;Delete a User&lt;/strong&gt;&lt;/h4&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;And one last time, replace &lt;code&gt;{id}&lt;/code&gt; with the ID of the user you want to delete.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;http DELETE :3001/user/42
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;HTTP/1.1 200 OK
Content-Length: 16
Date: Sun, 10 Sep 2023 20:47:46 GMT
content-type: text/plain;charset=utf-8

Delete User 42
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now you&apos;ve successfully tested all of your user CRUD operations. It&apos;s like a full-course breakfast — everything is present and accounted for!&lt;/p&gt;
&lt;h2&gt;Diving into the Heart of the Matter: &lt;strong&gt;Reflection&lt;/strong&gt; and &lt;strong&gt;Decorators&lt;/strong&gt;&lt;/h2&gt;
&lt;p&gt;In programming, reflection is a mechanism that allows you to inspect and manipulate program elements like classes and objects at runtime. In other words, reflection enables a program to observe its own structure, similar to how you can observe your own reflection in the mirror. This allows for greater dynamic behavior, enabling more powerful and flexible constructs like decorators.&lt;/p&gt;
&lt;h3&gt;Enter the classic &lt;code&gt;import &quot;reflect-metadata&quot;{:typescript}&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;For our endeavor, we&apos;ll use &lt;strong&gt;&lt;em&gt;reflect-metadata&lt;/em&gt;&lt;/strong&gt;, a library that enables the addition and retrieval of runtime type metadata.
This is particularly useful when working with decorators in TypeScript.
With &lt;code&gt;import &quot;reflect-metadata&quot;{:typescript}&lt;/code&gt;, we can attach metadata directly to classes and properties, providing a deeper level of customization.&lt;/p&gt;
&lt;h3&gt;Installing &lt;em&gt;reflect-metadata&lt;/em&gt;&lt;/h3&gt;
&lt;p&gt;In the spirit of brevity, let&apos;s get it into our project right away. Execute the following command:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;bun add reflect-metadata@latest
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&amp;lt;Trivia emoji=&quot;🌪&quot;&amp;gt;
You&apos;ll notice how incredibly fast that was, god damn — another win for Bun.
&amp;lt;/Trivia&amp;gt;&lt;/p&gt;
&lt;p&gt;This sets the stage for us to delve into creating our ExpressoTS framework on top of Elysia, enriched with the powers of reflection and decorators. Trust me, it&apos;ll be the butter on the toast of our breakfast-themed stack!&lt;/p&gt;
&lt;h3&gt;Creating Our Pseudo-Framework&lt;/h3&gt;
&lt;p&gt;I&apos;ll create a directory &lt;code&gt;src/breakfast-ts/&lt;/code&gt; to house &lt;code&gt;src/breakfast-ts/decorators.ts&lt;/code&gt;, a crucial code file for our project.&lt;/p&gt;
&lt;h3&gt;Understanding the Building Blocks of Breakfast-TS: A Guide to Decorators&lt;/h3&gt;
&lt;p&gt;Let&apos;s take a moment to understand the decorators that make up the foundation of our Breakfast-TS pseudo-framework. If you&apos;re new to the concept of decorators or TypeScript metadata, fear not — this section aims to introduce these ideas step by step.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;h4&gt;&lt;strong&gt;What Are Symbols?&lt;/strong&gt;&lt;/h4&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Before diving into the decorators themselves, let&apos;s briefly discuss Symbols. A Symbol is a unique and immutable data type that is often used to identify object properties. In our code, we&apos;re using them to create unique keys for our metadata:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export const CONTROLLER_KEY = Symbol(&quot;controller&quot;);
// ... other keys
&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;h4&gt;&lt;strong&gt;What is a Controller?&lt;/strong&gt;&lt;/h4&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In the world of web frameworks, a Controller is a class responsible for handling incoming HTTP requests and sending responses.
Our &lt;code&gt;function Controller(){:typescript}&lt;/code&gt; decorator is a way to mark a class as one such handler. Here&apos;s how it works:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export function Controller(prefix: string): ClassDecorator {
  return (target) =&amp;gt; {
    Reflect.defineMetadata(CONTROLLER_KEY, prefix, target);
  };
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;When you add &lt;code&gt;@Controller(&quot;/api&quot;){:typescript}&lt;/code&gt; above a class, this decorator tells our framework that this class is responsible for routes that start with &lt;code&gt;&quot;/api&quot;{:typescript}&lt;/code&gt;.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;h4&gt;&lt;strong&gt;Grouping with Modules&lt;/strong&gt;&lt;/h4&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In larger applications, it can be useful to group related controllers and use-cases together. That&apos;s where our &lt;code&gt;function Module(){:typescript}&lt;/code&gt; decorator comes in:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export function Module(options: {
  usecases: any[];
  controllers: any[];
}): ClassDecorator {
  return (target) =&amp;gt; {
    Reflect.defineMetadata(MODULE_KEY, options, target);
  };
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;function Module(){:typescript}&lt;/code&gt; decorator expects an &lt;code&gt;(options: { ... }){:typescript}&lt;/code&gt; object that can include arrays of &lt;code&gt;usecases: any[]{:typescript}&lt;/code&gt; and &lt;code&gt;controllers: any[]{:typescript}&lt;/code&gt;.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;h4&gt;&lt;strong&gt;What is Dependency Injection?&lt;/strong&gt;&lt;/h4&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Dependency Injection is a design pattern used to increase code modularity and ease testing. Our &lt;code&gt;function Injectable(){:typescript}&lt;/code&gt; decorator indicates that a class can have dependencies automatically provided, rather than having to create them internally.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export function Injectable(): ClassDecorator {
  return (target) =&amp;gt; {
    Reflect.defineMetadata(INJECTABLE_KEY, true, target);
  };
}
&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;h4&gt;&lt;strong&gt;Making Routes&lt;/strong&gt;&lt;/h4&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Now, how do we specify which function should run for a specific HTTP request like &lt;strong&gt;GET&lt;/strong&gt; or &lt;strong&gt;POST&lt;/strong&gt;? For this, we have specific decorators:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function Route(method: string, route: string): MethodDecorator {
  return (target, propertyKey) =&amp;gt; {
    Reflect.defineMetadata(METHOD_KEY, method, target, propertyKey as string);
    Reflect.defineMetadata(ROUTE_KEY, route, target, propertyKey as string);
  };
}

export function Get(route: string = &quot;/&quot;): MethodDecorator {
  return Route(&quot;get&quot;, route);
}

export function Post(route: string = &quot;/&quot;): MethodDecorator {
  return Route(&quot;post&quot;, route);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;These decorators specify which HTTP method (GET, POST, etc.) a method in our controller class should respond to.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;h4&gt;&lt;strong&gt;The Full Picture&lt;/strong&gt;&lt;/h4&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Here&apos;s the full code combining all these concepts:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import &quot;reflect-metadata&quot;;

export const CONTROLLER_KEY = Symbol(&quot;controller&quot;);
export const METHOD_KEY = Symbol(&quot;method&quot;);
export const ROUTE_KEY = Symbol(&quot;route&quot;);
export const MODULE_KEY = Symbol(&quot;module&quot;);
export const INJECTABLE_KEY = Symbol(&quot;injectable&quot;);

export function Controller(prefix: string): ClassDecorator {
  return (target) =&amp;gt; {
    Reflect.defineMetadata(CONTROLLER_KEY, prefix, target);
  };
}

export function Module(options: {
  usecases: any[];
  controllers: any[];
}): ClassDecorator {
  return (target) =&amp;gt; {
    Reflect.defineMetadata(MODULE_KEY, options, target);
  };
}

export function Injectable(): ClassDecorator {
  return (target) =&amp;gt; {
    Reflect.defineMetadata(INJECTABLE_KEY, true, target);
  };
}

function Route(method: string, route: string): MethodDecorator {
  return (target, propertyKey) =&amp;gt; {
    Reflect.defineMetadata(METHOD_KEY, method, target, propertyKey as string);
    Reflect.defineMetadata(ROUTE_KEY, route, target, propertyKey as string);
  };
}

export function Get(route: string = &quot;/&quot;): MethodDecorator {
  return Route(&quot;get&quot;, route);
}

export function Post(route: string = &quot;/&quot;): MethodDecorator {
  return Route(&quot;post&quot;, route);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;With these decorators, we have versatile tools to structure our application, making it both maintainable and scalable. And just like that, you&apos;ve brewed the perfect cup of ExpressoTS to kickstart your day!&lt;/p&gt;
&lt;h3&gt;A Closer Look at the BreakfastFactory: Cooking Up Your Routes&lt;/h3&gt;
&lt;p&gt;Let&apos;s dig into another important part of our Breakfast-TS framework, the &lt;code&gt;class BreakfastFactory{:typescript}&lt;/code&gt;.
This class plays the role of a master chef, bringing all the ingredients together to serve a tasty API.
Create this file at &lt;code&gt;src/breakfast-ts/index.ts{:bash}&lt;/code&gt;.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;h4&gt;&lt;strong&gt;Initialization and Setting Up Elysia&lt;/strong&gt;&lt;/h4&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;We start by importing the necessary modules and metadata keys. Then, the &lt;code&gt;class BreakfastFactory{:typescript}&lt;/code&gt; is defined.
It has a property &lt;code&gt;private app: Elysia;{:typescript}&lt;/code&gt;, which is an instance of Elysia:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export class BreakfastFactory {
  private app: Elysia;

  constructor() {
    this.app = new Elysia();
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;h4&gt;&lt;strong&gt;The &lt;code&gt;static create() {}{:typescript}&lt;/code&gt; method&lt;/strong&gt;&lt;/h4&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The &lt;code&gt;static create(module: any) {}{:typescript}&lt;/code&gt; method is the centerpiece. It takes a module as an argument and proceeds to configure routes and controllers.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export class BreakfastFactory {
  private app: Elysia;

  constructor() {
    this.app = new Elysia();
  }

  static create(module: any) {
    const factory = new BreakfastFactory();
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;h4&gt;&lt;strong&gt;Fetching Metadata and Initializing Providers&lt;/strong&gt;&lt;/h4&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;First, we extract metadata from the AppModule using &lt;code&gt;Reflect.getMetadata{:typescript}&lt;/code&gt;.
Then, we instantiate all the providers mentioned in the &lt;code&gt;usecases{:typescript}&lt;/code&gt; field of the module metadata:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export class BreakfastFactory {
  private app: Elysia;

  constructor() {
    this.app = new Elysia();
  }

  static create(module: any) {
    const factory = new BreakfastFactory();

    const moduleMetadata = Reflect.getMetadata(MODULE_KEY, module);

    const instances = moduleMetadata.usecases.map(
      (provider: any) =&amp;gt; new provider()
    );
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;h4&gt;&lt;strong&gt;Adding Routes to Elysia&lt;/strong&gt;&lt;/h4&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Next, the method iterates over each controller, again using metadata to fetch the necessary information:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export class BreakfastFactory {
  // ...
  static create(module: any) {
    // ...

    moduleMetadata.controllers.forEach((Controller: any) =&amp;gt; {
      const prefix = Reflect.getMetadata(CONTROLLER_KEY, Controller);
      const controller = new Controller(...instances);
      // ... (More code)
    });
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;For each controller, we initiate it with the instances of &lt;code&gt;usecases{:typescript}&lt;/code&gt; as arguments.
Then, we scan through its methods to fetch their metadata and subsequently attach them as routes to our Elysia instance.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export class BreakfastFactory {
  // ...
  static create(module: any) {
    // ...

    moduleMetadata.controllers.forEach((Controller: any) =&amp;gt; {
      const prefix = Reflect.getMetadata(CONTROLLER_KEY, Controller);
      const controller = new Controller(...instances);

      Object.getOwnPropertyNames(Object.getPrototypeOf(controller)).forEach(
        (property) =&amp;gt; {
          // ... (Metadata fetching and route setup)
        }
      );
    });
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This specific piece of code, nested within the &lt;code&gt;.forEach(){:typescript}&lt;/code&gt; loop for each controller, is the powerhouse of our framework.
It brings in cool possibilities like dependency injection in Elysia&apos;s state, among others.&lt;/p&gt;
&lt;p&gt;First, we check if the property is not the &lt;code&gt;&quot;constructor&quot;{:typescript}&lt;/code&gt;. This is essential because the constructor is not a route,
but merely a setup function for the object:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export class BreakfastFactory {
  // ...
  static create(module: any) {
    // ...
    moduleMetadata.controllers.forEach((Controller: any) =&amp;gt; {
      const prefix = Reflect.getMetadata(CONTROLLER_KEY, Controller);
      const controller = new Controller(...instances);

      Object.getOwnPropertyNames(Object.getPrototypeOf(controller)).forEach(
        (property) =&amp;gt; {
          if (property !== &quot;constructor&quot;) {
            // ... (More code)
          }
        }
      );
    });
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Next, we use the Reflect API to fetch metadata associated with the method and the route.
We&apos;re using the &lt;code&gt;METHOD_KEY{:typescript}&lt;/code&gt; and &lt;code&gt;ROUTE_KEY{:typescript}&lt;/code&gt; to do this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;if (property !== &quot;constructor&quot;) {
  const method = Reflect.getMetadata(METHOD_KEY, controller, property);
  const route = Reflect.getMetadata(ROUTE_KEY, controller, property);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Before attaching the route to our Elysia app, we perform a quick sanity check to make sure both variables exist:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;if (property !== &quot;constructor&quot;) {
  const method = Reflect.getMetadata(METHOD_KEY, controller, property);
  const route = Reflect.getMetadata(ROUTE_KEY, controller, property);

  if (route &amp;amp;&amp;amp; method !== null) {
    // ... (More code follows)
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Once the sanity check passes, we log the route being added for better visibility:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;console.log(`🍳🥓☕ Adding route ${method.toUpperCase()} ${prefix}${route}`);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The real magic happens in the following line, where we dynamically call Elysia&apos;s routing method:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// @ts-ignore
factory.app[method](
  prefix + route,
  (req: any, res: any) =&amp;gt; controller[property](req, res),
  {
    type: &quot;json&quot;,
  }
);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here, &lt;code&gt;factory.app[method]{:typescript}&lt;/code&gt; dynamically chooses the HTTP method (GET, POST, etc.) to which we attach the route.
The route itself is a combination of the controller prefix and the specific method route.&lt;/p&gt;
&lt;p&gt;The function &lt;code&gt;(req: any, res: any) =&amp;gt; controller[property](req, res){:typescript}&lt;/code&gt; is what gets executed when this route is hit.
Essentially, it forwards the request and response objects to the corresponding method in the controller.&lt;/p&gt;
&lt;p&gt;The &lt;code&gt;{type: &quot;json&quot;}{:typescript}&lt;/code&gt; part tells Elysia to treat the response as JSON.
This is particularly useful as it sets the stage for future features like automatic response serialization, dependency injection in states, and much more.&lt;/p&gt;
&lt;p&gt;Understanding this section equips you with the skills to extend Elysia and tap into its full power.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;h4&gt;&lt;strong&gt;Making It Listen&lt;/strong&gt;&lt;/h4&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Finally, the &lt;code&gt;async function listen(port: number){:typescript}&lt;/code&gt; is quite straightforward. It makes the Elysia server listen on a specific port:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export class BreakfastFactory {
  // ...

  public async listen(port: number) {
    this.app.listen(port);
    console.log(`🦊 Elysia is running on port ${this.app.server?.port}...`);
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;h4&gt;&lt;strong&gt;The Complete Code&lt;/strong&gt;&lt;/h4&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Here&apos;s the full &lt;code&gt;class BreakfastFactory{:typescript}&lt;/code&gt; code for reference:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import &quot;reflect-metadata&quot;;

import Elysia from &quot;elysia&quot;;
import {
  CONTROLLER_KEY,
  METHOD_KEY,
  MODULE_KEY,
  ROUTE_KEY,
} from &quot;./decorators&quot;;

export class BreakfastFactory {
  private app: Elysia;

  static create(module: any) {
    const factory = new BreakfastFactory();

    // Fetch metadata from the AppModule
    const moduleMetadata = Reflect.getMetadata(MODULE_KEY, module);

    // Create an instance of the providers
    const instances = moduleMetadata.usecases.map(
      (provider: any) =&amp;gt; new provider()
    );

    // Get controllers and add routes to Elysia
    moduleMetadata.controllers.forEach((Controller: any) =&amp;gt; {
      const prefix = Reflect.getMetadata(CONTROLLER_KEY, Controller);
      const controller = new Controller(...instances);

      Object.getOwnPropertyNames(Object.getPrototypeOf(controller)).forEach(
        (property) =&amp;gt; {
          if (property !== &quot;constructor&quot;) {
            const method = Reflect.getMetadata(
              METHOD_KEY,
              controller,
              property
            );
            const route = Reflect.getMetadata(ROUTE_KEY, controller, property);

            if (route &amp;amp;&amp;amp; method !== null) {
              console.log(
                `🍳🥓☕ Adding route ${method.toUpperCase()} ${prefix}${route}`
              );
              // @ts-ignore
              factory.app[method](
                prefix + route,
                (req: any, res: any) =&amp;gt; controller[property](req, res),
                {
                  type: &quot;json&quot;,
                }
              );
            }
          }
        }
      );
    });

    return factory;
  }

  constructor() {
    this.app = new Elysia();
  }

  public async listen(port: number) {
    this.app.listen(port);
    console.log(`🦊 Elysia is running on port ${this.app.server?.port}...`);
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;With &lt;code&gt;class BreakfastFactory{:typescript}&lt;/code&gt;, you&apos;ve just set up a powerful, flexible base for your APIs.&lt;/p&gt;
&lt;h2&gt;Integrating It All Together&lt;/h2&gt;
&lt;p&gt;We&apos;ll now go through how to integrate all the components we&apos;ve discussed so far into a single, functional application.&lt;/p&gt;
&lt;h3&gt;The Entry Point: &lt;code&gt;src/main.ts&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;We rename &lt;code&gt;src/index.ts&lt;/code&gt; to &lt;code&gt;src/main.ts&lt;/code&gt; to signify that it&apos;s the entry point to our application.
This is where we use the &lt;code&gt;class BreakfastFactory{:typescript}&lt;/code&gt; to bootstrap our entire application.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { BreakfastFactory } from &quot;./breakfast-ts&quot;;

async function bootstrap() {
  const app = BreakfastFactory.create(/* A module */);
  await app.listen(3000);
}

bootstrap();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here, &lt;code&gt;BreakfastFactory.create(AppModule){:typescript}&lt;/code&gt; bootstraps our application by initiating all controllers, routes, and use-cases
as to be defined in a module.&lt;/p&gt;
&lt;h3&gt;The Use-Case: &lt;code&gt;src/app/app.use-case.ts&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;The use-case is responsible for handling the actual business logic.
It&apos;s marked as &lt;code&gt;@Injectable{:typescript}&lt;/code&gt;, which means it can be easily provided to other classes, like our controller.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { Injectable } from &quot;../breakfast-ts/decorators&quot;;

@Injectable()
export class AppUseCase {
  public execute(): string {
    return &quot;Hello from the app use case!&quot;;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;The Controller: &lt;code&gt;src/app/app.controller.ts&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;The controller orchestrates between the route handling and the use-case execution.
The controller defines methods that handle HTTP requests, and it leverages the AppUseCase to execute specific business logic.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { Controller, Get, Post } from &quot;../breakfast-ts/decorators&quot;;
import { AppUseCase } from &quot;./app.use-case&quot;;

@Controller(&quot;/api&quot;)
export class AppController {
  constructor(private appUseCase: AppUseCase) {}

  @Get()
  handleRequest(_req: any, _res: any) {
    return this.appUseCase.execute();
  }

  @Post(&quot;/data&quot;)
  handlePostRequest(req: any) {
    console.log(req.body);
    return &quot;Okay&quot;;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;The Module: &lt;code&gt;src/app/app.module.ts&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;The module serves as a container that ties together different parts of our application — controllers and use-cases in this case.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { Module } from &quot;../breakfast-ts/decorators&quot;;
import { AppController } from &quot;./app.controller&quot;;
import { AppUseCase } from &quot;./app.use-case&quot;;

@Module({
  usecases: [AppUseCase],
  controllers: [AppController],
})
export class AppModule {}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This modular design ensures scalability and maintainability. Any time you need to add new functionality, it becomes as simple as
defining new use-cases and controllers and registering them in the module.&lt;/p&gt;
&lt;h3&gt;Completing the Main Function&lt;/h3&gt;
&lt;p&gt;Finally, we update the &lt;code&gt;main.ts&lt;/code&gt; file to use our &lt;code&gt;class AppModule{:typescript}&lt;/code&gt;,
which has the definitions for our use-case and controller. This will bring our whole app to life.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { BreakfastFactory } from &quot;./breakfast-ts&quot;;
import { AppModule } from &quot;./app/app.module&quot;;

async function bootstrap() {
  const app = BreakfastFactory.create(AppModule);
  await app.listen(3000);
}

bootstrap();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is the glue that brings everything together. When you run this &lt;code&gt;bootstrap(){:typescript}&lt;/code&gt; function, your application starts,
listens on port &lt;code&gt;3000{:typescript}&lt;/code&gt;, and is ready to handle incoming requests through the routes defined in your &lt;code&gt;class AppController{:typescript}&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;And there we have it — a fully functional, custom-designed TypeScript web application that utilizes advanced features like decorators
and metadata reflection for a clean, efficient, and organized codebase.&lt;/p&gt;
&lt;h3&gt;Let&apos;s Test It Out&lt;/h3&gt;
&lt;p&gt;Running with &lt;code&gt;bun run --watch src/main.ts{:bash}&lt;/code&gt; will start the application, and we already see the logs of our routes being added:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;🍳🥓☕ Adding route GET /api/
🍳🥓☕ Adding route POST /api/data
🦊 Elysia is running on port 3001...
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To test your newly created endpoints, we use &lt;code&gt;httpie{:bash}&lt;/code&gt; again.&lt;/p&gt;
&lt;p&gt;First, let&apos;s test the GET route &lt;code&gt;&quot;/api&quot;{:typescript}&lt;/code&gt;. Open a terminal and execute the following command:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;http :3000/api
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You should expect a response that resembles the following:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;HTTP/1.1 200 OK
Content-Length: 26
Date: Sun, 10 Sep 2023 20:47:46 GMT
content-type: text/plain;charset=utf-8

Hello from the app use case!
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This confirms that the GET request is working as expected, returning a message from our use case.&lt;/p&gt;
&lt;p&gt;Next, let&apos;s move on to the POST route &lt;code&gt;&quot;/api/data&quot;{:typescript}&lt;/code&gt;. In the terminal, run:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;http POST :3000/api/data expresso-plus-bun=success
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The server should return a simple &lt;code&gt;&quot;Okay&quot;{:typescript}&lt;/code&gt; message, like so:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;HTTP/1.1 200 OK
Content-Length: 5
Date: Sun, 10 Sep 2023 20:48:10 GMT
content-type: text/plain;charset=utf-8

Okay
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In addition, you should see a console log on your server indicating the POST data, &lt;code&gt;{ &quot;expresso-plus-bun&quot;: &quot;success&quot; }{:json}&lt;/code&gt;,
was successfully received and processed.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;❮ bun run --watch src/main.ts
🍳🥓☕ Adding route GET /api/
🍳🥓☕ Adding route POST /api/data
🦊 Elysia is running on port 3001...
{
  &quot;expresso-plus-bun&quot;: &quot;success&quot;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;These tests verify that your server is properly set up to handle both GET and POST requests. Talk about a brew-tiful success!&lt;/p&gt;
&lt;hr /&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;In this walkthrough, we embarked on a coding journey that took us through building a TypeScript backend application
with a new flavor — using Elysia as the foundational framework and enriching it with our custom decorators and modules.
Our adventure covered various modern concepts such as decorators, reflection, and dependency injection, illustrating how they can be seamlessly integrated to produce a clean, maintainable, and scalable codebase.&lt;/p&gt;
&lt;p&gt;We first set up a basic Elysia app with a simple endpoint. From there, we delved into extending Elysia by adding
CRUD operations for a hypothetical user model. This was just the appetizer. The main course involved creating
a custom framework, &lt;code&gt;&quot;Breakfast-TS&quot;{:ts}&lt;/code&gt;, that leveraged TypeScript&apos;s advanced features.
We crafted decorators to annotate our classes, methods, and properties and used metadata reflection to dynamically bind them to Elysia&apos;s core.&lt;/p&gt;
&lt;p&gt;This not only simplified our application logic but also opened the doors for more advanced features,
like dependency injection in Elysia states.
All of these were stitched together in the final chapter, where we integrated everything we had built into a fully
functioning backend application. Finally, we tested our server routes to ensure that our application was not just theoretical but a working model.&lt;/p&gt;
&lt;p&gt;This guide was intended as a starter pack for those looking to leverage modern TypeScript features in backend development.
While our example was fairly basic, the principles and patterns we&apos;ve discussed here are scalable and can be adapted for more complex projects.
The breakfast analogy wasn&apos;t just for fun — it&apos;s a reminder that building good software, like a good breakfast,
requires a mix of the right ingredients.&lt;/p&gt;
&lt;p&gt;So what&apos;s next? The possibilities are endless.
You can extend this framework with more complex use cases, implement a database, or even integrate it with front-end technologies.
The world — or in this case, the kitchen — is your oyster.&lt;/p&gt;
&lt;p&gt;So go ahead, &lt;a href=&quot;https://github.com/daniel-boll/breakfast-ts&quot;&gt;fork this code&lt;/a&gt;, and let&apos;s cook up some more amazing projects together.
Hungry for more? Check out the Call to Action at the end of this post and join us at ExpressoTS.
A balanced coding breakfast is the best way to start your day, wouldn&apos;t you agree? 🍳🥓☕&lt;/p&gt;
&lt;h2&gt;Call to Action&lt;/h2&gt;
&lt;p&gt;If you found this guide insightful and you&apos;re buzzing with ideas on how to extend it, we&apos;d love for you to get involved! We&apos;ve only scratched the surface of what&apos;s possible, and there&apos;s a multitude of exciting features and optimizations that could make this experiment even more powerful.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Extend The Framework&lt;/strong&gt;: Feel free to clone the repository, add features, or fix bugs. Your contributions are not just welcomed; they&apos;re eagerly anticipated.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Bun Integration&lt;/strong&gt;: If you&apos;re interested in the bun integration, we would be thrilled to see you contribute to &lt;a href=&quot;https://github.com/expresso-ts/expresso-ts&quot;&gt;ExpressoTS core&lt;/a&gt;. File an issue, make a pull request, or engage in the discussions. Your insights could be the missing puzzle piece in making this integration smooth and powerful.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Join The Community&lt;/strong&gt;: Last but not least, if you want to be part of a community of like-minded developers, we have a space for you. Jump into our &lt;a href=&quot;https://discord.com/invite/PyPJfGK&quot;&gt;Discord server&lt;/a&gt; to discuss ideas, ask questions, or just chat about TypeScript, Elysia, and all things coding.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;By contributing, you&apos;re not just enhancing a project; you&apos;re joining a community of developers who are passionate about pushing TypeScript&apos;s capabilities to the limit. Let&apos;s build, learn, and grow together.&lt;/p&gt;
&lt;p&gt;So, what are you waiting for? Let&apos;s turn this experiment into an evolution. See you on GitHub and Discord! 🚀👨‍💻👩‍💻&lt;/p&gt;
</content:encoded></item><item><title>How to structure C++ projects with xmake</title><link>https://daniel-boll.me/posts/how-to-structure-cpp-projects-with-xmake/</link><guid isPermaLink="true">https://daniel-boll.me/posts/how-to-structure-cpp-projects-with-xmake/</guid><description>Using a simple lua configured builder and package manager.</description><pubDate>Fri, 20 Jan 2023 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;I have always felt that work in C++ projects was too cumbersome. I wanted to have a simple way to create a project, and I wanted to have a simple way to build and test it.&lt;/p&gt;
&lt;p&gt;C/C++ third-party libraries are a pain to build, historically. You have to download the source, configure, build, and install it. This is a pain, especially if you are not using a package manager.&lt;/p&gt;
&lt;hr /&gt;
&lt;h2&gt;&lt;a href=&quot;https://xmake.io/#/&quot;&gt;xmake&lt;/a&gt; for the rescue&lt;/h2&gt;
&lt;blockquote&gt;
&lt;p&gt;xmake is a lightweight cross-platform build utility based on Lua. It uses xmake.lua to maintain project builds. Compared with makefile/CMakeLists.txt, the configuration syntax is more concise and intuitive. It is very friendly to novices and can quickly get started in a short time. Let users focus more on actual project development.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;xmake is awesome and extremely easy for simple and even more complex and robust projects, it works as a package manager (which was the selling point for me) and as a project generator + build backend.&lt;/p&gt;
&lt;p&gt;The &lt;strong&gt;installation&lt;/strong&gt; can be done through &lt;code&gt;curl&lt;/code&gt;, but there are other methods in their docs.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;bash &amp;lt;(curl -fsSL https://xmake.io/shget.text)
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Sample project&lt;/h2&gt;
&lt;p&gt;To create a project we run:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;xmake create sample-project # Notice that sample-project is the name, you can choose any other
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The xmake.lua file should look like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;add_rules(&quot;mode.debug&quot;, &quot;mode.release&quot;)

target(&quot;sample-project&quot;)
    set_kind(&quot;binary&quot;)
    add_files(&quot;src/*.cpp&quot;)

-- A bunch of comments
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;First, I usually set the language to use the standard c++20 with &lt;code&gt;set_languages(&quot;c++20&quot;){:lua}&lt;/code&gt;, then I add a list of libs that this project will have, for now, I will only include the &lt;strong&gt;&lt;a href=&quot;https://fmt.dev/latest/index.html&quot;&gt;{fmt}&lt;/a&gt;&lt;/strong&gt; lib with local &lt;code&gt;libs = { &quot;fmt&quot; }{:lua}&lt;/code&gt;, removing the comments it should look like this now:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;set_languages(&quot;c++20&quot;)
add_rules(&quot;mode.debug&quot;, &quot;mode.release&quot;)

local libs = { &quot;fmt&quot; }

target(&quot;sample-project&quot;)
    set_kind(&quot;binary&quot;)
    add_files(&quot;src/*.cpp&quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The folder structure that I adopted is having the includes and source folder for the application-specific scope like a library implementation and the standalone folder as the binary API entry point for the library.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;.
├── benchmark         (optional in case we need benchmark)
├── include
├── source
├── standalone
│   └── main.cpp
├── test              (optional in case we need tests)
└── xmake.lua
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As we added the include and source folder for the library we need to adapt xmake.lua&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;set_languages(&quot;c++20&quot;)
add_rules(&quot;mode.debug&quot;, &quot;mode.release&quot;)

local libs = { &quot;fmt&quot; }

add_includedirs(&quot;include&quot;)
add_requires(table.unpack(libs))

target(&quot;sample-project-lib&quot;)
  set_kind(&quot;static&quot;)
  add_files(&quot;source/**/*.cpp&quot;)
  add_packages(table.unpack(libs))

target(&quot;sample-project&quot;)
  set_kind(&quot;binary&quot;)
  add_files(&quot;standalone/main.cpp&quot;)
  add_packages(table.unpack(libs))
  add_deps(&quot;sample-project-lib&quot;)

-- NOTE: Requires a test library to be installed
-- target(&quot;test&quot;)
--   set_kind(&quot;binary&quot;)
--   add_files(&quot;test/*.cpp&quot;)
--   add_packages(table.unpack(libs))
--   add_deps(&quot;sample-project-lib&quot;)

-- NOTE: Requires a benchmark library to be installed
-- target(&quot;benchmark&quot;)
--   set_kind(&quot;binary&quot;)
--   add_files(&quot;benchmark/*.cpp&quot;)
--   add_packages(table.unpack(libs))
--   add_deps(&quot;sample-project-lib&quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now that we added the packages to the binary standalone when we run xmake to compile it the next time it&apos;ll be prompting us to download &lt;strong&gt;&lt;a href=&quot;https://fmt.dev/latest/index.html&quot;&gt;{fmt}&lt;/a&gt;&lt;/strong&gt; through xrepo, the first time we download a version of a library it&apos;ll keep it at &lt;code&gt;~/.xmake/packages&lt;/code&gt; for future projects.&lt;/p&gt;
&lt;p&gt;Now, with &amp;lt;strong&amp;gt;standalone/main.cpp&amp;lt;/strong&amp;gt; like&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#include &amp;lt;fmt/core.h&amp;gt;

auto main() -&amp;gt; int {
  fmt::print(&quot;Hello, {}!\n&quot;, &quot;world&quot;);
  return 0;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We can run &lt;code&gt;xmake &amp;amp;&amp;amp; xmake run{:sh}&lt;/code&gt; to build and run the default target, if we want to specify another target we can run &lt;code&gt;xmake run target_name{:sh}&lt;/code&gt; would produce the same effect as &lt;code&gt;xmake run sample-project{:sh}&lt;/code&gt;.&lt;/p&gt;
&lt;h2&gt;Boilerplate Repo&lt;/h2&gt;
&lt;p&gt;If you are looking for a easy to begin with boilerplate I&apos;ve created one at my GitHub.&lt;/p&gt;
&lt;p&gt;::github{repo=&quot;daniel-boll/xmake-boilerplate&quot;}&lt;/p&gt;
</content:encoded></item><item><title>Foliage Classification</title><link>https://daniel-boll.me/posts/foliage-classification/</link><guid isPermaLink="true">https://daniel-boll.me/posts/foliage-classification/</guid><description>Foliage Classification Machine Learning with manual feature extraction</description><pubDate>Thu, 19 Jan 2023 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import Trivia from &quot;@components/mdx/Trivia.astro&quot;;
import Caption from &quot;@components/mdx/Caption.astro&quot;;&lt;/p&gt;
&lt;p&gt;import theDatasetImage from &quot;./the_dataset.jpg&quot;;
import prePrunedImages from &quot;./pre-pruned.png&quot;;
import prunedImages from &quot;./pruned.png&quot;;
import labeledImages from &quot;./labeled.png&quot;;
import finalImage from &quot;./final.png&quot;;&lt;/p&gt;
&lt;p&gt;import { Image } from &quot;astro:assets&quot;;&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;In my Digital Image Processing course, we were tasked with a challenging project. The goal was to create a system capable of analyzing images of six different plant species. The system had to be trained using a dataset of 36 images, and once trained, it should be able to analyze all images in a specified folder. The final output of the system was to generate a comprehensive report containing information about each analyzed image, including the name of the image file. In the following sections, I will detail how I approached and solved this problem.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;Getting to Know Our Leafy Subjects: An Introduction to the Dataset&lt;/h2&gt;
&lt;p&gt;The first thing we needed to do in this project was getting to grips with the dataset. We had 36 images, each packed with different plant species – six in total. However, there was a hitch. None of the images were labeled. So, all we had were a bunch of leaf images from various plants, without any indications of which leaf belonged to which plant.&lt;/p&gt;
&lt;p&gt;&amp;lt;Image
src={theDatasetImage}
alt=&quot;A image from the dataset&quot;
class=&quot;self-center mb-0 md:h-1/2 md:w-1/2&quot;
/&amp;gt;&lt;/p&gt;
&lt;p&gt;&amp;lt;figcaption class=&quot;text-center text-xs italic&quot;&amp;gt;
&amp;lt;strong&amp;gt;Figure 1:&amp;lt;/strong&amp;gt; A image from the dataset
&amp;lt;/figcaption&amp;gt;&lt;/p&gt;
&lt;p&gt;Here&apos;s an example image from the dataset. As you can see, it&apos;s not immediately clear which leaf belongs to which plant species. We were truly in uncharted territory.&lt;/p&gt;
&lt;h2&gt;The Problem: Tackling an Unlabeled Dataset and Close Neighbors&lt;/h2&gt;
&lt;p&gt;Working with an unlabeled dataset was our first hurdle. Most of my prior machine learning experience had been with supervised learning, where you have clear labels for training data. But in this case, we had to get our hands dirty and dive into the deep end of unsupervised machine learning.&lt;/p&gt;
&lt;p&gt;Our task was to label the data manually, which meant separating each leaf from the images and then assigning them a label. And if that wasn&apos;t enough, some leaves were too close together, which made them hard to separate. Picture two pieces of paper glued together, and you get the idea.&lt;/p&gt;
&lt;h2&gt;Creating the Environment: Welcome to the Python World&lt;/h2&gt;
&lt;p&gt;The next step in our journey was to set up our working environment. We decided to use Python, a favorite in the machine learning realm, for its simplicity and robustness. Plus, it&apos;s got a treasure trove of useful libraries and tools, making it an excellent choice for this project.&lt;/p&gt;
&lt;p&gt;To create a consistent and portable development environment, we used Docker. This allowed us to package up the application with all of the parts it needed and run it anywhere Docker is installed. Below is the Dockerfile we used:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# Use an official Tensorflow runtime as a parent image
FROM tensorflow/tensorflow:latest-gpu-jupyter

# Set the working directory to /app
WORKDIR /app

# Add local directory&apos;s content to the docker image under /app
ADD . /app

# Allow statements and log messages to immediately appear in the Knative logs
ENV PYTHONUNBUFFERED True

RUN apt-get update &amp;amp;&amp;amp; apt-get install -y \
    wget \
    libcairo2-dev \
    libgl1-mesa-glx \
    python3-tk

# Install any needed packages specified in the requirements file
COPY requirements.txt /app
RUN pip install --no-cache-dir -r requirements.txt
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We used the official Tensorflow image as our base and installed some additional packages that we needed. We also copied our local directory content into the docker image and installed the necessary Python packages from our requirements.txt file.&lt;/p&gt;
&lt;p&gt;&amp;lt;Trivia emoji=&quot;🤠&quot;&amp;gt;
At the start, our project was without a &lt;em&gt;requirements.txt&lt;/em&gt;, the lifeline of
Python dependencies. An attempt to create one with pip freeze fell flat
&lt;em&gt;(image analysis can be picky!)&lt;/em&gt;. So, we found ourselves manually jotting down
dependencies as we progressed. Ah, the joy of unexpected surprises in coding!
Should have used &lt;strong&gt;Poetry&lt;/strong&gt;.
&amp;lt;/Trivia&amp;gt;&lt;/p&gt;
&lt;p&gt;To manage our Docker environment more easily, we used Docker Compose. Here&apos;s the docker-compose.yml file we used:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;version: &quot;3&quot;

services:
  tensorflow:
    build: .
    volumes:
      - .:/app
    ports:
      - &quot;5000:5000&quot;
    command: /bin/bash
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;With this setup, we were able to persist our data across Docker sessions, as Docker Compose takes care of the volumes for us.&lt;/p&gt;
&lt;p&gt;Finally, we created a Makefile to automate our common tasks, such as building the Docker image, running the Docker container, and running our main Python script:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;.PHONY: build run sudo_run help

help: ## Show this help
 @echo &quot;Available targets:&quot;
 @echo
 @awk &apos;BEGIN {FS = &quot;:.*?## &quot;} /^[a-zA-Z_-]+:.*?## / {printf &quot;\033[36m%-15s\033[0m %s\n&quot;, $$1, $$2}&apos; $(MAKEFILE_LIST)

build: ## Build the Docker image
 docker-compose build

run: ## Run the Docker container
 docker-compose run -u $(shell id -u):$(shell id -g) tensorflow bash

sudo_run: ## Run the Docker container as sudo
 docker-compose run tensorflow bash

drun: clean ## Run the code within the docker
 python src/main.py
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&amp;lt;Trivia emoji=&quot;🤤&quot;&amp;gt;
Sweet &lt;strong&gt;AWK&lt;/strong&gt; juice to make a automatic &lt;code&gt;help&lt;/code&gt; message in Make.
&amp;lt;/Trivia&amp;gt;&lt;/p&gt;
&lt;h2&gt;Pruning the Dataset: Separating the Leaves&lt;/h2&gt;
&lt;p&gt;After setting up our environment and sorting out our dependencies, it was time to roll up our sleeves and start the real work. The first major task? Implementing the leaf extraction.&lt;/p&gt;
&lt;p&gt;The goal here was to segment the leaves in the images, isolate them from each other, and then save them separately for further analysis. This process is crucial, as it ensures our machine learning model can focus on individual leaves, rather than being confused by a bunch of overlapping leaves.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import os
import cv2
import numpy as np

def extract_leaves(image_path, output_folder):
    os.makedirs(output_folder, exist_ok=True)
    min_area_threshold = 100
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Our function &lt;code&gt;extract_leaves{:python}&lt;/code&gt; takes two arguments: the path to the image file and the output folder to save extracted leaves. The &lt;code&gt;os.makedirs(output_folder, exist_ok=True){:python}&lt;/code&gt; line ensures the output folder is created if it doesn&apos;t exist. We also set a minimum area threshold to ignore any small areas that could be noise.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;def extract_leaves(image_path, output_folder):
    os.makedirs(output_folder, exist_ok=True)
    min_area_threshold = 100

    img = cv2.imread(image_path, cv2.IMREAD_UNCHANGED)
    channels = cv2.split(img)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We load the image using &lt;code&gt;cv2.imread{:python}&lt;/code&gt; with the flag &lt;code&gt;cv2.IMREAD_UNCHANGED{:python}&lt;/code&gt; to preserve transparency information. Then, we split the image into its channels (Red, Green, Blue, Alpha) using &lt;code&gt;cv2.split{:python}&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;def extract_leaves(image_path, output_folder):
    os.makedirs(output_folder, exist_ok=True)
    min_area_threshold = 100

    img = cv2.imread(image_path, cv2.IMREAD_UNCHANGED)
    channels = cv2.split(img)

    _, mask = cv2.threshold(channels[3], 1, 255, cv2.THRESH_BINARY)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We create a mask by thresholding the alpha channel (the 4th channel in our image). The cv2.threshold function sets all pixel values greater than 1 to 255 (white), creating a binary image where the leaves are white and the background is black.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;def extract_leaves(image_path, output_folder):
    os.makedirs(output_folder, exist_ok=True)
    min_area_threshold = 100

    img = cv2.imread(image_path, cv2.IMREAD_UNCHANGED)
    channels = cv2.split(img)

    _, mask = cv2.threshold(channels[3], 1, 255, cv2.THRESH_BINARY)

    contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Then, we find the contours (outlines) of all objects in the mask using the cv2.findContours function. This gives us a list of contours, each representing a leaf in the image.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;    img = cv2.imread(image_path, cv2.IMREAD_UNCHANGED)
    channels = cv2.split(img)

    _, mask = cv2.threshold(channels[3], 1, 255, cv2.THRESH_BINARY)

    contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    for i, contour in enumerate(contours):
        area = cv2.contourArea(contour)
        if area &amp;lt; min_area_threshold:
            continue
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We loop through each contour and calculate its area using cv2.contourArea. If the area is smaller than our set threshold, we skip the contour. This helps us ignore small noises or artifacts in the image.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;    for i, contour in enumerate(contours):
        area = cv2.contourArea(contour)
        if area &amp;lt; min_area_threshold:
            continue

        contour_mask = np.zeros_like(mask)
        cv2.drawContours(contour_mask, [contour], 0, 255, -1)
        object_img = cv2.bitwise_and(img, img, mask=contour_mask)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;For each valid contour, we create a blank mask and draw the contour on it using cv2.drawContours. This gives us a mask where only the current leaf is white. We then perform a bitwise-and operation on the original image and the mask, effectively isolating the leaf in the image.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;    for i, contour in enumerate(contours):
        area = cv2.contourArea(contour)
        if area &amp;lt; min_area_threshold:
            continue

        contour_mask = np.zeros_like(mask)
        cv2.drawContours(contour_mask, [contour], 0, 255, -1)
        object_img = cv2.bitwise_and(img, img, mask=contour_mask)

        image_file = os.path.basename(image_path)
        object_name = f&quot;{os.path.splitext(image_file)[0]}_{i}.png&quot;
        output_path = os.path.join(output_folder, object_name)
        cv2.imwrite(output_path, object_img)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Finally, we save each isolated leaf as a separate image in our output folder. We generate the output file name based on the original image&apos;s name and the index of the contour, ensuring each leaf gets a unique name.&lt;/p&gt;
&lt;p&gt;This function was key to preparing our dataset for further processing.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Pre-pruned images&lt;/th&gt;
&lt;th&gt;Pruned images&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&amp;lt;Image src={prePrunedImages} alt=&quot;Pre-pruned images&quot; class=&quot;md:w-1/2 md:h-1/2 self-center&quot; /&amp;gt;&lt;/td&gt;
&lt;td&gt;&amp;lt;Image src={prunedImages} alt=&quot;Pruned images&quot; class=&quot;md:w-1/2 md:h-1/2 self-center&quot; /&amp;gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&amp;lt;Caption index=&quot;2&quot; caption=&quot;Originally the images contained multiple leaves. We used the extract_leaves function to isolate each leaf into its own image.&quot; /&amp;gt;&lt;/td&gt;
&lt;td&gt;&amp;lt;Caption index=&quot;3&quot; caption=&quot;After pruning, each image contains only one leaf.&quot; /&amp;gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;h3&gt;Good Ol&apos; Manual Labeling: A Sip of Coffee and a LOT of Patience&lt;/h3&gt;
&lt;p&gt;Once we extracted the individual leaves from each image, we had another challenge to tackle - labeling. You&apos;d think we had some complex, fancy-pants algorithm do the job, right? Well, not really!&lt;/p&gt;
&lt;p&gt;We simply labeled each leaf by eye and hand, old-school style. Yep, that&apos;s right! It&apos;s like playing &apos;spot the differences&apos;, only with leaves and, trust me, they aren&apos;t as different as you&apos;d hope. Every leaf took a sip of coffee and a squinty-eyed look, backed up by some educated guesses (and prayers).&lt;/p&gt;
&lt;p&gt;A little bit of drudgery? Absolutely. But hey, nothing says &apos;hands-on data science&apos; quite like manually labelling hundreds of leaf images while nursing a caffeine overdose. So, a toast to the unsung hero of any machine learning project - the humble manual labeler! (The things we do for love... and accuracy).&lt;/p&gt;
&lt;p&gt;Remember folks, machine learning isn&apos;t all glamorous algorithms and fancy models. Sometimes, it&apos;s about slogging through leaf pictures while questioning your life choices.&lt;/p&gt;
&lt;p&gt;&amp;lt;Image
src={labeledImages}
alt=&quot;Labeling&quot;
class=&quot;self-center md:h-1/2 md:w-1/2&quot;
/&amp;gt;
&amp;lt;Caption
index=&quot;4&quot;
caption=&quot;The labeling process was a little tedious, but it was worth it in the end.&quot;
/&amp;gt;&lt;/p&gt;
&lt;h2&gt;Feature Extraction: The &apos;What&apos;s What&apos; of Leaves&lt;/h2&gt;
&lt;p&gt;With our leaves neatly isolated, we moved on to the critical step of feature extraction. Here&apos;s a look at the code that performed this task:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;def extract_feature(image_path, step=Step.TRAIN):
    features = {}

    # Get the original contours and extract features
    contours = image.get_contours(image_path)
    features[image_path] = extract_features_from_contours(
        contours, image_path, step)

    return features
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In our &lt;code&gt;extract_feature{:python}&lt;/code&gt; function, we find the leaf contours and then extract the features from these contours. The extracted features are stored in a dictionary using the image path as the key.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;def extract_features_from_contours(contours, image_path, step):
    contour_features = []

    freeman_features = freeman_chain_code.extract_features(contours)
    statistical_features = statistics.extract_features(contours)
    local_binary_pattern_features = local_binary_pattern.extract_features(
        contours, image_path)

    for freeman_feature, statistical_feature in zip(freeman_features,
                                                    statistical_features):
        feature = {
            &quot;chain_code&quot;: freeman_feature,
            &quot;lbp&quot;: local_binary_pattern_features,
            **statistical_feature,
        }

        if step == Step.TRAIN:
            name = image_path.split(&quot;/&quot;)[1]
            feature[&quot;class&quot;] = name

        contour_features.append(feature)

    return contour_features
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&amp;lt;Trivia emoji=&quot;🌿&quot;&amp;gt;
As we can see only when we are training the model we do know the classes.
&amp;lt;/Trivia&amp;gt;&lt;/p&gt;
&lt;h2&gt;Feature Serialization: Storing the Leafy Knowledge&lt;/h2&gt;
&lt;p&gt;Once we have successfully extracted the critical features from our leaf dataset, the next step is to serialize and store this data. Serializing our dataset converts it into a format that can be easily saved to disk and subsequently loaded back when needed. For this purpose, we use a powerful Python library known as &lt;code&gt;joblib&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Here&apos;s a simple piece of code demonstrating how we&apos;ve done this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;from joblib import dump, load

def save_features(features):
    dump(features, &quot;features.pkl&quot;)

def load_features():
    return load(&quot;features.pkl&quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And just like that, our feature extraction process is complete! We&apos;ve successfully isolated our leaves, extracted meaningful features from them, and stored these features for future use.&lt;/p&gt;
&lt;h2&gt;Model Training: Teaching our AI to Understand Leaves&lt;/h2&gt;
&lt;p&gt;So, you&apos;ve followed us through leaf isolation and feature extraction, and we&apos;ve managed to store all this data in a convenient format. But what next? Here comes the exciting part – training our model! In this section, we&apos;ll get our hands dirty with some real machine learning using a type of network known as a Multi-Layer Perceptron (MLP).&lt;/p&gt;
&lt;p&gt;Let&apos;s walk through the code that does the magic:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import numpy as np

from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
from sklearn.preprocessing import StandardScaler

def train(features):
    X = []
    y = []

    # Extract the features and their respective classes
    for _, v in features.items():
        for d in v:
            for i in range(len(d[&quot;extent&quot;])):
                feature = [
                    d[&quot;aspect_ratio&quot;][i],
                    d[&quot;eccentricity&quot;][i],
                    d[&quot;extent&quot;][i],
                    d[&quot;solidity&quot;][i],
                    *d[&quot;hu_moments&quot;][i],
                    *d[&quot;lbp&quot;][i],
                ]

                X.append(feature)
                y.append(d[&quot;class&quot;])

    # Convert the lists to numpy arrays
    X = np.array(X)
    y = np.array(y)

    # Scale your data
    scaler = StandardScaler()
    X = scaler.fit_transform(X)

    # Split into train and test sets
    X_train, X_test, y_train, y_test = train_test_split(
        X,
        y,
        test_size=0.3,
        random_state=42,
        stratify=y,
    )

    # Create the MLP classifier
    mlp = MLPClassifier(hidden_layer_sizes=(100, 100),
                        max_iter=200,
                        verbose=True)

    # Fit the model
    mlp.fit(X_train, y_train)

    # Save the model
    dump(mlp, &quot;model.pkl&quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now, I understand that it might not be the prettiest code you&apos;ve ever seen. But hey &lt;em&gt;&quot;if it looks stupid but it works, it ain&apos;t stupid!&quot;&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;This function, aptly named train, takes in our pre-processed features as input. It prepares the data, scales it, splits it into training and testing sets, and then trains our MLP model. Finally, the trained model is saved to the disk for future use.&lt;/p&gt;
&lt;p&gt;The model training process involves a few steps:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;We first construct our feature matrix X and target vector y.&lt;/li&gt;
&lt;li&gt;The feature data is then standardized to ensure that our MLP isn&apos;t swayed unduly by features that naturally have larger values.&lt;/li&gt;
&lt;li&gt;Our data is split into a training set to teach our model and a test set to verify its performance. We&apos;re reserving 30% of the data for testing purposes.&lt;/li&gt;
&lt;li&gt;An MLPClassifier object is then initialized with two hidden layers, each having 100 neurons. The training process is carried out over 200 iterations (epochs).&lt;/li&gt;
&lt;li&gt;The model is then trained using the fit method, and we finally save our trained model to a file named model.pkl for future use.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&amp;lt;Trivia emoji=&quot;🚜&quot;&amp;gt;
The beauty of coding isn&apos;t just about creating intricate and aesthetically
pleasing lines of code. It&apos;s about getting the job done, and our humble piece
of training code does just that – efficiently, and effectively!
&amp;lt;/Trivia&amp;gt;&lt;/p&gt;
&lt;h2&gt;Classification: Bringing the AI to Life with Labels&lt;/h2&gt;
&lt;p&gt;The model training chapter has been a roller coaster, and now we have a trained model ready to unleash on leaf images. The next exciting chapter is about the classification, where our trained Multi-Layer Perceptron (MLP) takes in the processed features and recognizes the types of leaves.&lt;/p&gt;
&lt;p&gt;Here&apos;s how the magic unfolds:&lt;/p&gt;
&lt;h3&gt;Loading the Trained Model&lt;/h3&gt;
&lt;p&gt;First, we load our previously saved MLP model from the disk.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;mlp = load(&quot;model.pkl&quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Preparing the Features&lt;/h3&gt;
&lt;p&gt;We loop through the files, extract the features, and construct our feature matrix &lt;code&gt;X&lt;/code&gt; just like we did in the training process.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;for file in files:
    X = []
    for d in features[file]:
        lbp_feature = list(chain(*d[&quot;lbp&quot;]))
        feature = [
            d[&quot;aspect_ratio&quot;],
            d[&quot;eccentricity&quot;],
            d[&quot;extent&quot;],
            d[&quot;solidity&quot;],
            *d[&quot;hu_moments&quot;],
            *lbp_feature,
        ]
        X.append(feature)

    # Convert the lists to numpy arrays
    X = np.array(X)
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Scaling and Prediction&lt;/h3&gt;
&lt;p&gt;The features are then standardized, and the MLP model predicts the classes along with the probabilities for each class.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# Scale your data
scaler = StandardScaler()
X = scaler.fit_transform(X)

# Predict the classes
predictions = mlp.predict(X)
probabilities = mlp.predict_proba(X)
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Labeling the Images&lt;/h3&gt;
&lt;p&gt;The predictions and probabilities are then used to annotate the original images with labels. The bounding rectangles and labels are drawn on the images.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;image = cv2.imread(file)
probability_of_class = np.max(probabilities, axis=1)

for i, leaf_features in enumerate(features[file]):
    # Get the bounding rectangle and calculate the label positions
    # Draw the text labels and percentage labels on the image
    print(f&quot;Label: {predictions[i]} with probability {probability_of_class[i]}&quot;)

    print(&quot;Features:&quot;)
    leaf_contour = leaf_features[&quot;contours&quot;][i]

    # Get the bounding rectangle
    x, y, w, h = cv2.boundingRect(leaf_contour)

    # Calculate the center of the rectangle
    class_label = (x + w // 2, y + h // 2)
    percentage_label = (x + w // 2, y + h // 2 + 40)

    # Draw the text label on the image
    cv2.putText(
        image,
        str(predictions[i]),
        class_label,
        cv2.FONT_HERSHEY_SIMPLEX,
        1,
        (0, 255, 0),
        2,
    )

    # Draw the percentage label on the image
    cv2.putText(
        image,
        f&quot;{probability_of_class[i] * 100:.2f}%&quot;,
        percentage_label,
        cv2.FONT_HERSHEY_SIMPLEX,
        1,
        (255, 255, 0),
        2,
    )

# Save the classified image
cv2.imwrite(&quot;classified/&quot; + file.split(&quot;/&quot;)[-1], image)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The result is an image where each leaf is labeled with its corresponding class and confidence score.&lt;/p&gt;
&lt;p&gt;&amp;lt;Trivia emoji=&quot;🍃&quot;&amp;gt;
The classification step is where the AI showcases its intelligence, turning
raw data into insights. It is the final piece that completes the puzzle,
letting us see the leaves through the lens of our intelligent algorithm.
&amp;lt;/Trivia&amp;gt;&lt;/p&gt;
&lt;p&gt;&amp;lt;Image
src={finalImage}
alt=&quot;A image from the dataset&quot;
class=&quot;self-center md:h-1/2 md:w-1/2&quot;
/&amp;gt;&lt;/p&gt;
&lt;p&gt;This brings us to the end of our AI journey to understand leaves. We&apos;ve learned about preprocessing, feature extraction, model training, and classification. Now you have a full-fledged system capable of recognizing and labeling different types of leaves. Happy leaf hunting! 🍁&lt;/p&gt;
</content:encoded></item></channel></rss>