<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Ernesto — Backend Engineering & Beyond]]></title><description><![CDATA[I'm a full stack developer with experience in Vue, React, Node, NestJS, MongoDB, Flutter and SQL. I write about my experiences and share tips and tricks on how to build better web and mobile apps]]></description><link>https://ernestoyanac.com</link><generator>RSS for Node</generator><lastBuildDate>Wed, 11 Nov 2026 16:48:59 GMT</lastBuildDate><atom:link href="https://ernestoyanac.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[NestJS Custom Decorators and Pipes: Stop Sending Context in Query Params]]></title><description><![CDATA[Stop sending context in query params. Use NestJS createParamDecorator + an async DI pipe to resolve user context server-side, from JWT to handler.]]></description><link>https://ernestoyanac.com/nestjs-custom-decorator-async-pipe-request-context</link><guid isPermaLink="true">https://ernestoyanac.com/nestjs-custom-decorator-async-pipe-request-context</guid><category><![CDATA[nestjs]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[backend]]></category><category><![CDATA[clean code]]></category><category><![CDATA[design patterns]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Ernesto Yanac Huertas]]></dc:creator><pubDate>Sat, 25 Jul 2026 09:41:40 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/641a26b67b483d01e1b3f58a/88363666-6541-4746-97b5-0582913dc449.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Every request in our e-commerce API used to look like this:</p>
<pre><code class="language-plaintext">GET /api/cart/items?storeKey=store-fr&amp;country=FR&amp;currency=EUR
</code></pre>
<p>The frontend computed <code>storeKey</code>, <code>country</code>, and <code>currency</code> from the logged-in user's profile and attached them to <strong>every single request</strong>. Cart, checkout, orders, wishlist — same three query params, everywhere.</p>
<p>This is a quiet design smell, and one day we admitted it had real costs:</p>
<ol>
<li><p><strong>Trust.</strong> Query params are user input. Nothing stops a client from sending <code>currency=XXX</code> and seeing prices in a market they don't belong to. We were re-validating on the backend what the backend already knew.</p>
</li>
<li><p><strong>Duplication.</strong> Every frontend hook re-implemented the same "resolve store from user profile" logic.</p>
</li>
<li><p><strong>Leaky ownership.</strong> The <em>backend</em> owns pricing and stock, but the <em>frontend</em> decided which store and currency to query.</p>
</li>
</ol>
<p>The fix: resolve that context <strong>server-side</strong>, and expose it to route handlers with one decorator:</p>
<pre><code class="language-ts">@Get('cart')
getCart(@ShopperContext() ctx: ShopperContext) {
  // ctx.storeKey, ctx.country, ctx.currency — resolved server-side
}
</code></pre>
<p>One clarification before we go further, because it's a common misconception:</p>
<blockquote>
<p><strong>The JWT is the identity, not the data source.</strong> The only thing we take from the token is the user's <strong>email</strong> (the <code>sub</code> claim), extracted by the auth guard during validation. Everything else — store, country, currency, locale — is fetched from our own storage (Redis cache, PostgreSQL fallback) <em>using that email</em>. You should never stuff preferences into the JWT itself: they'd go stale until the token expires, and they bloat every request's header.</p>
</blockquote>
<p>This post explains the pattern, why it's built from <strong>two</strong> NestJS building blocks instead of one, and the pitfalls we hit so you don't have to.</p>
<h2>The scenario</h2>
<p>Our fictional shop, <strong>Shopland</strong>, is a NestJS API. Accounts are stored in PostgreSQL (home store, locale, country) and profiles are cached in Redis. A JWT <code>AuthGuard</code> already validates the token and does the classic:</p>
<pre><code class="language-ts">request['user'] = { email: payload.sub, roles: [...] };
</code></pre>
<p>Every cart endpoint needs a <code>ShopperContext</code>:</p>
<pre><code class="language-ts">export interface ShopperContext {
  accountId: string;
  storeKey: string;   // derived: `store-${country.toLowerCase()}`
  country: string;
  currency: string;   // derived from country
  locale: string;
  homeStoreId: string | null;
}
</code></pre>
<p>The requirements: resolve it <strong>once per request</strong>, from cache-first storage, and make it <strong>impossible to misuse</strong> by the ten developers who'll add endpoints next quarter.</p>
<h2>The NestJS request lifecycle is the key</h2>
<p>Where you hook into the pipeline decides what you're allowed to do:</p>
<pre><code class="language-plaintext">Middleware → Guards → Interceptors (pre) → Pipes → Handler → Interceptors (post) → Filters
</code></pre>
<p>Two lifecycle facts drive the whole design:</p>
<ul>
<li><p><strong>Pipes run after guards.</strong> When our pipe executes, <code>AuthGuard</code> has already populated <code>request.user</code>. Ordering is free.</p>
</li>
<li><p><strong>Pipes transform handler arguments.</strong> Per the official docs, pipes exist for exactly two things: <em>transformation</em> and <em>validation</em> of route-handler parameters.</p>
</li>
</ul>
<h2>Why not a guard, interceptor, or middleware?</h2>
<p>I see these misused constantly, so let's be precise about what the docs say each block is <em>for</em>:</p>
<table>
<thead>
<tr>
<th>Building block</th>
<th>Documented purpose</th>
<th>Async + DI?</th>
<th>Verdict for our case</th>
</tr>
</thead>
<tbody><tr>
<td><strong>Guard</strong></td>
<td>"Determine whether a given request will be handled" — <strong>authorization</strong></td>
<td>✅</td>
<td>Off-label. It <em>can</em> attach data (the docs' own auth example does <code>request['user'] = payload</code>), but fetching a profile isn't an allow/deny decision</td>
</tr>
<tr>
<td><strong>Interceptor</strong></td>
<td>Bind logic before/after execution, transform the <strong>response</strong>, caching</td>
<td>✅</td>
<td>Works, but semantics are cross-cutting concerns, not argument resolution</td>
</tr>
<tr>
<td><strong>Middleware</strong></td>
<td>Framework-level pre-processing</td>
<td>limited</td>
<td>❌ Runs <strong>before</strong> guards — <code>request.user</code> doesn't exist yet</td>
</tr>
<tr>
<td><strong>Pipe</strong></td>
<td>"<strong>Transformation</strong>: transform input data to the desired form"</td>
<td>✅</td>
<td>✅ Textbook fit: transform the authenticated identity into a rich context object</td>
</tr>
<tr>
<td><strong>REQUEST-scoped provider</strong></td>
<td>Lazy per-request injection</td>
<td>✅</td>
<td>Valid, but it makes <strong>every consumer</strong> request-scoped too (new instance graph per request — the docs explicitly warn about the perf cost)</td>
</tr>
</tbody></table>
<p>Using a guard to fetch data "because the auth example does it" is the most common justification I hear. The auth example attaches the <em>by-product of a decision it already made</em>. Fetching a profile is not a decision — it's a transformation. Stay in your lane, and the codebase stays teachable.</p>
<h2>The two-piece constraint</h2>
<p>Here's the trap that forces the design:</p>
<ul>
<li><p><strong>Param decorator factories are synchronous and have no dependency injection.</strong> <code>createParamDecorator</code> can see the request, but it can't call your <code>ShopperProfileService</code>.</p>
</li>
<li><p><strong>Pipes support async and DI, but they're blind</strong>: a pipe only receives whatever value the decorator extracted. It can't reach the request on its own.</p>
</li>
</ul>
<p>So we chain them: <strong>decorator extracts → pipe transforms.</strong></p>
<blockquote>
<p>⚠️ You may read that async param-decorator factories "work" because Nest awaits the factory result internally. That's undocumented behavior — don't build on it.</p>
</blockquote>
<h2>Implementation</h2>
<h3>1. The service: cache-first profile lookup</h3>
<pre><code class="language-typescript">@Injectable()
export class ShopperProfileService {
  constructor(
    @InjectRepository(Account) private readonly accounts: Repository&lt;Account&gt;,
    @Inject(CACHE_MANAGER) private readonly cache: Cache,
  ) {}

  /** Returns the cached ShopperProfile, or the Account entity on cache miss. */
  async findProfile(email: string): Promise&lt;ShopperProfile | Account&gt; {
    const key = `shopper:profile:${hash(email.toLowerCase().trim())}`;

    try {
      const userCached = await this.cache.get&lt;ShopperProfile&gt;(key);
      if (userCached) return userCached;
    } catch {
      // cache is an optimization — fall through to the database
    }

    const account = await this.accounts.findOne({
      where: { email: email.toLowerCase().trim() },
    });
    if (!account) throw new NotFoundException(`No profile for ${email}`);
    return account;
  }
}
</code></pre>
<p>Note it returns a <strong>union</strong> — cache gives you a plain object, TypeORM gives you an entity instance. The pipe handles both.</p>
<h3>2. The param decorator: extract the raw request</h3>
<pre><code class="language-typescript">export const RawRequest = createParamDecorator(
  // _data must stay: Nest always calls the factory as (data, ctx).
  // The placeholder keeps ctx in the second position.
  (_data: unknown, ctx: ExecutionContext): ShopperContextRequest =&gt;
    ctx.switchToHttp().getRequest&lt;ShopperContextRequest&gt;(),
);
</code></pre>
<p>Why the whole request and not just the email? Because the pipe needs it twice: to <strong>read</strong> <code>request.user.email</code>, and to <strong>write back</strong> <code>request.shopperContext</code> at the end (so interceptors or downstream code can use it too).</p>
<h3>3. The pipe: async transformation</h3>
<pre><code class="language-ts">@Injectable()
export class ShopperContextPipe implements PipeTransform&lt;
  ShopperContextRequest,
  Promise&lt;ShopperContext&gt;
&gt; {
  constructor(private readonly profiles: ShopperProfileService) {}

  async transform(request: ShopperContextRequest): Promise&lt;ShopperContext&gt; {
    const email = request.user?.email;
    if (!email) {
      throw new UnauthorizedException('Is AuthGuard applied?');
    }

    const source = await this.profiles.findProfile(email);

    const context =
      source instanceof Account            // entity instance → DB path
        ? this.buildFromAccount(source)
        : this.buildFromCache(source);     // plain object → cache path

    request.shopperContext = context;      // side effect: available downstream
    return context;
  }

  private buildFromAccount(account: Account): ShopperContext {
    const country = account.countryCode ?? 'US';
    return {
      accountId: account.id,
      storeKey: `store-${country.toLowerCase()}`,
      country,
      currency: currencyForCountry(country),
      locale: account.locale ?? 'en-US',
      homeStoreId: account.homeStoreId ?? null,
    };
  }
  // buildFromCache mirrors this for the cached shape...
}
</code></pre>
<p><code>instanceof Account</code> is a clean discriminator: TypeORM returns real entity instances, your cache returns deserialized plain objects.</p>
<h3>4. The wrapper: making the right thing effortless</h3>
<p>You could stop here and write <code>@RawRequest(ShopperContextPipe)</code> at every call site. <strong>Don't.</strong> There's a foot-gun TypeScript cannot catch:</p>
<pre><code class="language-ts">@Get('cart')
getCart(@RawRequest() ctx: ShopperContext) { ... }
//      ↑ forgot the pipe — compiles fine, and at runtime
//        ctx is the RAW REQUEST, not a ShopperContext 💥
</code></pre>
<p>There's zero type linkage between a custom decorator's factory output and the handler's declared parameter type. So bundle extractor + pipe into one named decorator:</p>
<pre><code class="language-ts">export function ShopperContext(): ParameterDecorator {
  return RawRequest(ShopperContextPipe);
}
</code></pre>
<p>Now the correct usage is also the shortest usage. That's not cosmetic — it's API design: you made the mistake <em>unrepresentable</em>.</p>
<h2>The result</h2>
<p><strong>Before</strong> — client-sent context, validated defensively:</p>
<pre><code class="language-typescript">@Get('cart')
getCart(
  @Query('storeKey') storeKey: string,     // who do you trust?
  @Query('currency') currency: string,
) { ... }
</code></pre>
<p><strong>After</strong> — server-resolved, one line:</p>
<pre><code class="language-typescript">@UseGuards(AuthGuard) // validates JWT, sets request.user.email
@Get('cart')
getCart(@ShopperContext() ctx: ShopperContext) {
  return this.cartService.getCart(ctx);
}
</code></pre>
<p>The frontend deletes its context-building hooks. The backend owns country/currency resolution — as it should, since it owns pricing.</p>
<h2>Pitfalls I hit (so you don't)</h2>
<ol>
<li><p><strong>Unit tests break in a surprising way.</strong> Nest instantiates param-pipe classes <em>when the testing module compiles</em>. A bare <code>Test.createTestingModule({ controllers: [CartController] })</code> will fail with "can't resolve dependencies of ShopperContextPipe". Fix: register the dependency as a mock provider — <code>{ provide: ShopperProfileService, useValue: { findProfile: vi.fn() } }</code>. Same behavior applies to <code>@UseGuards</code> classes.</p>
</li>
<li><p><strong>You can't remove the</strong> <code>_data</code> <strong>parameter</strong> from the decorator factory. Nest always calls it as <code>(data, ctx)</code> — the first slot is positional. Delete it and your <code>ctx</code> receives the decorator argument instead. Runtime crash, every request.</p>
</li>
<li><p><code>applyDecorators()</code> <strong>does not work for parameter decorators.</strong> It composes class/method decorators only. The function wrapper above is the correct mechanism.</p>
</li>
<li><p><strong>Ordering matters but is automatic:</strong> pipes always run after guards, so <code>@UseGuards(AuthGuard)</code> on the controller is enough. Just don't try the same trick in middleware — it runs <em>before</em> guards.</p>
</li>
</ol>
<h2>Why this respects NestJS guidelines</h2>
<ul>
<li><p><strong>Pipes do what pipes are documented to do</strong> — transform input data into the desired form. <code>email → ShopperContext</code> is exactly that.</p>
</li>
<li><p><strong>Guards keep their single responsibility</strong> (allow/deny). We didn't smuggle data-fetching into one.</p>
</li>
<li><p><strong>Each block is testable in isolation</strong>: the service with a mocked repository, the pipe with a mocked service, the decorator by invoking its stored factory from <code>ROUTE_ARGS_METADATA</code>.</p>
</li>
<li><p><strong>No</strong> <code>Scope.REQUEST</code> <strong>provider</strong>, avoiding the hidden per-request instantiation cost the docs warn about.</p>
</li>
</ul>
<h2>Key takeaways</h2>
<ul>
<li><p>Query params are user input. If the server already knows something, don't ask the client for it.</p>
</li>
<li><p>The JWT carries <strong>identity</strong> (email), your storage carries <strong>state</strong> (profile). Don't blur that line.</p>
</li>
<li><p><code>createParamDecorator</code> extracts (sync, no DI) → pipes transform (async, DI) → a wrapper decorator fuses them so the pipe can't be forgotten.</p>
</li>
<li><p>Choose building blocks by their <em>documented</em> purpose, not by what you can technically force them to do. Future maintainers — including you in six months — will read semantics, not just code.</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[How to Implement Idempotency in a NestJS + PostgreSQL Stack (Without Losing Sleep Over Duplicate Requests)]]></title><description><![CDATA[Guide to implementing idempotency in a Vue + NestJS + PostgreSQL stack using idempotency keys, a custom NestJS Guard, and SQL]]></description><link>https://ernestoyanac.com/how-to-implement-idempotency-in-a-nestjs-postgresql-stack-without-losing-sleep-over-duplicate-requests</link><guid isPermaLink="true">https://ernestoyanac.com/how-to-implement-idempotency-in-a-nestjs-postgresql-stack-without-losing-sleep-over-duplicate-requests</guid><category><![CDATA[nestjs]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[PostgreSQL]]></category><category><![CDATA[backend]]></category><category><![CDATA[api]]></category><category><![CDATA[idempotence]]></category><dc:creator><![CDATA[Ernesto Yanac Huertas]]></dc:creator><pubDate>Sat, 23 May 2026 09:02:57 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/641a26b67b483d01e1b3f58a/0eaaeb78-ec1c-43c9-82cb-62198c22589a.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>How to Implement Idempotency in a NestJS + PostgreSQL Stack</h2>
<p>If you've ever built a payment flow or an order creation endpoint, you've probably faced this scenario: the user clicks "Submit", the network hiccups, the client retries — and suddenly you've charged them twice. That's exactly the problem <strong>idempotency</strong> solves.</p>
<p>Idempotency means that executing the same operation multiple times produces the same result as executing it once. It's a foundational concept in distributed systems, and something every senior backend engineer should have in their toolkit.</p>
<p>In this post I'll walk through one practical way to implement it in a <strong>Vue + NestJS + PostgreSQL</strong> stack. It's not the only approach — I'll touch on alternatives at the end — but it's clean, pragmatic, and battle-tested.</p>
<h2>The Core Pattern: Idempotency Keys</h2>
<p>The idea is simple:</p>
<ol>
<li><p>The client generates a unique key (UUID) per user action</p>
</li>
<li><p>It sends that key in every request for that action</p>
</li>
<li><p>The server stores the result of the first execution</p>
</li>
<li><p>On duplicate requests, it returns the cached result without re-executing</p>
</li>
</ol>
<h2>Implementation</h2>
<h3>1. Client (Vue)</h3>
<p>Generate the key once per user action and hold it until the operation is confirmed. Don't regenerate on retry — that defeats the purpose.</p>
<pre><code class="language-js">const idempotencyKey = crypto.randomUUID()

await axios.post('/payments', payload, {
  headers: { 'Idempotency-Key': idempotencyKey }
})
</code></pre>
<h3><strong>2. NestJS Guard</strong></h3>
<p>A Guard is a clean place to intercept the request before it hits your controller. If we've seen this key before and have a stored result, we short-circuit the response immediately.</p>
<pre><code class="language-typescript">@Injectable()
export class IdempotencyGuard implements CanActivate {
  constructor(private readonly idempotencyService: IdempotencyService) {}

  async canActivate(context: ExecutionContext): Promise&lt;boolean&gt; {
    const req = context.switchToHttp().getRequest()
    const res = context.switchToHttp().getResponse()
    const key = req.headers['idempotency-key']

    if (!key) return true

    const cached = await this.idempotencyService.get(key)
    if (cached) {
      res.status(cached.status).json(cached.body)
      return false
    }

    req.idempotencyKey = key
    return true
  }
}
</code></pre>
<h3><strong>3. Service</strong></h3>
<p>Store the result After executing the business logic, persist the result tied to the key. Next time the same key arrives, the Guard handles it before your service is even called.</p>
<pre><code class="language-typescript">async createPayment(dto: CreatePaymentDto, key: string) {
  const result = await this.processPayment(dto)

  await this.idempotencyService.save(key, {
    status: 201,
    body: result,
    expiresAt: addHours(new Date(), 24)
  })

  return result
}
</code></pre>
<h3>4. PostgreSQL Table</h3>
<pre><code class="language-sql">CREATE TABLE idempotency_keys (
  key         UUID PRIMARY KEY,
  status      INT NOT NULL,
  body        JSONB NOT NULL,
  created_at  TIMESTAMP DEFAULT NOW(),
  expires_at  TIMESTAMP NOT NULL
);
</code></pre>
<h3>5. IdempotencyService — Raw SQL</h3>
<p>You'll notice we're using raw SQL here rather than an ORM like TypeORM or Prisma. That's a deliberate choice for this example — raw SQL gives you full control over query execution, and in a case like this the queries are simple enough that an ORM adds more abstraction than value. That said, the approach works equally well with any ORM; it's up to you and your team's conventions.</p>
<pre><code class="language-typescript">async get(key: string) {
  return this.db.query(
    `SELECT * FROM idempotency_keys 
     WHERE key = $1 AND expires_at &gt; NOW()`,
    [key]
  )
}

async save(key: string, data: { status: number, body: object, expiresAt: Date }) {
  await this.db.query(
    `INSERT INTO idempotency_keys (key, status, body, expires_at)
     VALUES (\(1, \)2, \(3, \)4)
     ON CONFLICT (key) DO NOTHING`,
    [key, data.status, data.body, data.expiresAt]
  )
}
</code></pre>
<p>The <code>ON CONFLICT DO NOTHING</code> clause is doing important work here — it handles race conditions at the database level, so even if two identical requests arrive simultaneously, only one will ever be written.</p>
<h2>Things Worth Knowing Key expiry.</h2>
<p>Keys don't need to live forever. 24 hours is a common default for most use cases. Clean up expired rows periodically with a scheduled job. Scope by user. If your system is multi-tenant, consider prefixing keys with the user or account ID (userId:uuid) to avoid any risk of cross-user collisions. Only apply it where it matters. Idempotency is relevant for non-idempotent operations: POST, PATCH, and anything with side effects. Don't wrap GET endpoints in this — they're already idempotent by nature.</p>
<h2>Other Ways to Achieve This</h2>
<p>This is one approach, but it's worth knowing the alternatives depending on your constraints: Redis as the idempotency store. Instead of PostgreSQL, use Redis with a TTL. It's faster for lookups and handles expiry natively. The trade-off is that Redis is a separate dependency and isn't durable by default — a restart could lose your idempotency records. A common pattern is to use Redis as a fast cache layer and PostgreSQL as the source of truth. Database-level unique constraints. If your operation maps to inserting a unique record (e.g. an order), a unique constraint on a client_reference_id column can be enough. The insert fails silently on duplicate, and you return the existing record. Simpler, but only works when the idempotency maps directly to a unique row. Transactional outbox pattern. For event-driven systems, combining idempotency with an outbox pattern ensures that both the DB write and the event emission happen exactly once. Overkill for most cases, but the right tool for complex distributed flows. Stripe's approach. Worth studying — Stripe stores idempotency keys server-side, tied to the authenticated user and the request path, and rejects keys reused with a different request body. A stricter but more robust implementation for financial systems.</p>
<blockquote>
<p>Idempotency isn't glamorous, but it's one of those things that separates systems that work from systems that almost work. Pick the approach that fits your architecture, be consistent, and your future self will thank you.</p>
</blockquote>
<p>Found this useful? Follow for more backend engineering content on NestJS, PostgreSQL, and distributed systems.</p>
]]></content:encoded></item><item><title><![CDATA[Updating multiple MongoDB documents - NodeJS: A BulkWrite Journey]]></title><description><![CDATA[Learn how to efficiently update existing MongoDB documents using MongoDB's bulkWrite function for performance and consistency]]></description><link>https://ernestoyanac.com/updating-multiple-mongodb-documents-nodejs-bulkwrite</link><guid isPermaLink="true">https://ernestoyanac.com/updating-multiple-mongodb-documents-nodejs-bulkwrite</guid><category><![CDATA[MongoDB]]></category><category><![CDATA[Performance Optimization]]></category><category><![CDATA[Node.js]]></category><dc:creator><![CDATA[Ernesto Yanac Huertas]]></dc:creator><pubDate>Sat, 13 Jul 2024 13:03:08 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/cijiWIwsMB8/upload/1cbbac9f59fe0c6abf5df1a231f9e2ca.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hey there! We're diving into the world of MongoDB and tackling a common scenario: updating existing data to include a new field. Specifically, we'll be adding a "tenancyName" field to our "posts" collection, using the corresponding "tenancyName" from a "companies" collection.</p>
<p>This could be achieved using an update aggregation pipeline, but for educational purposes, we will get the Posts joined with Company data and then create an update array to use a bulkWrite.</p>
<p><a target="_blank" href="https://ernestoyanac.com/bulkwrite-vs-iterative-updates"><strong>Why use bulkWrite instead of iterating with update statements?</strong></a></p>
<p>Let's break down the code and understand the process.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { MongoClient } <span class="hljs-keyword">from</span> <span class="hljs-string">'mongodb'</span>
<span class="hljs-keyword">import</span> { IPost } <span class="hljs-keyword">from</span> <span class="hljs-string">'src/infrastructure/database/post/post.interface'</span>

<span class="hljs-keyword">const</span> uri = process.env.DB_MONGO_URI
<span class="hljs-keyword">const</span> client = <span class="hljs-keyword">new</span> MongoClient(uri)

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateCompaniesWithTenancyName</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">await</span> client.connect()

    <span class="hljs-keyword">const</span> database = client.db(process.env.DB_NAME)
    <span class="hljs-keyword">const</span> postsCollection = database.collection&lt;IPost&gt;(<span class="hljs-string">'posts'</span>)
    <span class="hljs-keyword">const</span> postsWithCompany = <span class="hljs-keyword">await</span> postsCollection
      .aggregate([
        {
          $lookup: {
            <span class="hljs-keyword">from</span>: <span class="hljs-string">'companies'</span>,
            localField: <span class="hljs-string">'companyId'</span>,
            foreignField: <span class="hljs-string">'_id'</span>,
            <span class="hljs-keyword">as</span>: <span class="hljs-string">'companyData'</span>,
          },
        },
      ])
      .toArray()

    <span class="hljs-keyword">const</span> bulkedPosts = postsWithCompany.reduce(<span class="hljs-function">(<span class="hljs-params">acc, currentPost</span>) =&gt;</span> {
      <span class="hljs-keyword">if</span> (currentPost.companyData.length &gt; <span class="hljs-number">0</span>) {
        <span class="hljs-keyword">const</span> updateOnePost = {
          updateOne: {
            filter: {
              _id: currentPost._id,
            },
            update: {
              $set: {
                tenancyName: currentPost.companyData[<span class="hljs-number">0</span>].tenancyName,
              },
            },
          },
        }
        acc.push(updateOnePost)
      }
      <span class="hljs-keyword">return</span> acc
    }, [] <span class="hljs-keyword">as</span> <span class="hljs-built_in">any</span>)

    <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> postsCollection.bulkWrite(bulkedPosts)
    <span class="hljs-built_in">console</span>.log(
      <span class="hljs-string">`<span class="hljs-subst">${result.matchedCount}</span> document(s) matched the filter, updated <span class="hljs-subst">${result.modifiedCount}</span> document(s)`</span>,
    )
  } <span class="hljs-keyword">finally</span> {
    <span class="hljs-keyword">await</span> client.close()
  }
}

updateCompaniesWithTenancyName().catch(<span class="hljs-built_in">console</span>.dir)
</code></pre>
<p><strong>Execute the script using Node.js:</strong></p>
<pre><code class="lang-bash">DB_MONGO_URI=<span class="hljs-string">"[[YourMongoDB_URI]]"</span> DB_NAME=<span class="hljs-string">"[[YourMongoDBName]]"</span> node <span class="hljs-string">'[[PathToYourJavaScriptFile]]'</span>
</code></pre>
<p><em>\</em>Don't forget to create your js file from this typescript example*</p>
<p><strong>Step 1: Connecting to MongoDB</strong></p>
<p>We start by establishing a connection to our MongoDB database using the <code>MongoClient</code> from the <code>mongodb</code> library. We use the <code>uri</code> variable, which holds the connection string, and create a new <code>MongoClient</code> instance.</p>
<p><strong>Step 2: Accessing Collections</strong></p>
<p>Once connected, we access the "posts" and "companies" collections using the <code>db</code> object. We'll be working with these collections to perform the update.</p>
<p><strong>Step 3: Finding Posts with Company Data</strong></p>
<p>The core of our update lies in the <code>aggregate</code> function. We use a <code>$lookup</code> stage to join the "posts" collection with the "companies" collection based on the "companyId" field. This creates a new field called "companyData" in each post document, containing the corresponding company information.</p>
<p><strong>Step 4: Preparing Bulk Update Operations</strong></p>
<p>We iterate through the results of the aggregation and build an array of update operations using the <code>reduce</code> function. For each post that has associated company data, we create an <code>updateOne</code> operation that sets the "tenancyName" field to the "tenancyName" from the company data.</p>
<p><strong>Step 5: Executing the Bulk Update</strong></p>
<p>Finally, we use the <code>bulkWrite</code> function on the "posts" collection to execute all the prepared update operations in a single batch. This ensures efficiency and minimizes the impact on the database.</p>
<p><strong>Step 6: Logging the Results</strong></p>
<p>After the update, we log the number of documents that matched the filter and the number of documents that were actually updated. This provides valuable feedback on the success of the operation.</p>
<p><strong>Key Takeaways</strong></p>
<ul>
<li><p><strong>MongoDB's</strong><code>aggregate</code> function is powerful for data manipulation and joins.</p>
</li>
<li><p><strong>Bulk operations are essential for efficient updates on large datasets.</strong></p>
</li>
<li><p><strong>Always remember to close the connection to the database after you're done.</strong></p>
</li>
</ul>
<p>This example demonstrates a common use case for updating data in MongoDB. By understanding the concepts of aggregation, joins, and bulk operations, you can confidently tackle similar tasks in your own projects.</p>
]]></content:encoded></item><item><title><![CDATA[BulkWrite vs. Iterative Updates]]></title><description><![CDATA[Discover why using MongoDB's bulkWrite function is significantly more efficient than iterative updates for updating multiple documents. Learn about the…]]></description><link>https://ernestoyanac.com/bulkwrite-vs-iterative-updates</link><guid isPermaLink="true">https://ernestoyanac.com/bulkwrite-vs-iterative-updates</guid><category><![CDATA[MongoDB]]></category><category><![CDATA[Databases]]></category><category><![CDATA[MongoDB Atlas]]></category><dc:creator><![CDATA[Ernesto Yanac Huertas]]></dc:creator><pubDate>Sat, 13 Jul 2024 12:46:55 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/0k_dCKxyIHc/upload/02433e6e7f41b3e23cb3290ea1634dad.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>We often encounter scenarios where we need to update multiple documents in a MongoDB collection. One common approach is to iterate through the documents and execute individual update statements. However, MongoDB provides a more efficient alternative: the <code>bulkWrite</code> function.</p>
<p>Let's delve into the reasons why <code>bulkWrite</code> reigns supreme over iterative updates:</p>
<h3 id="heading-1-performance-boost"><strong>1. Performance Boost:</strong></h3>
<ul>
<li><p><strong>Reduced Network Overhead:</strong> Iterative updates involve multiple round trips to the database, each requiring a separate network request. <code>bulkWrite</code>, on the other hand, bundles all update operations into a single request, significantly reducing network latency.</p>
</li>
<li><p><strong>Optimized Database Operations:</strong> MongoDB can optimize the execution of bulk operations, processing multiple updates in a single transaction. This minimizes the overhead associated with individual update operations.</p>
</li>
</ul>
<h3 id="heading-2-improved-consistency"><strong>2. Improved Consistency:</strong></h3>
<ul>
<li><strong>Atomic Updates:</strong><code>bulkWrite</code> ensures that all update operations within a batch are executed atomically. This means that either all updates succeed or none of them do, guaranteeing data consistency. Iterative updates, however, can lead to inconsistencies if an update fails mid-process.</li>
</ul>
<h3 id="heading-3-enhanced-error-handling"><strong>3. Enhanced Error Handling:</strong></h3>
<ul>
<li><strong>Centralized Error Management:</strong><code>bulkWrite</code> provides a single point of error handling. You can catch any errors that occur during the bulk operation and handle them accordingly. With iterative updates, you need to handle errors individually for each update, making error management more complex.</li>
</ul>
<h3 id="heading-4-simplified-code"><strong>4. Simplified Code:</strong></h3>
<ul>
<li><strong>Concise and Readable:</strong><code>bulkWrite</code> offers a more concise and readable way to perform multiple updates. It eliminates the need for complex loops and error handling logic, making your code cleaner and easier to maintain.</li>
</ul>
<h3 id="heading-example"><strong>Example:</strong></h3>
<p>Let's consider a scenario where we need to update the "tenancyName" field in multiple "posts" documents.</p>
<p><strong>Iterative Approach:</strong></p>
<pre><code class="lang-typescript">content_copyaddcompare_arrowsopen_in_fullfor (<span class="hljs-keyword">const</span> post <span class="hljs-keyword">of</span> posts) {
  <span class="hljs-keyword">await</span> postsCollection.updateOne(
    { _id: post._id },
    { $set: { tenancyName: post.tenancyName } },
  );
}
</code></pre>
<p><strong>BulkWrite Approach:</strong></p>
<pre><code class="lang-typescript">content_copyaddcompare_arrowsopen_in_fullconst bulkOperations = posts.map(<span class="hljs-function">(<span class="hljs-params">post</span>) =&gt;</span> ({
  updateOne: {
    filter: { _id: post._id },
    update: { $set: { tenancyName: post.tenancyName } },
  },
}));

<span class="hljs-keyword">await</span> postsCollection.bulkWrite(bulkOperations);
</code></pre>
<p>As you can see, the <code>bulkWrite</code> approach is significantly more concise and efficient.</p>
<h3 id="heading-conclusion"><strong>Conclusion:</strong></h3>
<p>While iterative updates might seem intuitive, <code>bulkWrite</code> offers a superior solution for updating multiple documents in MongoDB. It provides significant performance gains, improved consistency, enhanced error handling, and simplified code. Embrace the power of <code>bulkWrite</code> and streamline your MongoDB update operations!</p>
<p><strong>Reference:</strong><a target="_blank" href="https://www.mongodb.com/docs/drivers/node/current/usage-examples/bulkWrite/#:~:text=The%20bulkWrite()%20method%20performs,increases%20the%20throughput%20and%20performance.">https://www.mongodb.com/docs/drivers/node/current/usage-examples/bulkWrite/#:~:text=The%20bulkWrite()%20method%20performs,increases%20the%20throughput%20and%20performance.</a></p>
]]></content:encoded></item><item><title><![CDATA[Dynamic Slot Names: A Cool Way to Make Your Vue Components More Flexible]]></title><description><![CDATA[Dynamic slot names in Vue are a powerful way to create reusable, flexible, and interactive components. Learn how to use dynamic slot names]]></description><link>https://ernestoyanac.com/vue-dynamic-slot-names</link><guid isPermaLink="true">https://ernestoyanac.com/vue-dynamic-slot-names</guid><category><![CDATA[Vue.js]]></category><category><![CDATA[Frontend Development]]></category><category><![CDATA[full stack]]></category><dc:creator><![CDATA[Ernesto Yanac Huertas]]></dc:creator><pubDate>Thu, 26 Oct 2023 20:37:46 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1698352087913/ef7c1c83-8645-490d-9f80-0c061b39bf2d.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this post, we're going to talk about dynamic slot names. Dynamic slot names are a cool way to make your Vue components more flexible and reusable.</p>
<h2 id="heading-what-are-dynamic-slot-names">What are Dynamic Slot Names?</h2>
<p>Dynamic Slot Names allow you to inject content into a child component based on any value, such as the name of a prop or the value of a variable. This is in contrast to regular slot names, which are static and cannot be changed.</p>
<h2 id="heading-why-use-dynamic-slot-names">Why use dynamic slot names?</h2>
<p>There are a few reasons why you might want to use dynamic slot names:</p>
<ul>
<li><p><strong>To create reusable components.</strong> For example, you could create a table component that allows the parent component to specify the columns and rows of the table. You could use dynamic slot names to render the content of each cell in the table.</p>
</li>
<li><p><strong>To create dynamic forms.</strong> For example, you could create a form that allows the user to add new fields to the form. You could use dynamic slot names to render the new fields in the form.</p>
</li>
<li><p><strong>To create interactive UI components.</strong> For example, you could create a tab component that allows the user to switch between different tabs. You could use dynamic slot names to render the content of each tab.</p>
</li>
</ul>
<h2 id="heading-examples">Examples</h2>
<p>Here is an example of a reusable table component that uses dynamic slot names:</p>
<p>Code snippet</p>
<pre><code class="lang-javascript">&lt;template&gt;
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">table</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">thead</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">tr</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">th</span> <span class="hljs-attr">v-for</span>=<span class="hljs-string">"column in columns"</span> <span class="hljs-attr">:key</span>=<span class="hljs-string">"column"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">slot</span> <span class="hljs-attr">:name</span>=<span class="hljs-string">"column"</span> /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">tr</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">thead</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">tbody</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">tr</span> <span class="hljs-attr">v-for</span>=<span class="hljs-string">"item in items"</span> <span class="hljs-attr">:key</span>=<span class="hljs-string">"item.id"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">td</span> <span class="hljs-attr">v-for</span>=<span class="hljs-string">"column in columns"</span> <span class="hljs-attr">:key</span>=<span class="hljs-string">"column"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">slot</span> <span class="hljs-attr">:name</span>=<span class="hljs-string">"column"</span> <span class="hljs-attr">:item</span>=<span class="hljs-string">"item"</span> /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">tr</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">tbody</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">table</span>&gt;</span></span>
&lt;/template&gt;

