Utilize the express library (NodeJS, TypeScript) to send back the results of my function

I am curious about how I can handle the return values of my functions in my replies.

In this specific scenario, I am interested in returning any validator errors in my response if they exist.

Take a look at my SqlCompanyRepository.ts:

async create(company: CompanyCommand): Promise<CompanyEntity> {
    const createCompany = await dataSource.getRepository(CompanyEntity).save(company)
    await validate(company).then(errors => {
        if (errors.length > 0) {
            return errors;
        }
    });
    return createCompany
}

And here is my index.ts:

app.post("/company", async (req, res) => {
const company = new CompanyCommand()
company.id = crypto.randomUUID()
company.name = req.body.name
company.email = req.body.email
company.password = req.body.password

const checkEmail = await companyRepository.findByEmail(company.email)

if (!!checkEmail) {
    res.status(409).send("Email already exists.")
} else {
    const companyResult = await companyRepository.create(company)
    res.send(companyResult)
}
})

Answer №1

Instead of using return errors;, use throw errors;. This will cause the Promise<CompanyEntity> to be rejected with the errors message.

Next, make sure to encapsulate the function call in a try-catch block to handle this rejection:

try {
  const companyResult = await companyRepository.create(company)
  res.send(companyResult)
} catch(errors) {
  res.send(errors)
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with routing in a bundled Angular 2 project using webpack

Having a simple Angular application with two components (AppComponent and tester) webpacked into a single app.bundle.js file, I encountered an issue with routing after bundling. Despite trying various online solutions, the routing feature still does not wo ...

Is it beneficial to dockerize an AngularJS + nginx codebase?

Currently, I am working on an AngularJS front-end project that is hosted on nginx and communicates with a back-end Java server (which is not part of this codebase). Each time I need to install the package, I run the following commands: # ensure that node, ...

What are the steps to set up a MEVN project to run on an intranet using nginx?

As a newcomer to the world of Vue, Node, Express, and MongoDB API while using Nginx, I have a question about where to place the port configuration. Can anyone provide insight on this? My project consists of a "client" folder and a "server" folder, both co ...

What methods can we use to determine if the TURN or STUN server has successfully established a connection?

I rely on http://code.google.com/p/rfc5766-turn-server/ for my TURN and STUN server setup. I'm looking to develop diagnostics to determine whether the STUN or TURN servers are connected. I would greatly appreciate any assistance with: 1) Implementi ...

Utilizing Mongodb for complex query conditions

I am new to using MongoDB and express for database interactions. My goal is to query the database based on URL parameters by extracting them from the URL and adding them to an object if they exist in order to use them when querying the database. I have s ...

In what way can a Express Node app be successfully deployed with npm modules on AWS Lambda?

I am looking to host my node application on AWS Lambda, but I am facing an issue with npm packages that are not pre-installed in lambda. How can I successfully deploy my entire node app on lambda? One option is to upload the files as a zip file, but how ...

Do you have any suggestions on how to fix this npm SQLite installation issue?

Could use some help with an SQLite installation error I'm encountering. Any ideas on what the issue might be and how to resolve it? C:\Users\jacka\Downloads\discord-emoji-stealer-master\discord-emoji-stealer-master>npm i & ...

Can you explain the concept of static in Typescript?

Exploring the distinctions between the static and instance sides of classes is addressed in the Typescript documentation on this page. The static and instance sides of classes: understanding the difference In object-oriented programming languages like ...

Is there a way to bring in both a variable and a type from a single file in Typescript?

I have some interfaces and an enum being exported in my implementation file. // types/user.ts export enum LoginStatus { Initial = 0, Authorized = 1, NotAuthorized = 2, } export interface UserState { name: string; loginStatus: LoginStatus; }; ex ...

Finding a solution to the dilemma of which comes first, the chicken or the egg, when it comes to using `tsc

My folder structure consists of: dist/ src/ In the src directory, I have my .ts files and in dist, I keep my .js files. (My tsconfig.json file specifies "outDir":"dist" and includes 'src'). Please note that 'dist' is listed in my git ...

A guide on mimicking URL input and pressing ENTER in Chrome using Selenium and NodeJS

My current project involves using Selenium and NodeJS to automate download tests specifically on Chrome. Interestingly, I have observed that the download protection feature in Chrome behaves differently depending on whether a link is clicked or if the URL ...

notification triggered by a real-time database

Written below is the code responsible for triggering a change in the real-time database: const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase); expor ...

Is Npm not yet installed on your system?

After successfully downloading node.js from nodejs.org and installing it on my Windows system using gitbash, I encountered an issue while checking the versions. When I ran node -v, it displayed the version number as expected. However, upon running npm -v, ...

Express js routing issue ("Page Not Found")

Why do I receive a "Cannot GET /" message when I access my HTTP server at http://localhost:8000/? I am using Express JS for server-side routing and Angular for client-side. Some sources suggest that this error occurs because I haven't set a route for ...

The call signatures for `node-fetch -- typeof import("[...]/node-fetch/index")'` are not properly defined

Originated from this source: https://github.com/node-fetch/node-fetch#json ... my personal code: const fetch = require('node-fetch'); async function doFetch() { const response = await fetch('https://api.github.com/users/github'); ...

Creating an observer for a multiple selection dropdown in Aurelia: step by step tutorial

In my current setup, I have a dropdown menu that allows users to select a single option. This selection automatically provides me with the filtering value as an observable. Here is how it works: public months: any=[]; @observable public selectedMonth: ...

I'm having difficulty mocking a function within the Jest NodeJS module

I have a module in NodeJS where I utilize a function called existsObject to validate the existence of a file in Google Storage. While testing my application with Jest 29.1.2, I am attempting to create a Mock to prevent the actual execution of this functio ...

Is it possible to eliminate additional properties from an object using "as" in Typescript?

I am looking for a way to send an object through JSON that implements an interface, but also contains additional properties that I do not want to include. How can I filter out everything except the interface properties so that only a pure object is sent? ...

Issues with hot reloading in Express.js - GraphQL API are preventing it from functioning properly

In an attempt to create a mockAPI with hot reload functionality, I encountered an issue. Whenever I edit the schema or the data returned by the server and restart it, the changes are not reflected (I tested this using Postman). I believed that restarting ...

Instructions for utilizing executables from a package that has been installed locally in the node_modules directory

Is there a way to utilize a local version of a module in node.js? For instance, after installing coffee-script in my app: npm install coffee-script By default, this installation places coffee-script in ./node_modules, with the coffee command located at . ...