Skip to content

Instantly share code, notes, and snippets.

@jeffijoe
Created September 6, 2016 09:52
Show Gist options
  • Save jeffijoe/ad0a4247e4925310f64d893bdca1d483 to your computer and use it in GitHub Desktop.
Save jeffijoe/ad0a4247e4925310f64d893bdca1d483 to your computer and use it in GitHub Desktop.
Snippet for my Medium article
const router = new KoaRouter()
router.get('/todos', async (ctx) => {
const todosService = makeTodosService({
todosRepository: new TodosRepository(),
// Our Koa request knows about the current user
currentUser: ctx.state.user
})
ctx.body = await todosService.getTodos(ctx.request.query)
ctx.status = 200
})
router.post('/todos', async (ctx) => {
const todosService = makeTodosService({
todosRepository: new TodosRepository(),
currentUser: ctx.state.user
})
// ...
})
// and so on...
@gunzip
Copy link

gunzip commented Feb 17, 2018

Or you can just use currying (or bind()):

export const makeTodosService = (todoRepository) => (currentUser) => { ... return todoService... }
const router = new KoaRouter()

const todoService = makeTodoService(new TodosRepository());

router.get('/todos', async (ctx) => {
  const todosService = todoService(ctx.state.user);  
  ctx.body = await todosService.getTodos(ctx.request.query)
  ctx.status = 200
})
  
router.post('/todos', async (ctx) => {
  const todosService = todoService(ctx.state.user);  
  // ...
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment