<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Oscar Crespo Sanchez</title>
    <description>The latest articles on DEV Community by Oscar Crespo Sanchez (@imoscarcrespo).</description>
    <link>https://dev.to/imoscarcrespo</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F213514%2F800bc917-b934-42cf-a008-fddb5ce8dbd9.jpeg</url>
      <title>DEV Community: Oscar Crespo Sanchez</title>
      <link>https://dev.to/imoscarcrespo</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/imoscarcrespo"/>
    <language>en</language>
    <item>
      <title>SNS Localstack http subscription with Nestjs</title>
      <dc:creator>Oscar Crespo Sanchez</dc:creator>
      <pubDate>Mon, 22 Jan 2024 08:25:31 +0000</pubDate>
      <link>https://dev.to/imoscarcrespo/sns-localstack-http-subscription-with-nestjs-3n6b</link>
      <guid>https://dev.to/imoscarcrespo/sns-localstack-http-subscription-with-nestjs-3n6b</guid>
      <description>&lt;h2&gt;
  
  
  SNS Localstack http subscription with Nestjs
&lt;/h2&gt;

&lt;p&gt;Last week, I found myself on a mission to replicate a slice of the AWS infrastructure in my local environment. Acutting-edge microservices architecture powered by Fargate ECS, where seamless communication between services is orchestrated by SNS.&lt;/p&gt;

&lt;p&gt;Enter Localstack — your go-to tool for emulating cloud services locally. It’s the perfect match for bringing the AWS cloud experience right to your development machine.&lt;/p&gt;

&lt;p&gt;In this tutorial, I’ll guide you through the process of integrating a server in Nest.js that effortlessly communicates with Localstack SNS. Get ready to dive into the world of event-driven microservices and learn how to subscribe to events like a pro.&lt;/p&gt;

&lt;p&gt;But before we embark on this exciting journey, let’s set the stage. You’ll need to ensure a few essential resources are installed to make the most of this tutorial.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;Localstack&lt;/p&gt;

&lt;p&gt;brew install localstack/tap/localstack-cli&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Awslocal&lt;/p&gt;

&lt;p&gt;pip3 install awscli-local&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Nestjs&lt;/p&gt;

&lt;p&gt;npm i -g @nestjs/cli&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Npm &amp;gt;16&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Now that our toolbox is fully equipped, it’s time to dive into the exciting realm of server development. For the purpose of this tutorial, I’ve opted for Nest.js, a framework known for its lightning-fast setup and developer-friendly environment.&lt;/p&gt;

&lt;p&gt;Let’s kick things off by creating a new Nest.js project. Fire up your terminal and execute the following commands:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ npm i -g @nestjs/cli
$ nest new localstack-server
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In this tutorial, we won’t delve deep into the intricacies of Nest.js structure. Don’t worry, though, because if you’ve previously worked with any other backend framework, you’ll find yourself right at home.&lt;/p&gt;

&lt;p&gt;Rather than relying on all the libraries that come bundled with Nest.js by default, our focus will be on a crucial addition — the aws-sdk. This library is instrumental for confirming the SNS subscription. To install it, simply run the following command:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i -g @aws-sdk/client-sns
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now, if you’re already familiar with the magic of HTTP SNS, feel free to skip this part — you’re ahead of the game! But for those who are diving into this exciting world for the first time, let me break it down in a way that’s as friendly as a conversation over coffee.&lt;/p&gt;

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

&lt;p&gt;Take a look at the image to get a glimpse of what we’re about to build. Our server is gearing up to be a subscriber to an SNS topic, ready to catch messages as they flow through. Imagine it as setting up a personal hotline between your server and the SNS — whenever there’s a message, it rings our server’s bell!&lt;/p&gt;

&lt;p&gt;Now, here’s the scoop: before our server can start handling these incoming messages, it needs to confirm its subscription to SNS. Enter the /_sns/onEvent endpoint, a special spot where this confirmation magic happens.&lt;/p&gt;

&lt;p&gt;Let’s break down how you can configure your controller to make this seamless connection a reality.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Body, Controller, Get, Post, Req } from '@nestjs/common';
import { AppService } from './app.service';
import { Request } from 'express';

