Last active
December 11, 2022 10:09
-
-
Save jeffijoe/828b810d88c74449492bbc3bb9efa9cb to your computer and use it in GitHub Desktop.
Snippet for my Medium article
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Koa from 'koa' | |
import KoaRouter from 'koa-router' | |
import { asValue } from 'awilix' | |
import { scopePerRequest, makeInvoker } from 'awilix-koa' | |
import configureContainer from './configureContainer' | |
const app = new Koa() | |
const router = new KoaRouter() | |
const container = configureContainer() | |
// This installs a scoped container into our | |
// context - we will use this to register our current user! | |
app.use(scopePerRequest(container)) | |
// Let's do that now! | |
app.use((ctx, next) => { | |
ctx.state.container.registerValue({ | |
// Imagine some auth middleware somewhere... | |
// This makes currentUser available to all services! | |
currentUser: ctx.state.user | |
}) | |
return next() | |
}) | |
// Now our route handlers will be able to resolve a todos service.. | |
// using DEPENDENCY INJECTION! YEEEEHAW! | |
// P.S: be a good dev and use multiple files. ;) | |
const todosAPI = ({ todosService }) => { | |
return { | |
getTodos: async (ctx) => { | |
const todos = await todosService.getTodos(ctx.request.query) | |
ctx.body = todos | |
ctx.status = 200 | |
}, | |
createTodo: async (ctx) => { | |
const todo = await todosService.createTodo(ctx.request.body) | |
ctx.body = todo | |
ctx.status = 201 | |
}, | |
updateTodo: async (ctx) => { | |
const updated = await todosService.updateTodo( | |
ctx.params.id, | |
ctx.request.body | |
) | |
ctx.body = updated | |
ctx.status = 200 | |
}, | |
deleteTodo: async (ctx) => { | |
await todosService.deleteTodo( | |
ctx.params.id, | |
ctx.request.body | |
) | |
ctx.status = 204 | |
} | |
} | |
} | |
// Awilix magic will run the above function | |
// every time a request comes in, so we have | |
// a set of scoped services per request. | |
const api = makeInvoker(todosAPI) | |
router.get('/todos', api('getTodos')) | |
router.post('/todos', api('createTodo')) | |
router.patch('/todos/:id', api('updateTodo')) | |
router.delete('/todos/:id', api('deleteTodo')) | |
app.use(router.routes()) | |
app.listen(1337) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment