optimized local api instantiation to prepare for nextjs app router

This commit is contained in:
dswbx
2025-02-20 10:02:44 +01:00
parent eaa7276173
commit 6f776aeff7
9 changed files with 123 additions and 122 deletions

View File

@@ -1,5 +1,5 @@
import { Api, type ApiOptions } from "Api";
import type { CreateUserPayload } from "auth/AppAuth";
import { Api, type ApiOptions } from "bknd/client";
import { $console } from "core";
import { Event } from "core/events";
import { Connection, type LibSqlCredentials, LibsqlConnection } from "data";
@@ -48,6 +48,7 @@ export type CreateAppConfig = {
};
export type AppConfig = InitialModuleConfigs;
export type LocalApiOptions = Request | ApiOptions;
export class App {
modules: ModuleManager;
@@ -180,13 +181,15 @@ export class App {
return this.module.auth.createUser(p);
}
getApi(options: Request | ApiOptions = {}) {
async getApi(options?: LocalApiOptions) {
const fetcher = this.server.request as typeof fetch;
if (options instanceof Request) {
return new Api({ request: options, headers: options.headers, fetcher });
if (options && options instanceof Request) {
const api = new Api({ request: options, headers: options.headers, fetcher });
await api.verifyAuth();
return api;
}
return new Api({ host: "http://localhost", ...options, fetcher });
return new Api({ host: "http://localhost", ...(options ?? {}), fetcher });
}
}

View File

@@ -1,49 +1,35 @@
import type { IncomingMessage, ServerResponse } from "node:http";
import { nodeRequestToRequest } from "adapter/utils";
import type { App } from "bknd";
import { type FrameworkBkndConfig, createFrameworkApp } from "bknd/adapter";
import { Api } from "bknd/client";
export type NextjsBkndConfig = FrameworkBkndConfig & {
cleanSearch?: string[];
cleanRequest?: { searchParams?: string[] };
};
type GetServerSidePropsContext = {
req: IncomingMessage;
res: ServerResponse;
params?: Params;
query: any;
preview?: boolean;
previewData?: any;
draftMode?: boolean;
resolvedUrl: string;
locale?: string;
locales?: string[];
defaultLocale?: string;
};
let app: App;
let building: boolean = false;
export function createApi({ req }: GetServerSidePropsContext) {
const request = nodeRequestToRequest(req);
return new Api({
host: new URL(request.url).origin,
headers: request.headers
});
export async function getApp(config: NextjsBkndConfig) {
if (building) {
while (building) {
await new Promise((resolve) => setTimeout(resolve, 5));
}
if (app) return app;
}
building = true;
if (!app) {
app = await createFrameworkApp(config);
await app.build();
}
building = false;
return app;
}
export function withApi<T>(handler: (ctx: GetServerSidePropsContext & { api: Api }) => T) {
return async (ctx: GetServerSidePropsContext & { api: Api }) => {
const api = createApi(ctx);
await api.verifyAuth();
return handler({ ...ctx, api });
};
}
function getCleanRequest(req: Request, cleanRequest: NextjsBkndConfig["cleanRequest"]) {
if (!cleanRequest) return req;
function getCleanRequest(
req: Request,
{ cleanSearch = ["route"] }: Pick<NextjsBkndConfig, "cleanSearch">
) {
const url = new URL(req.url);
cleanSearch?.forEach((k) => url.searchParams.delete(k));
cleanRequest?.searchParams?.forEach((k) => url.searchParams.delete(k));
return new Request(url.toString(), {
method: req.method,
@@ -52,13 +38,12 @@ function getCleanRequest(
});
}
let app: App;
export function serve({ cleanSearch, ...config }: NextjsBkndConfig = {}) {
export function serve({ cleanRequest, ...config }: NextjsBkndConfig = {}) {
return async (req: Request) => {
if (!app) {
app = await createFrameworkApp(config);
app = await getApp(config);
}
const request = getCleanRequest(req, { cleanSearch });
return app.fetch(request, process.env);
const request = getCleanRequest(req, cleanRequest);
return app.fetch(request);
};
}

View File

@@ -10,7 +10,10 @@ type RemixContext = {
let app: App;
let building: boolean = false;
export async function getApp(config: RemixBkndConfig, args?: RemixContext) {
export async function getApp<Args extends RemixContext = RemixContext>(
config: RemixBkndConfig<Args>,
args?: Args
) {
if (building) {
while (building) {
await new Promise((resolve) => setTimeout(resolve, 5));
@@ -31,7 +34,7 @@ export function serve<Args extends RemixContext = RemixContext>(
config: RemixBkndConfig<Args> = {}
) {
return async (args: Args) => {
app = await createFrameworkApp(config, args);
app = await getApp(config, args);
return app.fetch(args.request);
};
}

View File

@@ -4,7 +4,8 @@ export {
AppEvents,
type AppConfig,
type CreateAppConfig,
type AppPlugin
type AppPlugin,
type LocalApiOptions
} from "./App";
export {