teleren/devto huggingface dataset:
Swagger + Node.js (Express) : A Step-by-Step Guide
Tags: javascript, node, beginners, programming
Published: 2024-07-03 14:30:19

Following the post on configuring Swagger for a SpringBoot project, today I will introduce you to a step-by-step guide to set up Swagger in a Node.js (Express) project.

## 1. Set Up Your Project

First, create a new Node.js project if you don't have one already.

```bash
mkdir swagger-demo
cd swagger-demo
npm init -y
npm install express swagger-ui-express swagger-jsdoc

```

## 2. Create Your Express Server
Create an index.js file (or app.js, depending on your preference):

```bash
touch index.js
```

```javascript
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerJsDoc = require('swagger-jsdoc');

const app = express();
const port = process.env.PORT || 3000;

// Swagger setup
const swaggerOptions = {
  swaggerDefinition: {
    myapi: '3.0.0',
    info: {
      title: 'My API',
      version: '1.0.0',
      description: 'API documentation',
    },
    servers: [
      {
        url: 'http://localhost:3000',
      },
    ],
  },
  apis: ['./routes/*.js'], // files containing annotations as above
};

const swaggerDocs = swaggerJsDoc(swaggerOptions);
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocs));

// Sample route
app.get('/api/hello', (req, res) => {
  res.send('Hello World!');
});

app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});

```

## 3. Document Your Routes
Create a routes folder and add a hello.js file to it (or any route file):

```bash
mkdir routes
cd routes
touch hello.js
```

Then, add the following code to `hello.js`:

```javascript
/**
 * @swagger
 * /api/user:
 *   get:
 *     summary: Retrieve a list of users
 *     responses:
 *       200:
 *         description: A list of users
 *         content:
 *           application/json:
 *             schema:
 *               type: array
 *               items:
 *                 type: object
 *                 properties:
 *                   id:
 *                     type: integer
 *                     example: 1
 *                   name:
 *                     type: string
 *                     example: John Doe
 */
app.get('/api/user', (req, res) => {
  res.json([{ id: 1, name: 'John Doe' }]);
});
```

## 4. Run Your Server

Start your server:

```
node index.js

```

## 5. Access Swagger UI

Open your browser and navigate to http://localhost:3000/api-docs. You should see the Swagger UI with your documented API.


![Swagger-javascript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qstxe6yfvs2h5agxenj9.png)


Following these steps, you can configure Swagger for your JavaScript project, providing interactive API documentation for your development team and end-users.

Thank you for reading! See you in the next post.