<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> {
  <span class="hljs-attr">props</span>: {
    <span class="hljs-attr">columns</span>: <span class="hljs-built_in">Array</span>,
    <span class="hljs-attr">items</span>: <span class="hljs-built_in">Array</span>
  }
}
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></span>
</code></pre>
<p>This component can be used to render any type of data, as long as the data is in the form of an array of objects. The <code>columns</code> prop specifies the names of the columns in the table, and the <code>items</code> prop specifies the data to be rendered in the table.</p>
<p>To use this component, you would simply pass in the columns and rows of the table as props. For example:</p>
<p>Code snippet</p>
<pre><code class="lang-javascript">&lt;template&gt;
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Table</span> <span class="hljs-attr">:columns</span>=<span class="hljs-string">"['name', 'age']"</span> <span class="hljs-attr">:items</span>=<span class="hljs-string">"[{ name: 'John Doe', age: 30 }, { name: 'Jane Doe', age: 25 }]"</span> /&gt;</span></span>
&lt;/template&gt;

<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
<span class="hljs-keyword">import</span> Table <span class="hljs-keyword">from</span> <span class="hljs-string">'./Table.vue'</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> {
  <span class="hljs-attr">components</span>: {
    Table
  },

  data() {
    <span class="hljs-keyword">return</span> {
      <span class="hljs-attr">items</span>: [
        { <span class="hljs-attr">name</span>: <span class="hljs-string">'John Doe'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">30</span> },
        { <span class="hljs-attr">name</span>: <span class="hljs-string">'Jane Doe'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">25</span> }
      ]
    }
  }
}
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></span>
</code></pre>
<p>This will render a table with two columns, <code>name</code> and <code>age</code>. The content of each cell in the table will be injected from the parent component using the <code>slot</code> element.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Dynamic slot names are a powerful tool that can help you create more reusable, flexible, and interactive Vue components. If you're not already using dynamic slot names, I encourage you to give them a try. You won't be disappointed!</p>
]]></content:encoded></item><item><title><![CDATA[How to Create a Cropper Component in Vue Using TypeScript and vue-advanced-cropper]]></title><description><![CDATA[How to Create a Cropper Component in Vue Using TypeScript and vue-advanced-cropper]]></description><link>https://ernestoyanac.com/how-to-create-a-cropper-component-in-vue-using-typescript-and-vue-advanced-cropper</link><guid isPermaLink="true">https://ernestoyanac.com/how-to-create-a-cropper-component-in-vue-using-typescript-and-vue-advanced-cropper</guid><category><![CDATA[Vue.js]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[Frontend Development]]></category><dc:creator><![CDATA[Ernesto Yanac Huertas]]></dc:creator><pubDate>Thu, 20 Jul 2023 21:45:40 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1689889665156/1d3a1312-b95d-4a57-8e2f-fd05482330a8.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Using a pre-defined cropper such as Vue-advanced-cropper can save you a lot of time, but using it properly as a reusable component is not always easy to implement. In this tutorial, you will learn how to create a cropper component in Vue using TypeScript and the vue-advanced-cropper library.</p>
<h2 id="heading-getting-started"><strong>Getting Started</strong></h2>
<p>First, you need to install the <a target="_blank" href="https://advanced-cropper.github.io/vue-advanced-cropper/">Vue-advanced-cropper</a> library. You can do this by running the following command in your terminal:</p>
<pre><code class="lang-bash">npm install vue-advanced-cropper
</code></pre>
<p>Once the library is installed, is time to create our reusable component. You can do this by creating a new file called <code>BaseCropper.vue</code></p>
<h2 id="heading-the-code">The code</h2>
<p>The following code shows the basic structure of the <code>BaseCropper.vue</code> component:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"ts"</span> <span class="hljs-attr">setup</span>&gt;</span><span class="javascript">
<span class="hljs-keyword">import</span> { Cropper } <span class="hljs-keyword">from</span> <span class="hljs-string">'vue-advanced-cropper'</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'vue-advanced-cropper/dist/style.css'</span>
<span class="hljs-keyword">import</span> { ref, watch } <span class="hljs-keyword">from</span> <span class="hljs-string">'vue'</span>
defineProps({
  <span class="hljs-attr">imageSource</span>: {
    <span class="hljs-attr">type</span>: <span class="hljs-built_in">String</span>,
    <span class="hljs-attr">required</span>: <span class="hljs-literal">true</span>,
  },
  <span class="hljs-attr">imageSize</span>: {
    <span class="hljs-attr">type</span>: <span class="hljs-built_in">Object</span>,
  },
})
<span class="hljs-keyword">const</span> imageRef = ref(<span class="hljs-string">'parentImageRef'</span>)
<span class="hljs-keyword">const</span> emit = defineEmits([<span class="hljs-string">'onImageChange'</span>, <span class="hljs-string">'onCrop'</span>, <span class="hljs-string">'onCancel'</span>])
watch(imageRef, <span class="hljs-function">() =&gt;</span> {
  emit(<span class="hljs-string">'onImageChange'</span>, imageRef.value)
})
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">template</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">Cropper</span>
      <span class="hljs-attr">ref</span>=<span class="hljs-string">"imageRef"</span>
      <span class="hljs-attr">:src</span>=<span class="hljs-string">"imageSource"</span>
      <span class="hljs-attr">:stencil-size</span>=<span class="hljs-string">"imageSize"</span>
      <span class="hljs-attr">:stencil-props</span>=<span class="hljs-string">"{
        handlers: {},
        movable: false,
        resizable: false,
      }"</span>
      <span class="hljs-attr">image-restriction</span>=<span class="hljs-string">"stencil"</span>
    /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">hr</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"solid"</span> &gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> @<span class="hljs-attr">click</span>=<span class="hljs-string">"$emit('onCancel')"</span>&gt;</span>Cancel<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> @<span class="hljs-attr">click</span>=<span class="hljs-string">"$emit('onCrop')"</span>&gt;</span>Crop image<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">style</span>&gt;</span><span class="css">
