Skip to content

Commit

Permalink
Added request recorder
Browse files Browse the repository at this point in the history
  • Loading branch information
allouis committed Jul 25, 2024
1 parent f4ec0cf commit aacb270
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ import {
} from './dispatchers';

import { inboxHandler, postPublishedWebhook, followAction } from './handlers';
import * as path from 'path';
import { RequestRecorder } from 'requestrecorder';

if (process.env.SENTRY_DSN) {
Sentry.init({ dsn: process.env.SENTRY_DSN });
Expand Down Expand Up @@ -206,6 +208,13 @@ app.use(async (ctx, next) => {
await next();
});

if (process.env.RECORD_INBOX_REQUESTS) {
const filePath = path.join(import.meta.dirname, '../', 'inbox-requests.json');
console.log(`Recording to ${filePath}`);
const requestRecorder = await RequestRecorder.create(filePath);
app.post('/.ghost/activitypub/inbox/:handle', requestRecorder.honoMiddleware.bind(requestRecorder));
}

/** Custom API routes */

app.get('/ping', (ctx) => {
Expand Down
43 changes: 43 additions & 0 deletions src/requestrecorder.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { Context, Next } from 'hono';
import { FileHandle, open } from 'fs/promises';

type JSONRequest = {
input: string
init: RequestInit
}

export class RequestRecorder {
private constructor(private readonly file: FileHandle) {}

async recordRequest(req: Request): Promise<void> {
try {
const json = await this.requestToJSON(req);
this.file.appendFile(JSON.stringify(json) + '\n');
} catch (err) {
console.error('Could not write JSON');
}
}

async honoMiddleware(ctx: Context<any>, next: Next) {
this.recordRequest(ctx.req.raw);
await next();
}

async requestToJSON(request: Request): Promise<JSONRequest> {
const req = request.clone();
const body = await new Response(req.body).text();
return {
input: req.url,
init: {
body: body,
headers: Object.fromEntries(req.headers.entries()),
method: req.method
}
};
}

static async create(path: string): Promise<RequestRecorder> {
const file = await open(path, 'a');
return new RequestRecorder(file);
}
}

0 comments on commit aacb270

Please sign in to comment.