Merge branch 'conf-mw' into 'main'

Add @ditto/api package with conf middleware

See merge request soapbox-pub/ditto!663
This commit is contained in:
Alex Gleason 2025-02-15 23:56:14 +00:00
commit 3d2816dd05
7 changed files with 81 additions and 0 deletions

View file

@ -1,5 +1,6 @@
{
"workspace": [
"./packages/api",
"./packages/config",
"./packages/ditto"
],

7
packages/api/deno.json Normal file
View file

@ -0,0 +1,7 @@
{
"name": "@ditto/api",
"version": "1.1.0",
"exports": {
"./middleware": "./middleware/mod.ts"
}
}

View file

@ -0,0 +1,19 @@
import { Hono } from '@hono/hono';
import { assertEquals } from '@std/assert';
import { confMw } from './confMw.ts';
Deno.test('confMw', async () => {
const env = new Map([
['DITTO_NSEC', 'nsec19shyxpuzd0cq2p5078fwnws7tyykypud6z205fzhlmlrs2vpz6hs83zwkw'],
]);
const app = new Hono();
app.get('/', confMw(env), (c) => c.text(c.var.conf.pubkey));
const response = await app.request('/');
const body = await response.text();
assertEquals(body, '1ba0c5ed1bbbf3b7eb0d7843ba16836a0201ea68a76bafcba507358c45911ff6');
});

View file

@ -0,0 +1,15 @@
import { DittoConfig } from '@ditto/config';
import type { MiddlewareHandler } from '@hono/hono';
/** Set Ditto config. */
export function confMw(
env: { get(key: string): string | undefined },
): MiddlewareHandler<{ Variables: { conf: DittoConfig } }> {
const conf = new DittoConfig(env);
return async (c, next) => {
c.set('conf', conf);
await next();
};
}

View file

@ -0,0 +1,22 @@
import { Hono } from '@hono/hono';
import { assertEquals } from '@std/assert';
import { confMw } from './confMw.ts';
import { confRequiredMw } from './confRequiredMw.ts';
Deno.test('confRequiredMw', async (t) => {
const app = new Hono();
app.get('/without', confRequiredMw, (c) => c.text('ok'));
app.get('/with', confMw(new Map()), confRequiredMw, (c) => c.text('ok'));
await t.step('without conf returns 500', async () => {
const response = await app.request('/without');
assertEquals(response.status, 500);
});
await t.step('with conf returns 200', async () => {
const response = await app.request('/with');
assertEquals(response.status, 200);
});
});

View file

@ -0,0 +1,15 @@
import { HTTPException } from '@hono/hono/http-exception';
import type { DittoConfig } from '@ditto/config';
import type { MiddlewareHandler } from '@hono/hono';
/** Throws an error if conf isn't set. */
export const confRequiredMw: MiddlewareHandler<{ Variables: { conf: DittoConfig } }> = async (c, next) => {
const { conf } = c.var;
if (!conf) {
throw new HTTPException(500, { message: 'Ditto config not set in request.' });
}
await next();
};

View file

@ -0,0 +1,2 @@
export { confMw } from './confMw.ts';
export { confRequiredMw } from './confRequiredMw.ts';