<span class="hljs-selector-class">.cropper</span> {
  <span class="hljs-attribute">min-height</span>: <span class="hljs-number">300px</span>;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
}
<span class="hljs-selector-tag">hr</span><span class="hljs-selector-class">.solid</span> {
  <span class="hljs-attribute">border-top</span>: <span class="hljs-number">3px</span> solid <span class="hljs-number">#bbb</span>;
}
</span><span class="hljs-tag">&lt;/<span class="hljs-name">style</span>&gt;</span>
</code></pre>
<p>The template for the <code>Cropper</code> component is simple. It simply renders the <code>Cropper</code> component with the imageSource and imageSize props. It also renders a hr element and two buttons. The first button is used to cancel the crop, and the second button is used to crop the image.</p>
<h2 id="heading-piece-by-piece">Piece by piece</h2>
<p>Now will let's explain the complete code piece by piece</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"ts"</span> <span class="hljs-attr">setup</span>&gt;</span><span class="javascript">
<span class="hljs-keyword">import</span> { Cropper } <span class="hljs-keyword">from</span> <span class="hljs-string">'vue-advanced-cropper'</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'vue-advanced-cropper/dist/style.css'</span>
<span class="hljs-keyword">import</span> { ref, watch } <span class="hljs-keyword">from</span> <span class="hljs-string">'vue'</span>

