Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

showcase: di-wise hono middleware #19

Open
ArjixWasTaken opened this issue Dec 13, 2024 · 1 comment
Open

showcase: di-wise hono middleware #19

ArjixWasTaken opened this issue Dec 13, 2024 · 1 comment

Comments

@ArjixWasTaken
Copy link

I wrote a simple hono.js middleware to integrate di-wise into your routing!

import { createMiddleware } from 'hono/factory';

import { Token } from 'di-wise';

// your custom global container
import { container } from '@/container';

type ExtractType<T> = T extends Token<infer U> ? U : never;

export const inject = <T, K extends Record<string, Token<T>>>(tokens: K) => {
    return createMiddleware<{ Variables: { [key in keyof K]: ExtractType<K[key]> } }>(async (ctx, next) => {
        for (const [key, token] of Object.entries(tokens)) {
            // @ts-ignore
            ctx.set(key, container.resolve(token));
        }

        return next();
    });
}

usage

import { Hono } from 'hono';

import { tokens } from '@/container';
import { inject } from '@/middleware';

const app = new Hono();

app.get('/login',
    inject({ userRepo: tokens.UserRepository }),
    async (ctx) => {
        ctx.var.userRepo.findByUsername(...)
    }
);

// or you can make it a global middleware!
app.use(inject({ userRepo: tokens.UserRepository }));

If you have any suggestions/improvements to make, please share them!

@ArjixWasTaken
Copy link
Author

honestly, resolving multiple tokens in batch like this would be nice even outside of hono.js

e.g.

const { userRepo } = container.resolve({ userRepo: tokens.UserRepository });

that way we can have a lot of injections, w/o having a lot of container.resolves

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant