improved astro adapter (serving api) + added documentation

This commit is contained in:
dswbx
2024-12-01 08:58:08 +01:00
parent b55fdd7516
commit feeb13c053
9 changed files with 166 additions and 23 deletions

View File

@@ -1,10 +1,8 @@
import { Api, type ApiOptions } from "bknd";
import { App, type CreateAppConfig } from "bknd";
type TAstro = {
request: {
url: string;
headers: Headers;
};
request: Request;
};
export type Options = {
@@ -19,3 +17,15 @@ export function getApi(Astro: TAstro, options: Options = { mode: "static" }) {
headers: options.mode === "dynamic" ? Astro.request.headers : undefined
});
}
let app: App;
export function serve(config: CreateAppConfig) {
return async (args: TAstro) => {
if (!app) {
app = App.create(config);
await app.build();
}
return app.fetch(args.request);
};
}

View File

@@ -11,10 +11,21 @@ export class AuthController implements ClassController {
getMiddleware: MiddlewareHandler = async (c, next) => {
// @todo: ONLY HOTFIX
// middlewares are added for all routes are registered. But we need to make sure that
// only HTML/JSON routes are adding a cookie to the response. Config updates might
// also use an extension "syntax", e.g. /api/system/patch/data/entities.posts
// This middleware should be extracted and added by each Controller individually,
// but it requires access to the auth secret.
// Note: This doesn't mean endpoints aren't protected, just the cookie is not set.
const url = new URL(c.req.url);
const last = url.pathname.split("/")?.pop();
const ext = last?.includes(".") ? last.split(".")?.pop() : undefined;
if (ext) {
if (
!this.auth.authenticator.isJsonRequest(c) &&
["GET", "HEAD", "OPTIONS"].includes(c.req.method) &&
ext &&
["js", "css", "png", "jpg", "jpeg", "svg", "ico"].includes(ext)
) {
isDebug() && console.log("Skipping auth", { ext }, url.pathname);
} else {
const user = await this.auth.authenticator.resolveAuthFromRequest(c);

View File

@@ -249,6 +249,7 @@ export class Authenticator<Strategies extends Record<string, Strategy> = Record<
}
}
// @todo: move this to a server helper
isJsonRequest(c: Context): boolean {
//return c.req.header("Content-Type") === "application/x-www-form-urlencoded";
return c.req.header("Content-Type") === "application/json";