<span class="hljs-comment">// Define the props</span>
defineProps({
  <span class="hljs-attr">imageSource</span>: {
    <span class="hljs-attr">type</span>: <span class="hljs-built_in">String</span>,
    <span class="hljs-attr">required</span>: <span class="hljs-literal">true</span>,
  },
  <span class="hljs-attr">imageSize</span>: {
    <span class="hljs-attr">type</span>: <span class="hljs-built_in">Object</span>,
  },
})

<span class="hljs-comment">// Create a ref to the image</span>
<span class="hljs-keyword">const</span> imageRef = ref(<span class="hljs-string">'parentImageRef'</span>)

<span class="hljs-comment">// Define the emits</span>
<span class="hljs-keyword">const</span> emit = defineEmits([<span class="hljs-string">'onImageChange'</span>, <span class="hljs-string">'onCrop'</span>, <span class="hljs-string">'onCancel'</span>])

<span class="hljs-comment">// Watch the imageRef and emit the onImageChange event when it changes</span>
watch(imageRef, <span class="hljs-function">() =&gt;</span> {
  emit(<span class="hljs-string">'onImageChange'</span>, imageRef.value)
})
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>The first part of the code imports the <code>Cropper</code> component from the <code>vue-advanced-cropper</code> library. It also imports the CSS styles for the <code>Cropper</code> component. Then, it defines the props for the <code>Cropper</code> component. There are just two props that I consider necessary in my component but there are a lot of possible props, you can explore the <a target="_blank" href="https://advanced-cropper.github.io/vue-advanced-cropper/components/cropper.html">library API</a> to define those you could add.</p>
<p>The <code>imageSource</code> prop is required and is the URL of the image that you want to crop. The <code>imageSize</code> prop is an object that specifies the width and height of the image.</p>
<p>Next, the code creates a ref to the image. This ref will be used to access the image in the template. Then, let's define the emits for the <code>Cropper</code> component.</p>
<p>The <code>onImageChange</code> event is emitted when the image changes (This will be used by the parent component to update its ref). The <code>onCrop</code> event is emitted when the crop is complete, and the <code>onCancel</code> event is emitted when the user cancels the crop.</p>
<p>Finally, the code watches the image and emits the <code>onImageChange</code> event when it changes. This ensures that the image is always up-to-date.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">template</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">Cropper</span>
      <span class="hljs-attr">ref</span>=<span class="hljs-string">"imageRef"</span>
      <span class="hljs-attr">:src</span>=<span class="hljs-string">"imageSource"</span>
      <span class="hljs-attr">:stencil-size</span>=<span class="hljs-string">"imageSize"</span>
      <span class="hljs-attr">:stencil-props</span>=<span class="hljs-string">"{
        handlers: {},
        movable: false,
        resizable: false,
      }"</span>
      <span class="hljs-attr">image-restriction</span>=<span class="hljs-string">"stencil"</span>
    /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">hr</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"solid"</span> &gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> @<span class="hljs-attr">click</span>=<span class="hljs-string">"$emit('onCancel')"</span>&gt;</span>Cancel<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> @<span class="hljs-attr">click</span>=<span class="hljs-string">"$emit('onCrop')"</span>&gt;</span>Crop image<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span>
