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

Expose Hono context to options callback #3

Merged
merged 2 commits into from
Feb 17, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 15 additions & 13 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { createMiddleware } from 'hono/factory';
import createFactory from 'ronin';

import type { Context } from 'hono';
import type { QueryHandlerOptions } from 'ronin/types';

type Factory = ReturnType<typeof createFactory>;

export type Bindings = {
Expand All @@ -16,7 +19,7 @@ type Env = {
Variables: Variables;
};

type QueryHandlerOptions = Parameters<typeof createFactory>[0];
interface Options extends QueryHandlerOptions {}

/**
* Create a Hono middleware that injects a RONIN client into the Hono context variables.
Expand All @@ -43,24 +46,23 @@ type QueryHandlerOptions = Parameters<typeof createFactory>[0];
*
* @returns A Hono middleware.
*/
export const ronin = (options: QueryHandlerOptions = {}) =>
export const ronin = (options?: Options | ((context: Context) => Options)) =>
createMiddleware<Env>(async (c, next) => {
if (!c.env.RONIN_TOKEN) {
const userOptions = options
? typeof options === 'function'
? options(c)
: options
: ({} satisfies QueryHandlerOptions);

const token = userOptions.token ?? c.env.RONIN_TOKEN;
if (!token)
throw new Error(
'A `RONIN_TOKEN` environment variable must be provided for the RONIN middleware',
'Either a `RONIN_TOKEN` environment variable or a `token` option must be provided for the RONIN middleware',
);
}

const { token: userToken, ...userOptions } =
typeof options === 'function' ? options() : options;

if (userToken) {
throw new Error('The RONIN middleware does not support a `token` option');
}

const client = createFactory({
token: c.env.RONIN_TOKEN,
...userOptions,
token,
});

c.set('ronin', client);
Expand Down
72 changes: 64 additions & 8 deletions tests/integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ import { createFactory } from 'hono/factory';
import { testClient } from 'hono/testing';

import { ronin } from '@/src/index';
import { fetcher } from '@/tests/utils';

import type { Bindings, Variables } from '@/src/index';
import { fetcher } from '@/tests/utils';

import.meta.env.RONIN_TOKEN = 'secret-token';

describe('use `ronin` middleware', () => {
describe('Use `ronin` middleware', () => {
const factory = createFactory<{ Bindings: Bindings; Variables: Variables }>();

it('with default options', async () => {
Expand Down Expand Up @@ -128,7 +128,55 @@ describe('use `ronin` middleware', () => {
expect(json).toHaveLength(1);
});

it('with a missing `RONIN_TOKEN`', async () => {
it('with custom options using the Hono context (function)', async () => {
const app = factory
.createApp()
.use(
'*',
ronin((context) => {
expect(context).toBeDefined();
expect(context.env).toMatchObject({});

return {
asyncContext: new AsyncLocalStorage(),
fetch: fetcher,
hooks: {
user: {
beforeGet: (query) => {
query.limitedTo = 1;
return query;
},
},
},
};
}),
)
.get('/', async (c) => {
expect(c.var.ronin).toBeDefined();

const users = await c.var.ronin.get.users();

expect(users).toBeDefined();
expect(users).toBeInstanceOf(Array);

return c.json(users);
});

const response = await testClient(app, {
RONIN_TOKEN: import.meta.env.RONIN_TOKEN,
}).index.$get();

expect(response.ok).toBe(true);
expect(response.status).toBe(200);

const json = await response.json();

expect(json).toBeDefined();
expect(json).toBeInstanceOf(Array);
expect(json).toHaveLength(1);
});

it('with a missing RONIN token', async () => {
let receivedError: Error | undefined;

const app = factory
Expand All @@ -152,16 +200,23 @@ describe('use `ronin` middleware', () => {

expect(receivedError).toMatchObject({
message:
'A `RONIN_TOKEN` environment variable must be provided for the RONIN middleware',
'Either a `RONIN_TOKEN` environment variable or a `token` option must be provided for the RONIN middleware',
});
});

it('with a `token` option', async () => {
it('with a `null` RONIN token', async () => {
let receivedError: Error | undefined;

const app = factory
.createApp()
.use('*', ronin({ fetch: fetcher, token: crypto.randomUUID() }))
.use(
'*',
ronin({
fetch: fetcher,
// @ts-expect-error `null` is not allowed here.
token: null,
}),
)
.get('/', async (c) => {
expect(c.var.ronin).toBeDefined();

Expand All @@ -175,11 +230,12 @@ describe('use `ronin` middleware', () => {
});

await testClient(app, {
RONIN_TOKEN: import.meta.env.RONIN_TOKEN,
RONIN_TOKEN: null,
}).index.$get();

expect(receivedError).toMatchObject({
message: 'The RONIN middleware does not support a `token` option',
message:
'Either a `RONIN_TOKEN` environment variable or a `token` option must be provided for the RONIN middleware',
});
});
});
Loading