teleren/devto huggingface dataset:
NodeJS Security Middlewares
Tags: security, middleware, api, node
Published: 2024-06-11 15:20:59

## Introduction

Many backend endpoints are written in NodeJS and it is crucial for us to protect our endpoints. A quick and simple way to do so would be to use middlewares. 

## Middleware

Middlewares allow us intercept and inspect requests, which makes it ideal for logging, authentication and inspecting requests. Here are 6 security middlewares which you can embed into your NodeJS project to secure it. 

## [Helmet](https://www.npmjs.com/package/helmet)

The Helmet package sets security headers in our API responses. These headers provide important security-related instructions to the browser or client about how to handle the content and communication, thus helping to prevent various types of attacks. 

## [CORS](https://www.npmjs.com/package/cors)

The CORS package allows us to whitelist domains, controlling access to our web resources.

## [Express XSS Sanitizer](https://www.npmjs.com/package/express-xss-sanitizer)

This package sanitizes user input data to prevent Cross Site Scripting (XSS) attacks

## [Express Rate Limit](https://www.npmjs.com/package/express-rate-limit)

If your Backend Servers are not fronted with a Web Application Firewall (WAF) or protected by DDoS mitigation services, you should definitely install this package to protect your endpoints from getting spammed by setting rate limits.

## [Express Mongo Sanitizer](https://www.npmjs.com/package/express-mongo-sanitize)

This package sanitizes user-supplied data to prevent MongoDB Operator Injection.

## [HPP](https://www.npmjs.com/package/hpp)

As Express populates HTTP request parameters with the same name into an array, attackers may pollute the HTTP parameters to exploit this mechanism. 

## Sample Code on Usage

```
const express = require('express');
const app = express();

const cors = require("cors");
const helmet = require("helmet");
const { xss } = require("express-xss-sanitizer");
const rateLimit = require("express-rate-limit");
const hpp = require("hpp");
const mongoSanitize = require("express-mongo-sanitize");


// Rate limit 

// Trust the X-Forwarded-* headers
app.set("trust proxy", 2);

const IP_WHITELIST = (process.env.IP_WHITELIST || "").split(",");

const limiter = rateLimit({
  windowMs: 10 * 60 * 1000, // 10 mins
  max: 500, // Limit each IP to 500 requests per 10 mins
  standardHeaders: true, //Return rate limit info in the `RateLimit-*` headers
  legacyHeaders: false, // Disable the 'X-RateLimit-*' headers
  skip: (request, response) => IP_WHITELIST.includes(request.ip),
});

app.use(limiter);

//Sanitize data
app.use(mongoSanitize());

//Set security headers
app.use(helmet());

//Prevent XSS attacks
app.use(xss());

//Prevent http param pollution
app.use(hpp());

//CORS

const whitelist = ['http://localhost:4000']; 

const corsOptions = {
  origin: function (origin, callback) {
    if (whitelist.indexOf(origin) !== -1) {
      callback(null, true)
    } else {
      callback(new Error('Not allowed by CORS'))
    }
  }
}

app.use(cors(corsOptions));

```
CQRS Design Pattern in Spring Boot? Explain with Example
Tags: java, springboot, kafka, designpatterns
Published: 2024-06-11 15:16:34

##CQRS Design Pattern in Spring Boot
==================================

What is CQRS Design Pattern?
----------------------------

> The CQRS *(Command Query Responsibility Segregation)* design pattern separates the responsibility of handling commands (write operations) from queries (read operations) into separate components.


Example: Online Shopping Platform
---------------------------------

### Problem Statement:

An Online shopping platform where users can browse products, add them to cart, place orders, and sellers can manage product listings and process orders. All read and write operations are currently handled within a single monolithic microservice.

### Suggested Approach using CQRS:

*   **Write Microservice:** Handles commands such as creating orders, updating order status, managing product listings, etc. Utilizes Kafka for publishing events related to write operations.
*   **Read Microservice:** Handles queries such as fetching product details, order history, etc. Subscribes to events published by the Write Microservice using Kafka for eventual consistency.

### Benefits of Using CQRS:

*   Scalability: Each microservice can be scaled independently based on the workload.
*   Performance: Optimizes read and write operations separately, leading to improved performance.
*   Maintainability: Clear separation of concerns simplifies the system architecture and enhances maintainability.

### Conclusion:

Implementing CQRS with Kafka in the online shopping platform improves scalability, performance, and maintainability by segregating read and write operations into separate microservices, ensuring a more efficient and scalable system architecture.