[Swagger + SpringBoot Project](https://dev.to/cuongnp/supercharge-your-spring-boot-application-with-swagger-a-step-by-step-guide-to-interactive-api-documentation-18g7)
JS Builders Meetup – Learn the PubSub Design Pattern for JavaScript!
Tags: javascript, meetup, webdev, programming
Published: 2024-07-03 14:30:00

**Hey Dev.to Community! 👋**

On July 3rd we had our monthly virtual gathering for JavaScript enthusiasts and web developers looking to expand their knowledge and connect with the community.


**Guest Speaker:** Vitor Norton, Developer Advocate at Superviz

**In this session, Vitor Norton will be teaching us about the Publisher/Subscriber (PubSub) Design Pattern. This pattern is essential for projects involving real-time collaboration and is a common topic in technical job interviews.**


{%embed https://youtube.com/live/U54Aj1c9WDo %}

---

Thanks for watching!
Error Handling (How to create Custom Error Handlers and Exceptions) - FastAPI Beyond CRUD (Part 16)
Tags: fastapi, python, api, programming
Published: 2024-07-03 14:26:36


This video explores error handling in FastAPI, focusing on customizing exception raising and tailoring error responses to meet our application's specific requirements. We cover creating custom exception classes and utilizing them effectively to manage errors and personalize their presentation according to the application's needs.
{%youtube jYbNq6QAQNI%}
Step-by-Step Guide: Estimated Reading Time in Bear Blog
Tags: bear, blog, reading, development
Published: 2024-07-03 14:20:56

---
title: Step-by-Step Guide: Estimated Reading Time in Bear Blog
published: true
description: Learn how to display the estimated reading time for your Bear blog posts using a simple script. Adjust placement and reading speed easily.
tags: Bear, Blog, Reading, Development
cover_image: https://bear-images.sfo2.cdn.digitaloceanspaces.com/yordi-1720013282.webp
# Use a ratio of 100:42 for best results.
# published_at: 2024-07-03 14:19 +0000
---

I'll be very short for those who just clicked this title and want results.

To show the estimated number of minutes it takes to read a blog post, add the following script to the footer directive of your Bear blog:

```javascript
<script src="https://cdn.jsdelivr.net/gh/froodooo/bear-plugins@0.0.26/bear/reading-time.js" />
```

This shows the estimated reading time just below the post date, using 255 words per minute as an average reading speed. The placement and reading speed can be changed by adding the following data attributes to the script:
- `data-before-child`: \[number\] (*defaults to 4*)
- `data-wpm`: \[number\] (*defaults to 255*)

For example, to put the estimated reading time above the post date and set an average reading speed of 200 words per minute, use the following script:

```javascript
<script src="https://cdn.jsdelivr.net/gh/froodooo/bear-plugins@0.0.26/bear/reading-time.js" data-before-child="3" data-wpm="200"/>
```

There you go, enjoy!

# The code
For those who are interested, this is the full script that called in the custom footer directive of a Bear blog:

```javascript
if (document.querySelector("body").classList.contains("post")) {
  const readingTime = Math.ceil(document.querySelector("main").innerText.trim().split(/\s+/).length / parseInt(document.currentScript.getAttribute("data-wpm") ?? 255));
  document
    .querySelector("main")
    .insertBefore(
      document.body.appendChild(
        Object.assign(
          document.createElement("p"), {
          className: "reading-time",
          innerHTML: `Reading time: ${readingTime} minute${readingTime > 1 ? "s" : ""}`
        })),
      document.querySelector("main").childNodes[parseInt(document.currentScript.getAttribute("data-before-child") ?? 4)]);
}
```

The first line makes sure that this code is only executed on blog post pages. Then, the average reading time in minutes is calculated by counting the words in the blog post (by splitting on the whitespace between words). The resulting value is rounded up. Then finally, a new paragraph is inserted on the page as a child of the tag with id `main`. A ternary operation makes sure that there is no "s" behind the word "minute" if the reading time is equal to 1 minute.
AWS Prefix Lists help simplify Networking
Tags: aws, networking, vpc, cloud
Published: 2024-07-03 14:15:56

I’ve been working with a client that acquired another company, and has multiple office sites, data centres, and a fair number of private networks. As part of the acquisition, they’ve been working on integrating the systems of the parent and the acquired company, and one element of that has been simplifying the IP address management by removing overlaps between private networks, including AWS VPCs.

As a result, I’ve been working on setting up some new VPCs, and connecting them into the corporate network. While setting this up I discovered that [customer-managed prefix lists on AWS](https://docs.aws.amazon.com/vpc/latest/userguide/working-with-managed-prefix-lists.html) can really simplify some use cases.

By way of example, imagine a networking situation like this:

![Example Network](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b6r7tp4f2qq8vny2trom.png)

With multiple customer networks and multiple VPCs, you can quickly end up needing to add a lot of CIDR blocks to a lot of places, particularly if you only want to target specific ranges, rather than a broad block (like 10.0.0.0/8).  Using specific examples, you might need to:
* add several CIDR ranges to each VPC’s route table to route the traffic to the transit gateway
* add several CIDR ranges to one or more ports in one or more security groups in each VPC in order to allow access from customer networks

If the organization adds another site or another CIDR block to an existing site, you might have to go back and find all the places you added those CIDR blocks to, and add it again. This can quickly get tedious.

This is particularly important if you’re making these changes by hand in the AWS console, either because you don’t have infrastructure setup automated or perhaps because you’re making an exploratory change ahead before changing your infrastructure automation, but even if your infrastructure is fully automated with Terraform, CloudFormation, CDK or Pulumi, you might find that a prefix list makes a security group easier to read.  

For instance, this security group that allows ICMP, HTTP and HTTPS from a prefix list:

![Security Group with Prefix List](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/90l2diysmtwvgmh6ix1b.png)

And this one allows it from the CIDR ranges in the diagram above:

![Security Group with CIDRs](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/20qhas0ynjrxxk3oa6ur.png)

I know which of these I find easier to visually inspect. 

So if you’re managing complicated networking on AWS and you haven’t taken a look at prefix lists, I hope I’ve convinced you that it’s time to take a look.
Level Up Your GitHub Repo Config Game
Tags: github, opensource, security, cloudnative
Published: 2024-07-03 14:11:32

_Stop with Spreasheets & Start Automating!_

If you’re like many open source project maintainers, your project might span tens or hundreds of GitHub repos, and your repo configuration may be wildly variable. How do you make sure that your repos always have a standard configuration in place, like a code of conduct, a security.md file, a license file, secret scanning, and Dependabot? It’s a lot for maintainers to remember and continuously monitor. Fortunately, you don’t have to — there are tools available to help.

In this video, Stacklok engineer and Knative maintainer Evan Anderson covers the breadth of free and open source tools available to help you keep your GitHub repos (and Actions) consistently configured and secure for your end users.  

{% embed https://youtu.be/wdw69jix8Eo %}


[Learn more about Minder](https://stacklok.com/minder) or [Get started with Minder today](cloud.stacklok.com)
Scop in Javascript with example
Tags: webdev, javascript, beginners, tutorial
Published: 2024-07-03 14:10:53

Scope in JavaScript refers to the visibility and accessibility of variables, functions, and objects in different parts of your code. JavaScript has three main types of scope:

1. Global scope
2. Function scope
3. Block scope (introduced in ES6 with let and const)

Here's an example demonstrating these scopes:

```javascript
// Global scope
let globalVar = "I'm global";

function exampleFunction() {
  // Function scope
  let functionVar = "I'm function-scoped";
  
  if (true) {
    // Block scope
    let blockVar = "I'm block-scoped";
    var functionScopedVar = "I'm function-scoped too";
    
    console.log(globalVar);  // Accessible
    console.log(functionVar);  // Accessible
    console.log(blockVar);  // Accessible
    console.log(functionScopedVar);  // Accessible
  }
  
  console.log(globalVar);  // Accessible
  console.log(functionVar);  // Accessible
  console.log(functionScopedVar);  // Accessible
  // console.log(blockVar);  // Error: blockVar is not defined
}

exampleFunction();

console.log(globalVar);  // Accessible
// console.log(functionVar);  // Error: functionVar is not defined
// console.log(blockVar);  // Error: blockVar is not defined
// console.log(functionScopedVar);  // Error: functionScopedVar is not defined
```
Connect MongoDB database with Next JS App(the simplest way)
Tags: mongodbwithnext, mongodbnext, nextjs, mongodb
Published: 2024-07-03 14:10:24

## 
In Next.js, especially when deploying on serverless environments or edge networks, database connections are established on every request. 

This is due to the nature of serverless functions, which do not maintain state between requests and can be spun up or down as needed. Here are some key points to consider:

**Serverless Functions:**

 Next.js uses serverless functions for API routes and server-side rendering (SSR). 
Each invocation of a serverless function is stateless and isolated, meaning it doesn't maintain a persistent connection to a database. 

Therefore, a new database connection must be established for each request.


```
import mongoose from "mongoose";

// Object to track connection state
type ConnectionObject = {
    isConnected?: number;
};

// Single connection object to be used across requests
const connection: ConnectionObject = {};

// Function to connect to the database
async function dbConnect(): Promise<void> {
    // Check if already connected to avoid redundant connections
    if (connection.isConnected) {
        console.log("Already Connected");
        return;
    }

    try {
        // Establish a new connection
        const db = await mongoose.connect(process.env.MONGO_URI || "", {
            // Use appropriate options here based on your setup
        });

        // Track the connection state
        connection.isConnected = db.connections[0].readyState;

        console.log("DB is connected");
    } catch (error) {
        console.log("DB connection error:", error);
        process.exit(1); // Exit the process if unable to connect
    }
}

export default dbConnect;

```
Thank You Me Latter
how to create new permission groups, permission category
Tags: odoo
Published: 2024-07-03 14:10:08

How to update and control permissions of an app and/or menu items using xml 

1. first of all we need to override - ir_module_category_data.xml
2. locate the menu items we need to hide/show based on permissions 
3. create the new permissions grroups, if it requires, under new category 

full code below 

```

<?xml version="1.0" encoding="utf-8"?>
<odoo>
    <data>
        <record model="ir.module.category" id="category_custompermission">
            <field name="name">The E-Cig Store Permissions</field>
            <field name="sequence">70</field>
            <field name="visible" eval="1" />
        </record>

        <record id="group_ecig_view_contacts_app" model="res.groups">
            <field name="name">View Contacts App</field>
            <field name="category_id" ref="custom_module_name.category_custompermission"/>
        </record>
        <record id="group_ecig_view_employees_app" model="res.groups">
            <field name="name">View Employees App</field>
            <field name="category_id" ref="custom_module_name.category_custompermission"/>
        </record>
        <record id="group_ecig_view_pos_app" model="res.groups">
            <field name="name">View POS Ribbon</field>
            <field name="category_id" ref="custom_module_name.category_custompermission"/>
        </record>

        <record id="contacts.menu_contacts" model="ir.ui.menu">
            <field name="groups_id" eval="[(5,0),(4, ref('custom_module_name.group_ecig_view_contacts_app'))]"/>
        </record>

        <record id="hr.menu_hr_root" model="ir.ui.menu">
            <field name="groups_id" eval="[(5,0),(4, ref('custom_module_name.group_ecig_view_employees_app'))]"/>
        </record>

        <record id="point_of_sale.pos_config_menu_catalog" model="ir.ui.menu">
            <field name="groups_id" eval="[(5,0),(4, ref('custom_module_name.group_ecig_view_pos_app'))]"/>
        </record>
        <record id="point_of_sale.menu_point_of_sale" model="ir.ui.menu">
            <field name="groups_id" eval="[(5,0),(4, ref('custom_module_name.group_ecig_view_pos_app'))]"/>
        </record>

        


    </data>
</odoo>
```
Top 10 ES6 Features that Every Developer Should know
Tags: javascript, typescript, webdev, programming
Published: 2024-07-03 14:08:59

## Top 10 ES6 Features that Every Developer Should know

**1. let and const:
**Block-scoped variable declarations. 'let' allows reassignment, 'const' doesn't. Prevents hoisting issues and unintended global variables. Improves code predictability and encourages better practices for variable scope and mutability.

**2. Arrow Functions:
**Concise syntax for function expressions. Lexically binds 'this', solving context issues in callbacks. Can't be used as constructors or methods needing their own 'this' binding. Simplifies code and reduces 'this'-related errors.

**3. Template Literals:
**Uses backticks for strings. Allows multi-line strings and interpolation with ${expression}. Improves readability when constructing complex strings or HTML templates. Supports tagged templates for custom string processing.

**4. Destructuring Assignment:
**Extracts values from arrays or object properties into distinct variables concisely. Useful for handling function returns, import statements, and complex data structures. Enhances code readability and reduces lines of code.

**5. Enhanced Object Literals:
**Shorthand syntax for defining object methods and properties. Allows computed property names. Simplifies object creation, especially when property names match variable names. Makes object definitions more concise and readable.

**6. Default Parameters:
**Allows setting default values for function parameters. Reduces need for manual parameter checks. Improves function flexibility and readability. Default values are used when arguments are undefined.

**7. Rest and Spread Operators:
**Rest (...) collects multiple elements into an array. Spread (...) expands arrays or objects. Useful in function arguments, array manipulation, and object composition. Simplifies working with arrays and function parameters.

**8. Promises:
**Represents asynchronous operations. Provides cleaner alternative to callbacks. Has states: pending, fulfilled, or rejected. Includes methods like then() and catch() for handling outcomes. Improves asynchronous code structure and error handling.

**9. Classes:
**Syntactical sugar over prototype-based inheritance. Provides familiar syntax for object-oriented programming. Includes constructors, methods, and inheritance. Doesn't change JavaScript's prototype-based nature but improves code organization and readability.

**10. Modules:
**Allows code organization into separate files. Uses import and export statements. Supports default and named exports. Improves code maintainability, reusability, and helps manage dependencies. Replaces older module patterns like CommonJS.
AI's Impact on Future Business: Transformation Across Industries and for IT Professionals 🌐
Tags: ai, it, automation
Published: 2024-07-03 14:01:40

Artificial Intelligence is already rewriting the rules of the business world, providing companies with new opportunities for innovation and growth. In the IT industry, understanding how AI is changing not only technological approaches but also business processes is crucial.

🔍 **Data Transparency and Business Analytics**: AI enables extracting valuable insights from large volumes of data, significantly improving the quality of business analysis and decision-making.

🤖 **Automation and Process Optimization**: AI-driven automation speeds up task execution, reduces costs, and enhances operational efficiency, which is particularly vital for IT professionals involved in developing and implementing new technologies.

🌐 **Personalized Customer Experience**: With AI, companies can offer more personalized services and products, enhancing user experience and strengthening customer loyalty.

🔒 **Cybersecurity and Data Protection**: AI plays a critical role in securing data, detecting threats, and preventing cyber-attacks, essential for maintaining customer trust and protecting corporate assets.

🔮 **Future Innovations and Research**: The development prospects of AI include new technologies and methods that will continue to transform business models and create new opportunities for IT professionals.

Artificial Intelligence is not just a tool but a key component for creating competitive advantages in the future business landscape. Understanding its potential and applying it in every aspect of work will enable companies and IT professionals to effectively adapt to the challenges of the new digital era.
Lazy Imports in Java?🙂‍↔️
Tags: java, coding, tutorial, learning
Published: 2024-07-03 13:51:14

I am an experienced Python user, and I love how everything is built-in. One feature I use daily is lazy imports. Recently, I was working with Java and wanted to do something similar. Although I couldn't find any good articles on the topic, I managed to figure it out. Here is a sample implementation based on the bcrypt library use case.

Before using lazy import, I would import the function at the top and use it later in the function.


```
import at.favre.lib.crypto.bcrypt.BCrypt;  

// Using it somewhere in the program
String password = “Test@123”
String storedHashString = "$2RandomHashString”
isValid = BCrypt.verifyer().verify(password.toCharArray(), storedHashString.toCharArray()).verified
```

Above, you can see example code where I am using the Bcrypt library's functions to verify a password. However, I wanted to import Bcrypt lazily. Here is what I did:

```
// Directly wrote this where I wanted to use this function.
Class<?> bCryptClass = Class.forName("at.favre.lib.crypto.bcrypt.BCrypt"); // Get the instance of the class
Method verifyerMethod = bCryptClass.getMethod("verifyer"); //Get the method  from class.
Object verifyer = verifyerMethod.invoke(null); // Invoke verifyer method and store instance in the variable.
Method verifyMethod = verifyer.getClass().getMethod("verify", char[].class, char[].class);
Object result = verifyMethod.invoke(verifyer, password.toCharArray(), storedHashString.toCharArray()); // Final invoke the verify method.
Boolean ans = (Boolean) result.getClass().getField("verified").get(result); // get the verified field.
```

Few things to notice here:

- I didn’t import the Bcrypt library at the top.
- It will be imported at runtime. If the jar file is not present, it will throw a ClassNotFoundException. So, add a try-catch block if needed.
- My goal was to achieve this because, in my case, the library might or might not exist in the environment.

Let me know if you have a better way to do this. I hope you find it helpful.
P.S. I'm a noob at Java, so don't quote me on this :P