What should the return type be for a Typescript node express controller?

What type of return function should I use in Node Express? I have come across information suggesting that I can use either any or void. However, using void is not recommended in this case. Can anyone provide some suggestions on the best approach? Currently, I am considering using

Promise<Response<any>>
, although it requires me to disable the rule "@typescript-eslint/no-explicit-any", which I am hesitant to do.

                                                     //Here: Promise<Response<any>> 
export default async function registration(req: TreqBodyReg, res: Response) {
  try {
    const { email, password } = req.body;
    const candidate = await ModelUser.findOne({ email }) as TreqBodyReg;
    if (candidate) {
      return res.status(400).json({ message: `There is already a user with the email ${email}` });
    }
    const hashPassword = bcrypt.hashSync(password, 7);
    const user = new ModelUser({ email, password: hashPassword });
    await user.save();
    return res.status(200).json({ message: `The user with the email ${email} has been successfully registered` });
  } catch (err) {
    console.log(err);
    // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
    return res.status(400).json({ message: `An error occurred during registration: ${err}` });
  }
};

Answer №1

It's not necessary for Express to expect a return value from the middleware/routing function. Therefore, in your case where you're using an async function, Promise<void> would be appropriate:

export default async function registration(req: TreqBodyReg, res: Response): Promise<void> {

Some developers prefer to use return along with the last action they performed, just like you did here:

return res.status(400).json({ message: `There is user with email ${email}` });

According to the Express documentation, there isn't a specified return value for json, so it likely results in undefined. However, since many Express methods are chainable, it might return the Response object. In that case, you could split the lines like this:

res.status(400).json({ message: `There is user with email ${email}` });
return;

Answer №2

A different approach was taken with this code

export default async function userRegistration(req: TreqBodyReg, res: Response): Promise<Response<void>> {
  try {
    const { email, password } = req.body;
    const existingUser = await ModelUser.findOne({ email }) as TreqBodyReg;
    if (existingUser) {
      res.status(400).json({ message: `User with email ${email} already exists` });
      return;
    }
    const hashedPassword = bcrypt.hashSync(password, 7);
    const newUser = new ModelUser({ email, password: hashedPassword });
    await newUser.save();
    res.status(200).json({ message: `User with email ${email} successfully registered` });
  } catch (error) {
    console.log(error);
    // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
    res.status(400).json({ message: `Error during registration: ${error}` });
  }
};

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

Is there a way to remove the old React component when there are two instances of it still active while passing variables?

Recently, I've encountered some unusual behavior with my React component. As a newcomer to React, I have a page where users can configure toast notifications that are displayed. For this functionality, I'm utilizing the react-hot-toast package. U ...

Output Scalable Vector Graphics (SVG) content on a webpage

I need to include an SVG element in my Angular 2+ code. My goal is to provide users with the option to print the SVG element as it appears on the screen. <div class="floor-plan" id="printSectionId2" (drop)="onDrop($event)" (dragover)="onDragOver ...

Analyzing elements within an array using Angular 4

I have an array filled with various Objects such as: [ {"id":1,"host":"localhost","filesize":73,"fileage":"2018-01-26 09:26:40"}, {"id":2,"host":"localhost","filesize":21,"fileage":"2018-01-26 09:26:32"}, {...} ] These objects are displayed in the fol ...

Assigning a specific data type to an object in TypeScript using a switch case statement

I am currently developing a React Native app using TypeScript. As part of my development, I am creating a handler with a switch case structure like the one below: export const handleMessageData = (dispatch: Dispatch, messageData: FCMMessage): void => ...

Using faceapi.js with nodejs and express

I'm in the process of creating a real-time face recognition model using faceapi js with node and express. I've attempted to detect faces using the following code. https://gist.github.com/Dannybrown2710/5e30c063da936ee947d8fff474f9f57b However, ...

Inadequate data being sent to the server from Angular2 post request

Currently, I have a form field whose value I am passing to a service as this.form.value. However, when I log this.form.value on the console, I see Object { email: "zxzx", password: "zxzxx" }. Despite this, when I send the same data to the service and make ...

The XHR request fails to transmit a JSON object

Having a client-server express app, I am currently working on sending an XHR request from my frontend to the controller while passing JSON data. The code snippet from my frontend looks like this: function handle_login(){ var username_field = document. ...

Troubleshooting problems with querying in mongoose and express: A comprehensive guide

As someone who is still relatively new to dynamic routing, I am struggling with implementing it correctly. My goal is to create a function that retrieves the user's purchases from the database and exports it as a CSV file. Everything was working fine ...

Vue.js - A dynamic parent component generates content based on data passed from a renderless child component

I am currently working on developing a system for generating buttons using vue 3 and vue-class-component. The main goal is to create a flexible button generation process, where the number of buttons generated can vary (it could be just one or multiple). Us ...

Steps for displaying an ejs file following an event in loopback

I want to display an ejs file after updating certain content in the database within a loopback model js file Here is a snippet of code for reference: Inviteduser.inviteStatusConfirm = function (invitedUserId, callback) { var status = 2; Inviteduser.upse ...

Guide to automatically sending users to a subdomain depending on their IP address location

Currently, my website is built using Node Express and I have a specific requirement. I want to redirect users to different subdomains based on their current location. For example, if a user in Singapore accesses site.com, they should be redirected to sg. ...

The Angular application is not functioning properly after running npm start, even though all the necessary packages have

Encountering a perplexing issue with my Angular application. After checking out the code on my new machine, I attempted to run my existing Angular 12 project. However, despite the application running properly in the command prompt, it is not functioning as ...

Mismatched data types for function arguments

const x: Example = { toY: (y: Maple) => { return y.p; } }; interface Example { toY: (y: Pine) => void; } interface Pine { c: string; } interface Maple extends Pine { p: boolean; } Despite the warning for interface names ...

Dynamically assign values to object properties of varying data types using indexing

My goal is to dynamically update one object using another object of the same type. This object contains properties of different types: type TypeOne = 'good' | 'okay'; type TypeTwo = 'default' | 'one'; interface Opt ...

The function cannot be called on a type that does not have a callable signature. The specified type, 'number | Dispatch<SetStateAction<number>>', does not have any compatible call signatures

Currently, I am working on setting up state to be passed through context in React using hooks. However, when I attempt to use the dispatched state updater function, an error is thrown: Cannot invoke an expression whose type lacks a call signature. Type &a ...

Removing query parameters in Angular when clicking the back button

I am in need of a way to verify if my income URL follows a specific format and then open a modal to perform an action. I have achieved this using the following code: route.queryParams.subscribe(async params => { if (!isNaN(params.rt)) { c ...

Typescript not being transpiled by Webpack

As I set out to create a basic website, I opted to utilize webpack for packaging. TypeScript and SASS were my choice of tools due to their familiarity from daily use. Following the documentation at https://webpack.js.org, I encountered issues with loaders ...

Signatures overburdened, types united, and the call error of 'No overload matches'

Consider a TypeScript function that takes either a string or a Promise<string> as input and returns an answer of the same type. Here's an example: function trim(textOrPromise) { if (textOrPromise.then) { return textOrPromise.then(val ...

Is it possible for me to transfer a change to the worldwide namespace from my library?

I am looking to enhance an existing TypeScript type within the global namespace in my library and then expose it for use in other projects. Can this be done? Below is my current code: Promise.ts Promise.prototype.catchExtension = function<T>(this ...

Uploading audio mp3 files with Angular 2 and ExpressJS to the server (maximum size of 16MB)

I am embarking on a new project that will require users to upload audio MP3 files under 16MB in size, which falls within the maximum file size limit for mongoDB. I have been researching but haven't found a clear solution on how to handle this on the s ...