--------------
Discover the more Java interview question for experienced developers! [YouTube Channel Link] (www.youtube.com/@codegreen_dev)
Optional Class in Java and its methods
Tags: java8, optional, util, streams
Published: 2024-06-11 15:06:18

##Optional Class in Java
======================

What is an Optional Class?
--------------------------

The Optional class in Java is a container object that may or may not contain a non-null value. It is used to avoid null pointer exceptions by providing a way to handle null values more effectively.

Available Methods in Optional Class
-----------------------------------

*   **Optional.isPresent()** - Checks if a value is present in the Optional.
*   **Optional.get()** - Gets the value from the Optional if present, otherwise throws NoSuchElementException.
*   **Optional.orElse(T other)** - Returns the value if present, otherwise returns the specified other value.
*   **Optional.orElseGet(Supplier other)** - Returns the value if present, otherwise returns the result produced by the supplying function.
*   **Optional.orElseThrow(Supplier exceptionSupplier)** - Returns the value if present, otherwise throws the exception produced by the supplying function.
*   **Optional.ifPresent(Consumer consumer)** - Executes the specified consumer if a value is present.
*   **Optional.filter(Predicate predicate)** - Filters the value of the Optional if present based on the specified predicate.
*   **Optional.map(Function mapper)** - Maps the value of the Optional if present using the specified mapper function.
*   **Optional.flatMap(Function\> mapper)** - Maps the value of the Optional if present to another Optional using the specified mapper function.

Example
-----------------

```java
import java.util.Optional;

public class OptionalExample {

    public static void main(String[] args) {
        // Example of Optional.isPresent()
        Optional<String> optionalString = Optional.ofNullable("Hello");
        System.out.println("Is value present? " + optionalString.isPresent());

        // Example of Optional.get()
        String value = optionalString.get();
        System.out.println("Value: " + value);

        // Example of Optional.orElse()
        Optional<String> emptyOptional = Optional.empty();
        String result = emptyOptional.orElse("Default Value");
        System.out.println("Result: " + result);

        // Example of Optional.ifPresent()
        optionalString.ifPresent(val -> System.out.println("Value is present: " + val));

        // Example of Optional.map()
        Optional<Integer> optionalLength = optionalString.map(String::length);
        optionalLength.ifPresent(len -> System.out.println("Length of value: " + len));
    }
}
```
            
        

Conclusion
----------

The Optional class in Java provides a set of methods to handle null values effectively, reducing the chances of null pointer exceptions and improving code readability.
My .NetFramework version does not work with my Microsoft.SharePointClient.dll version. Which version should I use?
Published: 2024-06-11 15:04:47

My .NetFramework version does not work with my Microsoft.SharePointClient.dll version.  Which version  should I use?

I am trying to add some CSOM functionality to my C# program such that I will be allowed to do CRUD operations on a Microsoft List (aka SharePoint List).  Assuming you know what CSOM and CRUD is, I will not bore you with the details of the specifics.  The end result of adding the references to the DLLS and the proper namespace, I get an error in my IDE:

> "Could not install package 'Microsoft.SharePoint.Client.dll
> 15.0.4420.1017'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.7.2', but the package does not
> contain any assembly references or content files that are compatible
> with that framework. For more information, contact the package
> author."

And so, I have two questions:

What .NetFramework version is compatible  with Microsoft.SharePoint.Client.dll 15.0.4420.1017 ?
(question 1)

What Microsoft.SharePoint.Client.dll version is compatible  with .NETFramework Version=v4.7.2 ?
(question 2)
DoubleTree Lucknow Factory
Published: 2024-06-11 15:01:02

Kuldeep Plywood Industries is an over fifty-year-old family legacy committed to delivering quality products in the plywood industrial market. Our roots date back to 1965 when Krishna Kumar Gupta started Kuldeep Sawmills – a small sawmill industry catering [local Lucknow market](https://doubletreekitchens.com/
) with their daily sawn-timber needs.
Your AWS app in depth like never before with sls-mentor
Tags: serverless, aws, javascript, tutorial
Published: 2024-06-11 15:00:36

---
published: true
title: 'Your AWS app in depth like never before with sls-mentor'
cover_image: https://raw.githubusercontent.com/pchol22/kumo-articles/master/blog-posts/sls-mentor/dashboard/assets/cover-image.png
description: 'sls-mentor is an open-source tool that generates an interactive graph of your AWS application. This graph contains all the interactions between components of your app. Recently, we also released dashboards that allow you to monitor stats like cold starts for example'
tags: serverless, AWS, javascript, tutorial
canonical_url:
---