import {
  ConfirmSubscriptionCommand,
  ConfirmSubscriptionCommandOutput,
  SNSClient,
} from '@aws-sdk/client-sns';


@Controller()
export class AppController {
  private readonly snsClient: SNSClient;

  constructor(private readonly appService: AppService) {
    this.snsClient = new SNSClient({
      endpoint: process.env.SNS_ENDPOINT || 'http://127.0.0.1:4566',
      region: process.env.AWS_REGION || 'eu-west-1',
    });
  }

  @Post('_sns/onEvent')
  onEvent(@Body() message: string, @Req() req: Request): Promise&amp;lt;ConfirmSubscriptionCommandOutput&amp;gt; | boolean {
    if (req.headers['x-amz-sns-message-type'] === 'SubscriptionConfirmation') {
      const subscribeEvent: { Token: string; TopicArn: string } =
        JSON.parse(message);
      const { Token: token, TopicArn: topicArn } = subscribeEvent;
      const command = new ConfirmSubscriptionCommand({
        Token: token,
        TopicArn: topicArn,
      });

      return this.snsClient.send(command)
    } else {
      return this.appService.doSomethingOnEvent()
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Certainly! Here’s a revised version of your text:&lt;/p&gt;

&lt;p&gt;In the constructor of our controller, I’ve declared the SNS client that will be our trusty companion in communicating with the Localstack service. Below, you’ll find the endpoint I’ve crafted to handle the SNS interactions.&lt;/p&gt;

&lt;p&gt;The first line of this endpoint is like a gatekeeper, performing validations to discern whether the incoming request is for a new subscription or if it carries a vital message. If it’s a subscription request, our mission is to let Localstack know that our endpoint is not only aware but also eager to receive messages.&lt;/p&gt;

&lt;p&gt;Once subscribed, our endpoint stands ready to gracefully handle events cascading in from the topic we’ve engaged with. I’ll guide you through this event-handling process in just a bit.&lt;/p&gt;

&lt;p&gt;However, before we proceed, let’s make a quick pitstop in our main.ts file. By default, Nest.js isn't configured to receive text-format bodies. To remedy this, we need to make a small tweak.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { NestExpressApplication } from '@nestjs/platform-express';

async function bootstrap() {
  const app = await NestFactory.create&amp;lt;NestExpressApplication&amp;gt;(AppModule, {
    rawBody: true,
    cors: true,
    bufferLogs: true,
  });
  app.useBodyParser('text');
  await app.listen(3000);
}
bootstrap();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;With the majority of the code in place, we’re almost there! The final step involves adding a new, empty service in the app.service.ts file. Think of it as giving our application that last missing puzzle piece.&lt;/p&gt;

&lt;p&gt;Let’s keep the momentum going and complete the puzzle by creating this essential service.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Injectable } from '@nestjs/common';

@Injectable()
export class AppService {

  public doSomethingOnEvent(){
    return true
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Finish!! Our service is done and you can execute it with the following command.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm start
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Before we dive into setting up all the Localstack magic, let me highlight a crucial detail.&lt;/p&gt;

&lt;p&gt;By default, our Localstack service is operating on port 4566 locally. You might be wondering why, in our app.controller.ts file, we're connecting to the SNS server at &lt;a href="http://127.0.0.1:4566"&gt;http://127.0.0.1:4566&lt;/a&gt;. Well, the reason lies in the fact that Localstack is running in Docker, and this is the gateway we use to access it.&lt;/p&gt;

&lt;p&gt;Understanding this connection point will ensure smooth communication between our application and the Localstack service.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Now, let’s transition to the “infrastructure” part — and trust me, it’s super easy.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;For a seamless experience, I highly recommend opening an iTerm split into three sections. Dedicate one section to your Nest.js server, another to the Localstack server, and the third for executing Localstack commands. This way, you’ll have a clear view of each component as we bring our infrastructure to life.&lt;/p&gt;

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

&lt;p&gt;We start localstack (left section)&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;localstack start
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Create sns resources:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;Create sns topic (where we send the messages and subscribe our endpoint)&lt;/p&gt;

&lt;p&gt;awslocal sns create-topic --name app_events&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Create a subscription to our nestjs endpoint server&lt;/p&gt;

&lt;p&gt;awslocal sns subscribe --topic-arn arn:aws:sns:eu-west-1:000000000000:app_events --protocol http --notification-endpoint &lt;a href="http://host.docker.internal:3000/_sns/onEvent"&gt;http://host.docker.internal:3000/_sns/onEvent&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Let’s pause for a moment here. Notice how we’re directing our server to &lt;a href="http://host.docker.internal:3000/"&gt;http://host.docker.internal:3000&lt;/a&gt; It’s the key to seamlessly reaching our server through the Docker machine. While instinctively, you might consider pointing directly to localhost, bear in mind that it won’t work in this setup.&lt;/p&gt;

&lt;p&gt;Now, if your server is successfully subscribed, keep an eye on your Localstack window — you should catch a glimpse of something like this.&lt;/p&gt;

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

&lt;p&gt;We’re almost there! The last piece of the puzzle involves sending messages and having your server gracefully catch them.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;awslocal sns publish --topic-arn arn:aws:sns:eu-west-1:000000000000:app_events --message "hello world"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Voilà! If everything went smoothly, you’ll find a reassuring message waiting for you in your Nest.js console.&lt;/p&gt;

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

&lt;p&gt;Recreating an entire infrastructure might sound daunting, but trust me, it’s a necessary journey for your team to have a playground without relying on a dedicated DevOps team. Just last week, I found myself grappling with this challenge, and the struggle inspired me to put together this free tutorial. Most tutorials out there come with a hefty price tag, but I believe everyone should have access to this knowledge.&lt;/p&gt;

&lt;p&gt;This is my first attempt at a tutorial, and I really hope it proves helpful, or at the very least, sparks some curiosity! Feel free to reach out if you need anything — I’m here to help and learn together.&lt;/p&gt;

&lt;p&gt;Happy coding! 🚀&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Code repository:&lt;/strong&gt; &lt;a href="https://github.com/imOscarCrespo/localstack-server"&gt;https://github.com/imOscarCrespo/localstack-server&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Instagram:&lt;/strong&gt; &lt;a href="https://www.instagram.com/oscarcrespo.xyz/"&gt;oscarcrespo.xyz&lt;/a&gt;&lt;/p&gt;

</description>
      <category>devops</category>
      <category>aws</category>
      <category>docker</category>
      <category>development</category>
    </item>
    <item>
      <title>How is to study computer science in Barcelona📚</title>
      <dc:creator>Oscar Crespo Sanchez</dc:creator>
      <pubDate>Sun, 26 Jan 2020 11:27:23 +0000</pubDate>
      <link>https://dev.to/imoscarcrespo/how-is-to-study-computer-science-in-barcelona-4f23</link>
      <guid>https://dev.to/imoscarcrespo/how-is-to-study-computer-science-in-barcelona-4f23</guid>
      <description>&lt;p&gt;I'm very excited to be writing my first post on such a platform as dev.io is 🚀. Since I started my degree in computer science in Barcelona, I'd always been thinking about how would be the degree in other countries in terms of the contents we have studied. So what about open a post for listening to people's opinions.&lt;/p&gt;

&lt;p&gt;The degrees in Spain are four years (in theory, I will explain my case in another post) with sixty "credits" per year. &lt;/p&gt;

&lt;p&gt;Let's talk about the first year. We had a total of fifteen subjects of which seven are pure maths and physics and the others are related to programming and computer basics. For making you an idea of the dramatic situation about the first year, we get into the university four/five groups of seventy people. The most important and hard requirement you have to achieve to continue studying is reaching out to thirty-two credits of the sixty in the first year, what it means more than half of the subjects, if not you are out of the university. The statistics say that each first-year more than half of the people who got in don't achieve that requirement.&lt;/p&gt;

&lt;p&gt;In the second year, we do more maths algorithms and programming stuff but all related to maths, what I mean is that we don't learn as much of programming as we would like. We carry out a lot of maths theorems that we will never use as programmers. &lt;br&gt;
To conclude I would like to know your experiences as a student, the similarities you have been through and how you feel after been finishing the degree. &lt;br&gt;
Thanks for reading this post and we are in touch! 😀&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
    </item>
  </channel>
</rss>
