jeffijoe / awilix-express

Awilix helpers/middleware for Express
MIT License
118 stars 7 forks source link

Trying minimal example #7

Closed sam-ji closed 6 years ago

sam-ji commented 6 years ago

I have this project structure:

src:  server.js  routes     todos.js

server.js

const Express = require ('express')
const { asClass, createContainer } = require('awilix')
const { loadControllers, scopePerRequest } = require ('awilix-express')

const app = Express()

class TodosService{
  getTodos (){ return "Holi"}
}

const container = createContainer()
.register({
  // Scoped lifetime = new instance per request
  // Imagine the TodosService needs a `user`.
  // class TodosService { constructor({ user }) { } }
  todosService: asClass(TodosService).scoped()
})
app.use(scopePerRequest(container))
// Loads all controllers in the `routes` folder
// relative to the current working directory.
// This is a glob pattern.
app.use(loadControllers('routes/*.js', { cwd: __dirname }))

app.listen(3000)

routes/todos.js

const { makeInvoker } = require('awilix-express')

function makeAPI({ todosService }) {
  return {
    getTodos: (req, res) => {
      return res.send(todosService.getTodos())
    }
  }
}

module.exports = function(router) {
  const api = makeInvoker(makeAPI)
  router.get('/todos', api('getTodos'))
}

I cannot get any response @GET/todos

Is that related to the usage of module.exports instead of exports? Any insight in how to make this work? Thanks in advance!

jeffijoe commented 6 years ago

You are mixing the manual approach of makeInvoker and the use of loadControllers 😄

If you wish to use loadControllers, update your route to use createController like so:

const { createController } = require('awilix-express')

function makeAPI({ todosService }) {
  return {
    getTodos: (req, res) => {
      return res.send(todosService.getTodos())
    }
  }
}

module.exports = createController(makeAPI)
  .get('/todos', 'getTodos')