</code></pre>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">style</span>&gt;</span><span class="css">
<span class="hljs-selector-class">.cropper</span> {
  <span class="hljs-attribute">min-height</span>: <span class="hljs-number">300px</span>;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
}
<span class="hljs-selector-tag">hr</span><span class="hljs-selector-class">.solid</span> {
  <span class="hljs-attribute">border-top</span>: <span class="hljs-number">3px</span> solid <span class="hljs-number">#bbb</span>;
}
</span><span class="hljs-tag">&lt;/<span class="hljs-name">style</span>&gt;</span>
</code></pre>
<p>The CSS styles for the <code>Cropper</code> component are very simple. They simply set the min-height and width of the <code>Cropper</code> component to 300px and 100%, respectively.</p>
<h2 id="heading-using-the-component">Using the component</h2>
<p>Once the component is created, we can use it.</p>
<p>In this example, I'm using it in a custom dialog component after a file was selected</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">BaseDialog</span> <span class="hljs-attr">v-model</span>=<span class="hljs-string">"coverDialog"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">ImageCropper</span>
        <span class="hljs-attr">:image-source</span>=<span class="hljs-string">"coverPicked"</span>
        <span class="hljs-attr">:image-size</span>=<span class="hljs-string">"{
            width: 500,
            height: 200,
        }"</span>
        @<span class="hljs-attr">on-crop</span>=<span class="hljs-string">"cropCoverImage"</span>
        @<span class="hljs-attr">on-cancel</span>=<span class="hljs-string">"closeCoverDialog"</span>
        @<span class="hljs-attr">on-image-change</span>=<span class="hljs-string">"updateCoverRef"</span>
    /&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">BaseDialog</span>&gt;</span>