## Your serverless app like you've never seen it before with sls-mentor

Ever dreamed of being able to visualize and analyze your entire AWS application at a glance? With the new 3.0 (alpha) of sls-mentor, it is now possible!

{% embed https://twitter.com/PierreChollet22/status/1754504552861024582 %}

sls-mentor is a **free** and **open-source** tool that generates an interactive graph of your AWS application. This graph contains all the interactions between components of your app (Lambda functions, DynamoDB tables, S3 buckets...).

sls-mentor also has a brand new feature: **Dashboards**. With dashboards, you have access to stats about your app such as :

- Lambda Cold start duration 🏎
- Lambda Bundle size 📦
- S3 bucket size 🪣
- DynamoDB table size 📊
- And more to come! ✨

![Lambda Dashboard](https://raw.githubusercontent.com/PChol22/kumo-articles/master/blog-posts/sls-mentor/dashboard/assets/lambda.png)

![Table Dashboard](https://raw.githubusercontent.com/PChol22/kumo-articles/master/blog-posts/sls-mentor/dashboard/assets/table.png)

## How to run sls-mentor?

You only need your CLI to run the new 3.0 of sls-mentor, simply use:

```sh
npx sls-mentor@alpha -p <AWS_CLI_PROFILE> -r <AWS_REGION>
```

{% cta https://github.com/sls-mentor/sls-mentor %} Star sls-mentor on Github ⭐️ {% endcta %}

sls-mentor will perform its analysis live, on the AWS Account associated with the CLI profile.

There are also filtering options: `-c` to specify cloudformation stacks, `-t` for tags

## We need you!

If you enjoyed trying sls-mentor 3.0, your feedback is valuable! Feel free to comment or to contact me on twitter

{% cta https://twitter.com/PierreChollet22 %} Contact me on twitter 🚀 {% endcta %}

We are also open to contributions!

{% cta https://github.com/sls-mentor/sls-mentor %} Contribute on Github ⭐️ {% endcta %}
Congrats to the Frontend Challenge: June Edition Winners!
Tags: devchallenge, frontendchallenge, css, javascript
Published: 2024-06-11 14:56:16

The wait is over! We are excited to announce the winners of the [Frontend Challenge: June Edition](https://dev.to/devteam/join-us-for-the-next-frontend-challenge-june-edition-3ngl).

From [sleepy Pikachu on the beach](https://dev.to/dhrutisubham03/sleepy-pikachu-4iha) to celebrating [World Bicycling Day](https://dev.to/israebenboujema/world-bicycle-day-css-art-frontend-challenge-june-edition-31oc), our DEV team of judges had a lot of fun reviewing everyone’s creative submissions, and learning about beaches around the world!

Whether you just completed your first challenge or you're on a challenge completion streak, we hope you're feeling proud of your submission and what you learned!

As always, there can only be a couple of winners.

## Congratulations To…

### CSS ART

Congrats to @tanveermahendra for wowing us with their **CSS Art**!

This submission was beautiful and touching. It stretches what can be done with CSS, and does so without sacrificing a shred of artistic integrity.

There were so many great submissions, and we felt that this one really nailed the challenge.

{% embed https://dev.to/tanveermahendra/css-art-june-was-made-for-happiness-5acm %}

### Glam Up My Markup

Congrats to @rith1x for building a beautiful, responsive website in the **Glam Up My Markup** prompt!

This submission exudes personality and professionalism and makes and creates a delightful and accessible user experience. It makes us want to visit one of these beaches!

{% embed https://dev.to/rith1x/glam-up-my-markup-beaches-4fn8 %}

***

Our two winners will receive an exclusive DEV badge and a gift from the [DEV Shop](https://shop.forem.com). All participants will receive a completion badge for rising to the challenge!


## What’s next?

Tomorrow (June 12), we’ll be launching a new partnered challenge, the [Twilio Challenge](https://dev.to/challenges/twilio), and our first-ever [Computer Science Challenge](https://dev.to/challenges/twilio). 

{% embed https://dev.to/t/twiliochallenge %}

{% embed https://dev.to/t/cschallenge %}

On June 26, we’ll be launching the [Wix Studio Challenge](https://dev.to/challenges/wix):

{% embed https://dev.to/t/wixstudiochallenge %}

Make sure to follow each challenge tag so you don’t miss the announcements!

Thank you to everyone who participated on the Frontend Challenge: June Edition! We hope you had fun, felt challenged, and maybe added a thing or two to your professional profile. See you next time!
Using Kafka in Spring Boot Application
Tags: kafka, eventdriven, springboot, java
Published: 2024-06-11 14:53:45

Kafka Consumer and Producer in Spring Boot
==========================================

1\. Dependency Required
-----------------------

You need to include the following dependency in your pom.xml or build.gradle:

```
<dependency>
    <groupId>org.springframework.kafka</groupId>
    <artifactId>spring-kafka</artifactId>
    <version>2.7.0</version>
</dependency>
```

        
Also See: {% cta https://dev.to/codegreen/setting-up-a-local-kafka-environment-on-windows-1h8c %} How to Setup Kafka Locally on Windows {% endcta %}    
        

2\. Kafka Configuration in application.properties
-------------------------------------------------

You need to configure Kafka for both Producer and Consumer in your application.properties:

```
# Kafka Producer configuration
spring.kafka.bootstrap-servers=localhost:9092
# Kafka Consumer configuration
spring.kafka.consumer.group-id=my-group
```
            
        

3\. Configuring Kafka Producer with @KafkaTemplate
--------------------------------------------------

To configure a Kafka producer, you can use the @KafkaTemplate annotation. You can serialize the message to JSON format using the JsonSerializer:

```
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.serializer.JsonSerializer;
import org.springframework.stereotype.Component;

@Component
public class MyKafkaProducer {

    @Autowired
    private KafkaTemplate<String, Object> kafkaTemplate;

    public void sendMessage(String topic, Object message) {
        kafkaTemplate.send(topic, message);
    }
}
```
            
        

4\. Configuring Kafka Consumer with @KafkaListener
--------------------------------------------------

To configure a Kafka consumer, you can use the @KafkaListener annotation. You can deserialize the message from JSON format using the JsonDeserializer:

```
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

@Component
public class MyKafkaConsumer {

    @KafkaListener(topics = "my-topic", groupId = "my-group")
    public void listen(String message) {
        System.out.println("Received Message: " + message);
    }
}
```         
        

Conclusion
----------

Spring Boot makes it easy to implement Kafka consumer and producer using the Spring Kafka library. By using annotations like @KafkaTemplate and @KafkaListener, developers can quickly set up Kafka communication in their applications.
Nimaga endi fasllar? (mapping jarayoni)
Tags: mappingreact, learningreact
Published: 2024-06-11 14:53:14

Endi sarlavhadagi rasmga birinchi o'rinda javob beramiz.Nimaga aynan fasllar.Bu biz o'rganmoqchi bo'lgan mavzu uchun ajoyib misol bo'la oladi.Chunki fasllar har doim takrorlanadi.Bahordan keyin yoz, Yozdan keyin kuz fasli, kuzdan keyin qish fasli kirib keladi.To'g'ri bu qaysidir mamlakatlarda o'zgarishi, balkim qish umuman bo'lmasligi mumkin.Lekin O'zbekistonda emas.Ho'p mavzudan cheklanmaymiz.Fasllar charxplakday aylanadi,Bu tabiat qonuni desak ham balkim adashmahgan bo'lamiz.Ha mavzudan anchayin chetashdik(lirik chekinish)Reactdagi mapping jarayoni ham aynan shunday.Takrorlanish jarayonini oldin olgan holda loopday bitta kod yozish orqali kodimizni optimillashtira olamiz.
Keling misollar ko'ra qolamiz
Datetime Module in Python
Tags: python, datascience, learning, functions
Published: 2024-06-11 14:49:39

The [datetime module in Python](https://www.almabetter.com/bytes/tutorials/python/datetime-python) provides classes for manipulating dates and times. It includes various functions and classes such as `datetime`, `date`, `time`, and `timedelta`, which allow for a wide range of operations.

1. **Date and Time Creation**: You can create objects representing dates and times. For example, `datetime.datetime.now()` returns the current date and time.

2. **Formatting and Parsing**: Dates and times can be formatted as strings using `strftime()` and parsed from strings using `strptime()`.

3. **Arithmetic Operations**: You can perform arithmetic operations on dates and times, such as adding or subtracting time intervals using `timedelta`.

4. **Time Zones**: The module also supports time zone conversion through the `pytz` library.

5. **Components Extraction**: Easily extract components like year, month, day, hour, minute, and second from `datetime` objects.

The `datetime` module is essential for handling and manipulating date and time data efficiently in Python.
NOT NULL in SQL
Tags: sql, database, datascience, learning
Published: 2024-06-11 14:45:27

The [NOT NULL in SQL](https://www.almabetter.com/bytes/tutorials/sql/not-null-in-sql) ensures that a column cannot have a NULL value. It mandates that every row must have a value for that column, preventing the insertion or updating of records with missing data in that column. This constraint is crucial for maintaining data integrity and ensuring that important fields are always populated with valid data. It can be defined during the creation of a table or added to an existing table. If an attempt is made to insert or update a row with a NULL value in a `NOT NULL` column, the database will reject the operation and return an error.
UNIQUE KEY in SQL
Tags: uniquekey, sql, database, datascience
Published: 2024-06-11 14:36:39

A [UNIQUE key in SQL](https://www.almabetter.com/bytes/tutorials/sql/unique-key-in-sql) is a constraint that ensures all values in a column or a combination of columns are unique across the table. This means no two rows can have the same value(s) in the specified column(s). Unlike the primary key, which must be unique and non-null, a table can have multiple UNIQUE keys, and they allow NULL values (although only one NULL per column if the UNIQUE constraint is applied). UNIQUE keys help maintain data integrity by preventing duplicate entries and can be defined during table creation or added later using the `ALTER TABLE` statement.
Dockerize a Nodejs Application
Tags: docker, devops, node, begginer
Published: 2024-06-11 14:32:13

I feel very embarrassed when I claim to be a backend developer without basic Docker knowledge. Doesn't it feel the same to you?

**Prerequisites**
Before I start, make sure you have the following installed:
1. **Node.js** and **npm:**.You can download and install it from the[ Node.js official website](https://nodejs.org/en).

2.**Docker:** Download and install form [Docker's Official Website.](https://www.docker.com)

![Begin Image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rq05ac1bdb60xrgcul4y.png)


### Step1: Create a Nodejs App or use my sample Nodejs App by cloning it

```
git clone https://github.com/AbhishekCS3459/Node_Docker_Demo
cd Node_Docker_Demo
npm install
```
### Step2 (Optional): Run the below command to run the application demo

```
npm run start
```

### Step3: Run the below command to build the docker image

```
docker build YOUR_IMAGE_NAME .
```
**Note:** . represents you are running the above command in the current directory where your node application exists.


### Step4: Check whether your image has build or not by running the below command
```
docker images
```
### Step5: Run the container using the following command
```
docker run -it -p 3000:3000 YOUR_IMAGE_NAME
```
**Note:** Here -it is a flag to run the container in interactive mode and -p for mapping the container port with the external port

# Container:
 A Docker container is a lightweight, standalone, executable package that includes everything needed to run a piece of software, including the code, runtime, system tools, libraries, and settings. Containers isolate the application from its environment, ensuring consistent behavior across different environments.

![Docker Container Image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s3jol8rcj1yl1rbnqp7x.png)


## Deploy the Image to Docker Hub
To share your Docker image with others, you can deploy it to Docker Hub.

### Step 1: Login to Docker Hub
First, log in to Docker Hub using the command:
```
docker login
```
You will be prompted to enter your Docker Hub username and password.

### Step 2: Tag Your Image
Tag your Docker image with your Docker Hub repository name. Replace YOUR_DOCKERHUB_USERNAME and YOUR_IMAGE_NAME with your Docker Hub username and the name of your image:
```
docker tag YOUR_IMAGE_NAME YOUR_DOCKERHUB_USERNAME/YOUR_IMAGE_NAME
```
Step 3: Push Your Image to Docker Hub
Push the tagged image to Docker Hub:
```
docker push YOUR_DOCKERHUB_USERNAME/YOUR_IMAGE_NAME
```
You can now see your image on Docker Hub and share it with others!

![Dev Image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ohosnirqr77fiko61pd9.png)

If you want to ask, ping me below.
Connect with me on Linkedin:
[linkedin/abhishekverman](https://www.linkedin.com/in/abhishekverman/).
Further Reading: **[Dockerize a Golang Application
](https://dev.to/abhishekcs3459/dockerise-a-golang-application-25lc)**
pocket rupee ledger loan App Customer Care Helpline Number 7439698803_Toll Free_7305296021✓.Call Now
Tags: javascript, beginners, programming, react
Published: 2024-06-11 14:21:01

pocket rupee ledger loan App Customer Care Helpline Number 7439698803_Toll Free_7305296021✓.Call Nowpocket rupee ledger loan App Customer Care Helpline Number 7439698803_Toll Free_7305296021✓.Call Nowpocket rupee ledger loan App Customer Care Helpline Number 7439698803_Toll Free_7305296021✓.Call Now