Home > OS >  Can't reach nested function from another file in javascript
Can't reach nested function from another file in javascript

Time:11-27

I am trying to make a layered architecture with nodejs&fastify.

import {UserRepository} from "../repositories/UserRepository.js"

const AuthController = (UserRepository) => {
const getUserOne =  () => {
    return "bla"
}

return {getUserOne}
}

export default AuthController

I just tried to create a controller which depends on the UserRepository, then I tried to inject this controller into the route file just like this:

import AuthController from "../controllers/AuthController.js";
console.log(AuthController.getUser)
export function Auth(f,  opts, done) {
f.post('/register', {}, AuthController.getUserOne )


done()
}

But I never reach the getUserOne function from routers, also I saw some similar examples on the web but those didn't help me.

What am I missing actually?

Thank you.

CodePudding user response:

You have defined AuthController as function that returns an object with the getUserOne function as a property. So in order to pass the getUserOne function like you are wanting you will need to call the AuthController function then reference the getUserOne function property on the object returned:

import AuthController from "../controllers/AuthController.js";

export function Auth(f,  opts, done) {
  f.post('/register', {}, AuthController().getUserOne )

  done()
}

If you are wanting to use the .(dot) notation you will need to define the getUserOne function as a property on the AuthController function by using the this keyword:

const AuthController = (UserRepository) => {
  this.getUserOne =  () => {
      return "bla"
  }

  return {getUserOne}
}

Then you will be able access the getUserOne function like you are above

  • Related