</code></pre>
<p>And the result is:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1689889002834/05db6ec3-88f3-4050-b8a3-67c29f71fe5f.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This is a basic example of how to create a Cropper Vue component using TypeScript and Vue-advanced-cropper. You can use this code as a starting point to create your own Cropper component.</p>
]]></content:encoded></item><item><title><![CDATA[How to Fetch Data from an API with useEffect in React]]></title><description><![CDATA[Learn how to fetch data from APIs in your React applications using the useEffect hook. Follow best practices and avoid common pitfalls. Async data fetching]]></description><link>https://ernestoyanac.com/how-to-fetch-data-from-an-api-with-useeffect-in-react</link><guid isPermaLink="true">https://ernestoyanac.com/how-to-fetch-data-from-an-api-with-useeffect-in-react</guid><category><![CDATA[React]]></category><category><![CDATA[Frontend Development]]></category><dc:creator><![CDATA[Ernesto Yanac Huertas]]></dc:creator><pubDate>Sat, 25 Mar 2023 22:35:29 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/YiX1jsdbWhY/upload/8e3e5ecf957b08e11ef6c4a28a3f78aa.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>One of the most important features of React is its ability that allows you to add side effects to function components such as fetching data, manipulating the DOM, and subscribing to events which allows you to perform side effects in your components.</p>
<p>We will take a closer look at how to use the useEffect hook in React. We will explain what the hook is, how it works, and provide examples of its use.</p>
<h2 id="heading-syntax-of-useeffect">Syntax of <code>useEffect</code>:</h2>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ExampleComponent</span>(<span class="hljs-params"></span>) </span>{
  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-comment">// do something when component mounts or updates</span>
    <span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> {
      <span class="hljs-comment">// do something when component unmounts or updates</span>
    };
  }, [<span class="hljs-comment">/* dependency array */</span>]);

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Example Component<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p><code>useEffect</code> takes two arguments: a function that runs when the component mounts or updates, and a dependency array which specifies which variables the effect depends on. The effect function can return a cleanup function, which will run when the component unmounts or updates. The dependency array can be empty, in which case the effect runs only once when the component mounts.</p>
<h2 id="heading-examples-of-common-side-effects">Examples of common side effects</h2>
<h3 id="heading-fetching-data-from-an-api-using-useeffect">Fetching data from an API using <code>useEffect</code>:</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { useEffect, useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">DataFetchingComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [data, setData] = useState([]);
  <span class="hljs-keyword">const</span> [loading, setLoading] = useState(<span class="hljs-literal">true</span>);
  <span class="hljs-keyword">const</span> [error, setError] = useState(<span class="hljs-literal">null</span>);

  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchData</span>(<span class="hljs-params"></span>) </span>{
      <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://api.example.com/data'</span>);
        <span class="hljs-keyword">const</span> json = <span class="hljs-keyword">await</span> response.json();
        setData(json);
        setLoading(<span class="hljs-literal">false</span>);
      } <span class="hljs-keyword">catch</span> (error) {
        setError(error);
        setLoading(<span class="hljs-literal">false</span>);
      }
    }
    fetchData();
  }, []);

  <span class="hljs-keyword">if</span> (loading) {
    <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;
  }

  <span class="hljs-keyword">if</span> (error) {
    <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Error: {error.message}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;
  }

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
      {data.map(item =&gt; (
        <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{item.id}</span>&gt;</span>{item.name}<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
      ))}
    <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span></span>
  );
}
</code></pre>
<p>This example uses <code>useEffect</code> to fetch data from an API when the component mounts. The <code>useState</code> hooks are used to hold the data, loading and error states while fetching the data. The data is then displayed on the screen.</p>
<h3 id="heading-subscribing-to-a-global-event-emitter-using-useeffect">Subscribing to a global event emitter using <code>useEffect</code>:</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> EventEmitter <span class="hljs-keyword">from</span> <span class="hljs-string">'./EventEmitter'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">EventListenerComponent</span>(<span class="hljs-params"></span>) </span>{
  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> listener = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Event:'</span>, event);
    };
    EventEmitter.addListener(<span class="hljs-string">'event'</span>, listener);
    <span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> {
      EventEmitter.removeListener(<span class="hljs-string">'event'</span>, listener);
    };
  }, []);

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>EventListener Component<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p>This example uses <code>useEffect</code> to subscribe to a global event emitter when the component mounts. The cleanup function is used to unsubscribe when the component unmounts.</p>
<h3 id="heading-modifying-the-dom-using-useeffect">Modifying the DOM using <code>useEffect</code>:</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ButtonComponent</span>(<span class="hljs-params"></span>) </span>{
  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> button = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'my-button'</span>);
    <span class="hljs-keyword">const</span> handleClick = <span class="hljs-function">() =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Button clicked'</span>);
    };
    button.addEventListener(<span class="hljs-string">'click'</span>, handleClick);
    <span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> {
      button.removeEventListener(<span class="hljs-string">'click'</span>, handleClick);
    };
  }, []);

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"my-button"</span>&gt;</span>Click me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
  );
}
</code></pre>
<p>This example uses <code>useEffect</code> to add a click event listener to a button when the component mounts. The cleanup function is used to remove the event listener when the component unmounts.</p>
<h2 id="heading-dont-forget">Don't forget:</h2>
<p>Declare all dependencies in the dependency array: It's important to declare all the dependencies of a <code>useEffect</code> function in the dependency array to ensure that the function is run at the right times. If a dependency is not included in the array, the effect function may not be</p>
<p><mark>I hope after this article, you will have a better understanding of how to use the useEffect hook in your React components, be able to write more efficient and maintainable code, and have a deeper understanding of how React works.</mark></p>
]]></content:encoded></item></channel></rss>