Context of the this property in Typescript + Node

Asked

Viewed 77 times

0

I have an XPTO class with the methods below, in the login method I try to call the answer treatment method, however, the this is Undefined in the context of the function, as far as I could understand I would have to use the function .bind(), but how would I do that if my response treatment function receives parameters?

Of course, I could do everything in one function only (I tested and worked), but then the function would be too big, I’ve read this question, but it was not clear.

Code of the two functions:

import AutenticacaoDAO from '../daos/autenticacao.dao'
import MailController from './email.controller'
import jwt from 'jsonwebtoken'
import TokenSecret from '../config/token-secret'
import crypto from 'crypto'
import { Request, Response } from 'express'
import { Usuario } from '../models/usuario.model';

class AutenticacaoController {
    constructor() {

    }  

    public async login(req: Request, res: Response) {
        let usuario;
        try {
            usuario = await AutenticacaoDAO.login(req.body)
            this.tratarResposta(crypto.createHash("md5").update(req.body.senha).digest("hex"), usuario, res)  //this está undefined           
        } catch (error) {
            res.json(error)
        }
    }

    private tratarResposta(senhaEnviada: any, usuario: any, res: Response){ //função que eu quero chamar
        if (usuario && usuario.length > 0 && senhaEnviada === usuario[0].usuario.senha && !usuario[0].usuario.bloqueado) {
            res.json({
                usuario: usuario,
                token: jwt.sign({ usuario: usuario[0] }, TokenSecret, { expiresIn: '7d' })
            })
        } else if (usuario && usuario.length > 0 && senhaEnviada !== usuario[0].usuario.senha) {
            res.status(403).json({
                mensagem: `Não foi possível efetuar o login, sua senha está incorreta.`, erro: res.statusCode
            })
        }
        else if (usuario && usuario.length > 0 && usuario[0].usuario.bloqueado) {
            res.status(403).json({
                mensagem: `Não foi possível efetuar o login, seu usuário encontra-se bloqueado. Converse com seu gestor.`, erro: res.statusCode
            })
        }
        else {
            res.status(404).json({
                mensagem: `Não foi possível efetuar o login: Usuario não encontrado.`, erro: res.statusCode
            })
        }
    }

}

export default new AutenticacaoController()
  • These methods are part of a class?

  • Yes, I’ll put the whole class, I think it looks better.

  • @luizfelipe, I put the whole class.

1 answer

1


When you are going to log in elsewhere, this.treatRespose will be referenced to that other place, not that class. Strange no? But JS is like that. haha

For that, inside the builder, put: this.login = this.login.bind(this)

This will make this.treatThis is a reference to this.treatThis is an Authenocontroller, not the class he will be calling. Whenever you use Undefined, you need to make a bind, and the best place for that is in the constructor.

I didn’t get to do code tests, but I believe that’s it. If it doesn’t work, create an online code (in codepen or elsewhere) simulating exactly how you are doing there.

Browser other questions tagged

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