teleren/devto huggingface dataset:
ExpressJS: How to throw custom errors
Tags: node, express, typescript, webdev
Published: 2022-11-02 00:53:03


## The problem
- Throwing readable custom errors is one of the most critical steps in the development of web applications. The communication between services must be clear and straight to the point.

## The tool

- Express middlewares when building NodeJS applications

## The Solution:
- Build an express _middleware_ to throw custom responses error statusCode and messages

- Our example will utilize a simple API built with ExpressJS and Prisma as an ORM

// app.ts
```ts

import express, { Request, Response, NextFunction } from 'express'
import 'express-async-errors'
import { router } from './routes'
import cors from 'cors'

const app = express()
app.use(express.json())
app.use(cors())
app.use(router)

app.use((err: {err: Error, statusCode: number, message: string}, _req: Request, res: Response, _next: NextFunction) => {
  if (err.err && err.err instanceof Error) {
    return res.status(err.statusCode).json({
      message: err.message,
      status: 'error'
    })
  }
  return res.status(500).json({
    status: 'error',
    message: 'Internal server error'
  })
})

export { app }
```

 -  In addition, we can also define how our error response will be displayed to our clients. Here you can choose to show whatever you want and whatever you feel is pertinent for the client to see.

// lib/error
```ts
const builder = ({ statusCode, message }: {statusCode: number, message: string}) => {
  return {
    err: new Error(),
    statusCode,
    message
  }
}

export const error = { builder }

```

- The object error should be thrown in the following manner

// src/services/userService.ts
```ts
import { error } from '../../lib/error'
import prismaClient from '../database/client'
import { IUser } from '../types/IUser'

interface ICreateUserRequest {
  name: string
  email: string
  password: string
}
const create = async ({ name, email, password }: ICreateUserRequest): Promise<IUser> => {
  if (!email) {
    throw error.builder({ statusCode: 422, message: 'Email not provided' })
  }

  if (await prismaClient.user.findFirst({ where: { email } })) {
    throw error.builder({ statusCode: 412, message: 'Email already taken' })
  }

  const user = await prismaClient.user.create({
    data: { name, email, password }
  })

  return user
}

export const userService = {create}

```
Zero to SaaS - Product #1 BookMarksy.io
Tags: tutorial, beginners, webdev, javascript
Published: 2022-11-02 00:50:37

I use twitter almost daily. I bookmark a bunch of useful information with the intention of coming back to take notes. But I almost never do.

The reason, I think, is because there’s too much friction involved in extracting the important information. So what if I could eliminate that friction?

Enter my first project idea, BookMarksy.io. 

A Micro-SaaS app that removes the friction of getting the important information out of your twitter bookmarks.

