Commit f632e714 authored by Kim, Hyeonseo's avatar Kim, Hyeonseo
Browse files

feat: add contextDataFactory parameter

parent 021a3b7a
Loading
Loading
Loading
Loading
+56 −47
Original line number Diff line number Diff line
import { type Federation } from "@fedify/fedify";
import type { Federation } from "@fedify/fedify";
import type { Elysia } from "elysia";

export type ContextDataFactory<TContextData> = () =>
	| TContextData
	| Promise<TContextData>;

export const fedify = <TContextData = unknown>(
	federation: Federation<TContextData>,
	contextDataFactory: ContextDataFactory<TContextData>,
) => {
	return (app: Elysia) =>
		app
			.decorate("federation", federation)
      .onRequest(async ({ request, set }) => {
			.onRequest(async ({ request, set, federation }) => {
				let notFound = false;
				let notAcceptable = false;

        // Create context data - you may want to make this configurable
        const contextData = {} as TContextData;
				// Create context data using the factory or default to empty object
				const contextData = await contextDataFactory();

				const response = await federation.fetch(request, {
					contextData,
          onload: () => {
            console.log("dfsfdsfds");
          },
					onNotFound: () => {
						// Let Elysia handle non-federation routes
						notFound = true;
@@ -37,16 +39,23 @@ export const fedify = <TContextData = unknown>(
					},
				});

        // If federation handled the request, return the response
        if (notFound || (notAcceptable && request != null)) {
				if (!notFound && !notAcceptable) {
					set.status = response.status;

					response.headers.forEach((value, key) => {
						set.headers[key] = value;
					});

					// Return response body if it exists
					if (response.body) {
						return response;
					}

					// Return empty response for successful requests without body
					return new Response(null, { status: response.status });
				}

				// Continue to next handler if federation didn't handle the request
			})
			.as("global");
};