How to allow a method to execute another method of the same Typescript class?

Asked

Viewed 56 times

0

I am working with a class that manages the registration and login of new users. Imagine that this class has two methods, the first isCharacterNameRegistered() checks if the nick already exists, and returns a boolean. The second registerNewCharacter() is responsible for making the registration, and before performing it, she also checks if the name (which can not be repeated) has already been registered. Not to repeat the same code, I thought it would be interesting to call the function isCharacterRegistered() inside registerNewCharacter() to allow or not to continue the registration. Here is the class in question:

class AuthManager {
    async isCharacterNameRegistered(characterName: string) { 
        /* verifica se o nome de personagem já é registrado, retorna true em caso afirmativo e false em caso negativo */

        const characterAlreadyRegistered = await Character.findOne({characterName})
        return !!characterAlreadyRegistered 
    }

    async registerNewCharacter(req: Request, res: Response) {
        const character = req.body

        if(this.isCharacterNameRegistered(character.characterName)) {
            return res.json({
                status: 'Erro Benigno',
                message: 'Já existe um personagem com esse nome',
                error: null
            })
        } 
    }
}

And we have a mistake, because the this inside registerNewCharacter() refers to the scope of the function in which it is evoked, not that of the class AuthManager, right? apart from the this Typescript does not compile, saying it cannot find isCharacterNameRegistered and suggests that we use the this, but as we’ve seen it doesn’t work!

What am I doing wrong? Is it possible to call one function directly within another or do I need an extra step? I thought the approach without using the this would work, because function calls within others are perfectly possible in several languages, as for example:

function dale() {
    return true
}

function dolly() {
    if(dale()) {
        console.log('dolly')
    }
}

dolly()

that works perfectly, but apparently the context of a class brings some new dynamics, because:

class Dollynho {
    dale() {
        return true
    }

    dolly() {
        if(dale()) {
            console.log('dolly')
        }
    }
}

const teste = new Dollynho

teste.dolly()

no longer works

  • 2

    If you do not maintain status in class instances, is it really necessary to use class? I have the impression that you are using class only as a mechanism to separate code. Is it then no longer worth using a module?

  • It’s Felipe, I think you’re right. But despite that, I still have to deal with classes elsewhere and I won’t be able to sleep tonight without taking that doubt.

  • How are you invoking the methods in question? Probably the context (this) is being lost, which makes it impossible to reference instance methods by this by the methods of the class itself, as you have shown.

  • @Luizfelipe his comment gave me a darn light. Before I exported the class so: export default new AuthManager (Is it bad practice to sport with the new? ) and then mattered like any other module inside my file that handles the routes, using it as follows: routes.post('/register', AuthManager.registerNewCharacter)

  • After your comment I tried another approach. exporting as: export default AuthManager and using it: routes.post('/register', (req, res ) => {const teste = new AuthManager; teste.registerNewCharacter(req, res)}) Which works perfectly, but I can’t get rid of the feeling of doing a dirty job. Think I should delete the post?

  • 2

    No problem to export direct with the new. The problem you were having is because of the loss of context when passing the method reference directly. The this in Javascript is complicated. : ) But the feeling of "pig" must be coming from the unnecessary use of classes there. You’re trying to use "object orientation" where you don’t need it. Note that your class doesn’t encapsulate any state, so the way it is, it’s not necessary. The "class" that is there only serves to separate code according to the functionality. In this case, a module that exports functions seems to me to make much more sense.

Show 1 more comment
No answers

Browser other questions tagged

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