Failure to assign constant value

Asked

Viewed 60 times

-2

I’m trying to create a function to register users, but has a constant that is not assigning the value of the request, follow the code I currently have:

Services

async create(req, res) {
    const user = req.body
    user.id8 = parseInt(user.id8)
    //Search for the passed 8ID in database
    const userID = await User.findOne({ id8: user.id8 })
    //Search for the passed Email in database
    const userMail = await User.findOne({ email: user.email })
    //8ID not exists in database
    if (!userID) {
        //Email not exists in databse
        if (!userMail) {
            User.create(user)
                .then(() => {
                    return res.status(201)
                })
                .catch((err) => {
                    return res.status(500).json({ error: "Internal error: ", err })
                })
        } else {
            return res.status(409).json({ error: `Email já cadastrado no sistema` })
        }
    } else {
        return res.status(409).json({ error: `8ID ja cadastrado no sistema` })
    }
},

Controller

async create(req, res) {
    const user = req.body

    if (userVal.isValid(user)) {
        const userCreate = await userServ.create(user)
        userCreate.status === 200
            ? res.status(200)
            : res.status(400).json({ error: "Os dados passados são inválidos" })
    } else {
        return res.status().json({ error: "Dados inválidos" })
    }
},

To const user in the controller contains an object with the information entered in the user register, such as name, password, email and 8ID (it is not a primary key but is unique).

After validation of the data type, they are sent to a function create no services. The object is received in the services request, but when trying to assign the object to a new one const user, the same does not happen, user remains as undefined.

I tried to use let and other names for the variable in the service but continued with the same error. I have already searched by debug the information received in the request of services and the object is entirely there, but the const does not assign this value.

  • 1

    Do not post code as image. That said. It wouldn’t be const { user } = req.body;? You can’t tell based on shared code

  • I put as image because a part was cutting in the formatting. So, the user is not a field of the request, this request comes with username, email, password, shift and position, which are mandatory data to register the user

  • pq create a constant of a value that can change each time the function is invoked? I guess I didn’t quite understand the concept of const, use a common variable instead

  • The value will not change, I am storing the data in the constant to query data of the object passed in the rest of the function scope

  • I think I get it now. You’re calling the Service at userServ.create(user)? If yes, you are passing a single argument (user) and is trying to get two (req, res). When trying to access req.body, you’re trying to access user.body, that is undefined.

  • Exactly, I tested in the Vscode debug and the data is circulating well in the controller, the user until there is as an object containing the data passed, when I send pro services through the userServ.create(user), i see that in the service request the req contains the data of the object passed, but when trying to assign this object of the request to new const user, he does not receive this data

  • It’s because of what I said... You expect to receive req, res but pass user. Or do userServ.create(user) expecting to receive user, or do userServ.create(req, res).

  • I understand, and how can I return the status in this case?

  • That is another more complex question that cannot be answered here. I recommend that you search for "Node express Architecture" on Google and things like that to better understand what the possibilities are and have a north.

  • Got it, but thanks for the help @Rafaeltavares, I was msm stuck in that part

Show 5 more comments

1 answer

0


Man, I’d do it like this:

Controller:

async create(req, res) {
    const user = req.body

    if (!userVal.isValid(user)) {
        return res.status(400).json({ message: "Dados inválidos" });
    }

    
    const userCreated = await userServ.create(user);

    if (!userCreated.success) {
        return res.status(400).json({ message: userCreated.message });
    }

    return res.status(200).json({ message: userCreated.message });
}

Service:

async create(user) {
    const id8 = parseInt(user.id8);
    const userID = await User.findOne({ id8 });

    if (userID) {
        return { success: false, message: "8ID ja cadastrado no sistema" };
    }

    const userMail = await User.findOne({ email: user.email });


    if (userMail) {
        return { success: false, message: "Email já cadastrado no sistema" };
    }

    await User.create(user);

    return { success: true, message: "Usuário cadastrado com sucesso" };
},
  • 1

    I tested and worked perfectly, I did not know I could make a Return so no services, mt thanks for the help

  • good, good to know it worked right. Good luck!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.