I’ll share more details in the coming days along with a waitlist! In the mean time, feel free to join the newsletter [here](https://www.getrevue.co/profile/brandonkpbailey)
SGML e sua relação com HTML
Tags: html, sgml, webdev, braziliandevs
Published: 2022-11-02 00:39:43

Tim Berners-Lee teve um grande desafio para tornar sua ideia sobre a Web e o HTML aceita no mundo. Nessa postagem você aprenderá o porquê de tratarmos de tags quando vamos escrever em HTML. Siga comigo e não se esqueça de me seguir caso goste do conteúdo.

O SGML (Standard Generalized Markup Language) era a linguagem de marcação preferida dentro da comunidade de documentação. O SGML é uma metalinguagem que é usada como base para a criação de outras linguagens. Para a criação de tags era necessário um DTD (Document Type Definition) que criava instruções para o SGML, assim era possível definir uma gramática. Era uma linguagem muito utilizada na CERN, empresa que Berners-Lee trabalhava, logo, ele viu isso como uma vantagem, pois poderia convencer seus colegas de adotar sua ideia.

A linguagem, para Tim, havia muitos detalhes estranhos e de difícil compreensão por parte das pessoas, apesar disso, ele viu como uma boa oportunidade. Pois, ela utilizava um sistema único para a criação de instruções AKA "tags", quais eram colocar palavras entre o sinal de menor que (<) e sinal de maior que (>) `<main>Exemplo</main>` para denotar o conteúdo principal de uma página ou cabeçalho, por exemplo. Levando isso em consideração, ele decidiu criar o HTML para se parecer com o SGML. Tim só não esperava que as pessoas aprenderiam tão facilmente as tags e escreveriam seus próprios documentos em HTML.

A diferença entre o SGML e HTML é que o HTML é uma aplicação do SGML, enquanto o SGML é usada para a criação de linguagens de marcação para documentos, um metadata.

Referência
Berners-Lee, Tim, Weaving The Web, 1999
UFF, Instituto de Computação, Linguagens de Especificação
I got the Hacktoberfest 2022 badge
Tags: hacktoberfest, challenge, opensource, community
Published: 2022-11-02 00:00:31

I got the Hacktoberfest 2022 badge!

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lhpb9o48m5s01k9vpw6h.png)
Awarded for successful completion of the [2022 Hacktoberfest challenge](https://hacktoberfest.com/).
Recursion in React simplified
Tags: blog, react, recursion, 2022
Published: 2023-06-15 21:57:26

---
title: Recursion in React simplified
published: true
date: 2022-11-02 00:00:00 UTC
tags: blog,react,recursion,2022
canonical_url: https://yakov.dev/blog/recursion-in-react-simplified
---

![Endless Stairs](https://yakov.dev/assets/images/photo-1542355554783-b612ff00383c-f6bf37a59fd71d6e37efc0681a8e1567.jpg)

Recursion is a computer science practice where a function calls itself until it reaches an exit condition. Sound pretty simple, right?

I Used to struggle with recursive code; it was hard to grasp the notion of something calling (invoking) itself, and it felt too abstract. Usually, recursion is demonstrated with the Fibonacci sequence, binary search tree, or some other theoretical example, which could be tough to wrap your head around. I wondered where such practice would be helpful UI-wise. For example, a comment section where each comment can have a sub-comment which will have a sub-comment of its own, which will have a sub-comment of its own, well, you got the idea.


First, let's write our comment component without recursion: the author name the comment's content.

```jsx
const Comment = ({ author, content }) => {
  return (
    <div>
      <span>{author}: </span>
      <span>{content}</span>
    </div>
  );
};
```


Let's render a comment within a comment. It sounds pretty basic, right? We have to call the comment component inside its return statement.

```jsx
const Comment = ({ author, content, subComment }) => {
  return (
    <div className='comment'>
      <span>{author}: </span>
      <span>{content}</span>
      <Comment {…subComment} />
    </div>
  );
};
```


What is wrong with the code above? It's not working! We get an error that says "Cannot read property 'author' of null". We need the exit condition for this component. When do we want this component to stop rendering itself? If the comment object doesn't have a sub-comment would be the specific case.

We could do this in two ways:

Solution 1: if the author or content props are missing then exit:

```jsx
const Comment = ({ author, content, subComment }) => {
  if (!author || !content) return null;
  return (
    <div className='comment'>
      <span>{author}: </span>
      <span>{content}</span>
      <Comment {…subComment} />
    </div>
  );
};
```

Solution 2: if the sub-comment object is null:

```jsx
const Comment = ({ author, content, subComment }) => {
  return (
    <div className='comment'>
      <span>{author}: </span>
      <span>{content}</span>
      {subComment && <Comment {…subComment} />}
    </div>
  );
};
```


In the first solution, we call the Comment function (component). When the condition is not met, we exit it, and in the second solution, we check for the condition before calling the function.

You can play with the code here: [https://codesandbox.io/s/simple-react-recursion-ycrtbb](https://codesandbox.io/s/simple-react-recursion-ycrtbb)

Thanks for reading!
Modern housing - September release
Tags: news, community, systems, showdev
Published: 2022-11-01 23:51:41


Hi All 👋🏻

We've just released our September's programming T-shirts.

Question was: 
**Do you own a home?**

Inspirational quote
_**Home is where our story begins…**_

---
## Answer yes
![Developer, Programmer T-shirt | There is no place like home](https://images.devshirt.club/there-is-no-place-like-127.0.0.1/there-is-no-place-like-127.0.0.1.jpeg)

### Design
With answer yes we did a spin-off of a classic joke.
We aimed to capture both that cosy warm feeling of a home. Or home address if you wish, and illustrate that most of us engineers tend to build our homes in a high tech fashion with a lot of automation and gadgets.
We hope that you'll enjoy our illustration 😊

---

## Answer no
![Developer, Programmer T-shirt | inspirational quote | If you control the code you control the world](https://images.devshirt.club/world-code-control/world-code-control.jpeg)

### Design
We've tried to target junior programmers who are just starting out. We've tried to capture their enthusiasm and joy of learning new stuff. At the same time we wanted to capture and celebrate that programming skills open a lot of previously closed doors.
We hope that you'll enjoy our illustration 😊

---

Read the [full story](https://www.devshirt.club/browse-shirts/modern-housing) of this programmer tee

---

## What is devshirt.club

devshirt.club is a paid tee a month club built specifically for developers, engineers and programmers in mind. Each month you answer a question and get a tee delivered at your doorstep. 
Every one of our shirts is illustrated and we aim to provide high quality tee's.
Indie Watch 🚀 - a newsletter for indie iOS developers
Tags: xcode, appstore, iosdevelopment, apple
Published: 2022-11-01 23:22:59

[Indie Watch](http://indie.watch/) is an exclusive weekly hand-curated newsletter showcasing the best iOS, macOS, watchOS, and tvOS apps from developers worldwide.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8rrrrsslbi89opqvoxvr.png)

The mission is to highlight the accomplishments and creativity of independent developers by providing a platform for them to share their ideas, their passion projects, and their stories.

Every week, we’ll provide you with a sampling of the best new apps, profiles of up-and-coming developers, and the occasional freebie. If you’re interested in being included in the next release, send in your application!

We've been running for nearly 6 months now with over 20+ issues released. So, make sure to subscribe if you’d like to stay up to date and receive emails when new content is published!

See it here: [Indie Watch](http://indie.watch/)
My Portfolio Site Has GitHub Comments 😎
Tags: github, webdev, giscus, nextjs
Published: 2022-11-01 22:28:55

[Giscus](https://giscus.app/) is a neat open source project that lets you add Github comments to your website.

It ~~abuses~~ uses the discussions API from Github to store each message.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4grew4loxzfaspa9aybl.png)

It has a lot of configurations you can do so consider giving them a ⭐️ for building an awesome product.

If you want to see a live demo [check out my site](https://boult.me). Feel free to drop a comment or reaction but keep things civil please 🙏.

If you are interested in how it was integrated into my next.js app check out the [source code here](https://github.com/Hacksore/Hacksore/blob/master/apps/web/src/pages/guestbook/index.tsx#L24-L35).
Enable file nesting for C# razor, Xaml and blazor pages in vscode
Tags: csharp, vscode, dotnet
Published: 2022-11-01 22:26:30

1. Step 1 - Open Visual Studio Code.

2. Step 2 - go to preference

![Open Preference](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/azzb68gotz5zo2ozqdlg.png)

![VSCode Preference](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z2flrmwenv0guwjovgos.png)

3. step 3 - Search nesting

![Search nesting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ine0798e65wkorky8zpn.png)

4. step 4 - Enable file nesting 

![Enable file nesting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e0jqze65yo29gvx356ci.png)

5. step 5 - Add these patterns

![file nesting patterns](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kuoeerv4zttyel50jjgo.png)

6. Congrats you have enabled nesting for your razor and xaml code. 

![Nested files](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ne9d81ymvq5pujdtw499.png)
Team Principles
Tags: leadership, agile, productivity
Published: 2022-11-01 22:25:30

###### I am always posting provoking post on my Linkedin, and I have decided to replicate those here. [Let's socialize!](https://www.linkedin.com/in/alexsandro-souza-dev)

Technology and modern working policies empower staff with more choices of how, when and where they work. Measuring output rather than presenteeism is a shift in how we work.

Team Principles is a guide to help with this new paradigm shift. Principles cover generalities, allow adaptation to unforeseen circumstances, don't put people in a box, and enable team members to use their best judgment and be innovative.

Team Principles will help everyone in the team thinking in a way that it maximises the effectiveness of delivering software

Find below an example of team principles.

- Divide tasks fairly and square, making sure the whole team is growing.

- It is essential that the team give feedback and ask questions.

- Fast response within the team — Unblocking the team member is the priority.

- Ensure phycology safety and blamelessness. We see failures as an opportunity to improve systems and processes.

- Choose to work on improving productivity over working on a feature.

- Make sure self-initiatives get the due recognition.

- Regularly reflect on how to become more effective.

- Measure progress and productivity by the amount of value delivered.

- Continuous improvement is better than delayed perfection.

- Choose code as the primary source of documentation.

- Be proud of our work and be able to lead initiatives in the company.

- Choose simplicity over clever or complex solutions(KISS).

- Follow [Agile principles](https://dev.to/apssouza22/agile-principles-explained-with-images-2633).
5 website help developers
Tags: beginners, javascript, webdev, career
Published: 2022-11-01 22:02:19

Hi every one this time I have come with a new topic called **best website for developers**. while you read doesn't make much change try to use the website will improve your skills. let us start with front-end developer website which are free.

**1.Frontend mentor**
In this website it will improve the skills of building website in real time like every website you should log in  by GitHub or Google
_[https://www.frontendmentor.io/](url)_



**2.Codier**
This is also same a before but little different like you can view the other developers solution and task are very little and large also. 
_[https://codier.io/](url)_



**3.LeetCode**
This one you mite heard lot as a developer this one is for the Algorithms and data structures in any language you can code. It is one of the best in the practice. this one also have the subscription module.
_[https://leetcode.com/](url)_



**4.Edabit**
This one is only for the JavaScript developer. it will challenges you in the JavaScript. At starting you can start with easy. but after certain time ask for the subscription. 
_ [https://edabit.com/](url)_



**5.Edx**
This is the online learning platform some course are free where you can start programming career. My favourite one is CS50 the complete course the present at here.
_[https://www.edx.org/](url)_



This is little short. but I think help you a lot.
Thank you for your valuable time to spend on reading.
Fully expand PR status checks on GitHub
Published: 2022-11-01 21:56:23

One thing I absolutely love about working on the Web is that I can literally tweak any web page according to my preferences.

You know, I can build a browser extension that changes colors, font sizes, improves accessibility, moves boxes, removes things I don’t need, etc. I can also write my own [bookmarklet](https://www.freecodecamp.org/news/what-are-bookmarklets/) for doing the same.

This is what I did recently after patiently enduring what I consider to be an annoying limitation on the PR (Pull Request) status checks list on GitHub.

PR status checks is a list of checks that show the status of all pipeline runs related to a PR. They are usually the last section on the PR page right before the “merge” button and the comment section.

What annoys me about this list is that it can’t be fully expanded. There’s a toggle to either hide all checks or show them but the list has a set height that limits how many items can be shown at a time. And sometimes the list can be quite long. If a run fails, it becomes quite annoying to scroll up and down to find what has failed.

So I built my own bookmarklet that simply removes the height and thus the list expands fully. Needless to say, I use it all time now 😎

Here’s a video 👇

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7gplqxfqdhpl4eruyx48.gif)

In case you want to use it too, here’s the source code:

```js
javascript: (() => {
  document.querySelector(
    '.merge-status-list.js-updatable-content-preserve-scroll-position'
  ).style.maxHeight = 'none';
})();
```

Happy coding 😉
Application Hosting and Database Hosting Are Now Available at Kinsta With $20 Off Your First Month
Tags: cloud, application, php
Published: 2022-11-01 21:52:03

Big news! We have officially launched Application Hosting and Database Hosting at Kinsta- which means you can start running your projects on our new services today! 

But before we get too excited, let’s break down what’s in store for anyone using our new hosting- and give you a sneak peek at what’s to come…

**What we offer:**

**[Application Hosting](https://kinsta.com/application-hosting/):**

- Run PHP, Node.js, Python, Java, Go, Ruby, and more. Easily connect with GitHub and automate deployments from source code to the Kinsta infrastructure- and save time & money in the process. We’ll handle deployments and security, making your process faster and simpler than ever. 

**[Database Hosting](https://kinsta.com/database-hosting/):**

- MySQL, PostgreSQL, MariaDB, and Redis. Quickly create a database and set up internal connections with your application for the best performance and security, as well as create an ecosystem of apps and databases for a robust solution. No complicated setups, more time to work on projects you care about. 

**[Managed WordPress Hosting](https://kinsta.com/wordpress-hosting/?plan=visits-business1&interval=month):**

- Lightning-fast performance, courtesy of Google’s C2 machines, a global Content Delivery Network, Cloudflare-backed security, and built-in application performance monitoring, to name a few of our premium features. 

> *“The launch of Kinsta's Application Hosting and Database Hosting opens the doors to so many creative possibilities! I'm so eager to see what our clients create with it and how their creations drive our platform development further and further. And we get the privilege of building the infrastructure on the latest and best hardware and technology stacks. It doesn't get much better than that for a hosting nerd!”*  - **Jenna Recktenwald, DevOps Team Lead**

With 55,000+ users and 10 years of industry experience, we’re excited to launch this new chapter at Kinsta- and we have lots more to come! 

Try our new [Application Hosting and Database Hosting services](https://kinsta.com/plans/?plan=visits-business1&interval=month) and receive $20 off your first month! 

> *“I hope our customers will enjoy our new Application Hosting & Database Hosting services as much as we enjoyed building them.  They unlock a new chapter in Kinsta's future which we couldn't be more excited about.”* - **Kristof Dombi, Head of Development Operations at Kinsta**

Let us know what you think in the comments below!
Day 648 : Hello
Tags: hiphop, code, coding, lifelongdev
Published: 2022-11-01 21:40:24

_liner notes_:
- Professional : Researched and responded to some community questions. Had a meeting with my manager. Worked on the UI and styling for the feature I added to a demo application. Did some research on some stuff I want to use in a hackathon starting this tomorrow. Want to get some of the start up stuff out of the way so I can actually focus on the feature I want to build. Not a bad day.

- Personal : Last night, I was playing around with the SSR Web Component demo application I made. Did some refactoring based on feedback I got from someone. Researched the things I'll need to do next. I worked on a design for my next side project. Played around with a Hello World WebXR demo app from AFrame. I think I'm going to use it in my hackathon project.

![A stream in a very lush forest with a waterfall in Dolni Sokolovec, Czech Republic](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lykbn8lofshpje41vt06.png)

Going to work some more on the WebXR demo project. I want to get a good basic understanding of Aframe so it's not too much of a blocker when I am actually working on the functionality I want to create during the hackathon. There's one part that looks like it may be difficult to make happen given what's there now. We'll see.

Have a great night!

peace piece
Dwane / conshus
https://dwane.io / https://HIPHOPandCODE.com
{% youtube 6jBhlyyB30o %}
Aprenda map() e filter() de uma vez — Javascript
Tags: javascript, beginners, programming
Published: 2022-11-01 21:34:09

Map e filter são dois entre alguns métodos na linguagem JavaScript que nos auxilia na manipulação do array. Acredite! Você aprendendo esses dois, conseguirá acelerar boa parte de iterações com array em seu projeto que estão por vir.

![Photo by freepik](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6iyd6kaa092zu4gstz5g.jpg)

## Map

A utilização do map vai permitir que você faça a operação com o array, passando a função Callback como argumento e será executada em cada um dos elementos desse array, e como resultado, devolve um novo array com os novos elementos.

Vamos de exemplo pra facilitar o seu entendimento!

Imagine que você está querendo fazer operações bem simples em cada elemento do array manualmente. Imagina com 10 objetos, 100 objetos, 1000 objetos, etc. Fazer manualmente acho que não seja uma boa ideia, ein? Você pode utilizar o método Map() justamente para isso.

```js
let numerosQualquer = [10, 5, 1]

const pegarValorComMap = numerosQualquer.map(function(valor) {
return valor * 2

})

// saída: [ 20, 10, 2 ]
```
_Por que a saída é [20, 10, 2]?_

O valor da função vai passar multiplicando por 2 cada elemento do array ao qual chamamos de numeroQualquer.

## Filter
O filter é um método bem utilizado para retornar ou filtrar informações que você deseja em um array, e assim feito, retornará um novo array com os novos elementos.

```js
let pegarNumerosAleatorios = [-443, 20, -37, 12, -5, 2, 4, 25, -30, 30, 10, -50];

let apenasNumerosPositivos = pegarNumerosAleatorios.filter(valor => valor >= 0);

// saída: [ 20,12,2,4,25,30,10 ]
```
_Por que a saída é [ 20, 12, 2, 4, 25, 30, 10]?_

Porque o valor da função vai passar por todos os elementos do array chamado pegarNumerosAleatorios, pegando/filtrando todos os valores acima ou igual 0.

---
Gostou? Comenta abaixo 👇 o que achou!