Add memoization utility (v0.0.1-alpha.4)
diff --git a/demo/src/DemoAPI.ts b/demo/src/DemoAPI.ts
index defdbe2..3c7c567 100644
--- a/demo/src/DemoAPI.ts
+++ b/demo/src/DemoAPI.ts
@@ -7,11 +7,14 @@
// Conduit API. This file could be shared to allow other projects
// to call this API with type safety.
-export type DemoAPI = YggdrasilConduitAPI<{
- /** The first argument to YggdrasilConduitAPI defines your API functions available to the client. */
- hello: (time: "morning" | "evening" | "afternoon" | "night") => Promise<string>;
- goodbye: () => Promise<string>;
-}, {
- /** The second argument defines common context parameters passed to all Conduit API calls. */
- name: string;
-}>;
\ No newline at end of file
+export type DemoAPI = {
+ client: {
+ /** The first argument to YggdrasilConduitAPI defines your API functions available to the client. */
+ hello: (time: "morning" | "evening" | "afternoon" | "night") => Promise<string>;
+ goodbye: () => Promise<string>;
+ };
+ context: {
+ /** The second argument defines common context parameters passed to all Conduit API calls. */
+ name: string;
+ };
+};
\ No newline at end of file
diff --git a/demo/src/index.ts b/demo/src/index.ts
index 17bb99f..03ad502 100644
--- a/demo/src/index.ts
+++ b/demo/src/index.ts
@@ -18,21 +18,23 @@
try {
return await DemoConduitServer.handleRequest(ygg);
- } catch(e) {
+ } catch (e) {
if (!(e instanceof YggdrasilStatus) || (e.status !== 404)) throw e;
}
try {
return await DemoRouter.handleRequest(ygg);
- } catch(e) {
+ } catch (e) {
if (!(e instanceof YggdrasilStatus) || (e.status !== 404)) throw e;
}
throw ygg.status(404, "INVALID_PATH", "Nobody was able to handle your request :(");
}, {
- env,
- ctx,
- conduit: createConduitServerSideClient<DemoAPI>({ name: "jottocraft" }, { baseURL: "https://yggdrasil.ns.jottocraft.com/demo/conduit/", fetcher: (input: RequestInfo | URL, init?: RequestInit) => this.fetch(new Request(input, init), env, ctx) })
+ ctx: {
+ env,
+ ctx,
+ conduit: createConduitServerSideClient<DemoAPI>({ name: "jottocraft" }, { baseURL: "https://yggdrasil.ns.jottocraft.com/demo/conduit/", fetcher: (input: RequestInfo | URL, init?: RequestInit) => this.fetch(new Request(input, init), env, ctx) })
+ }
}, {
debug: true,
baseURL: "https://yggdrasil.ns.jottocraft.com/demo",
diff --git a/demo/src/routes/index.ts b/demo/src/routes/index.ts
index 3aba3b8..d4d4c6a 100644
--- a/demo/src/routes/index.ts
+++ b/demo/src/routes/index.ts
@@ -4,4 +4,5 @@
export * from "./abc";
export * from "./def";
export * from "./goodbye";
-export * from "./hij";
\ No newline at end of file
+export * from "./hij";
+export * from "./memo";
\ No newline at end of file
diff --git a/demo/src/routes/memo.ts b/demo/src/routes/memo.ts
new file mode 100644
index 0000000..d15dbce
--- /dev/null
+++ b/demo/src/routes/memo.ts
@@ -0,0 +1,29 @@
+// Yggdrasil
+// Copyright (c) jottocraft 2024
+
+import { DemoServer } from "../server";
+
+async function multiplyNumbers() {
+ console.log("Multiplying numbers...");
+ return 34 * 45;
+}
+
+export const memo = DemoServer.defineRoute("GET", "/memo", async (ygg) => {
+ // Do the same thing a bunch of times to test memoization.
+ const data = await Promise.all([
+ ygg.memoize("multiplyNumbers", multiplyNumbers),
+ ygg.memoize("multiplyNumbers", multiplyNumbers),
+ ygg.memoize("multiplyNumbers", multiplyNumbers),
+ ygg.memoize("multiplyNumbers", multiplyNumbers),
+ ygg.memoize("multiplyNumbers", multiplyNumbers),
+ ygg.memoize("multiplyNumbers", multiplyNumbers),
+ ygg.memoize("multiplyNumbers", multiplyNumbers)
+ ]);
+
+ await new Promise(res => { setTimeout(res, 1000) });
+
+ // It should also work after the result is in.
+ data.push(await ygg.memoize("multiplyNumbers", multiplyNumbers));
+
+ return new Response("Result: " + data.join(","), { status: 200 });
+});
\ No newline at end of file
diff --git a/demo/src/server.ts b/demo/src/server.ts
index fd8ed6f..4d174f9 100644
--- a/demo/src/server.ts
+++ b/demo/src/server.ts
@@ -9,7 +9,9 @@
import { DemoAPI } from "./DemoAPI";
export const DemoServer = new YggdrasilServer<{
- env: DemoEnv;
- ctx: ExecutionContext;
- conduit: YggdrasilConduitAPIClient<DemoAPI>;
+ ctx: {
+ env: DemoEnv;
+ ctx: ExecutionContext;
+ conduit: YggdrasilConduitAPIClient<DemoAPI>;
+ }
}, DemoAPI>();
\ No newline at end of file
diff --git a/docs/docs/features/conduit.md b/docs/docs/features/conduit.md
index c8b2e70..ba0a76c 100644
--- a/docs/docs/features/conduit.md
+++ b/docs/docs/features/conduit.md
@@ -62,17 +62,18 @@
involve putting it in an NPM package, git submodule, etc.
```ts title="my-shared-library/conduit.ts"
-import { YggdrasilConduitAPI } from "@jottocraft/yggdrasil";
-
// This defines the type of your Conduit API.
-export type MyAPI = YggdrasilConduitAPI<{
- /** The first argument to YggdrasilConduitAPI defines your API functions available to the client. */
+export type MyAPI = {
+ /** The client object defines your API functions available to the client. */
+ client: {
hello: (time: "morning" | "evening" | "afternoon" | "night") => Promise<string>;
goodbye: () => Promise<string>;
-}, {
- /** The second argument defines common context parameters passed to all Conduit API calls. */
+ };
+ /** The context object defines common context parameters passed to all Conduit API calls. */
+ context: {
name: string;
-}>;
+ };
+};
// It's recommended to define the client options here to ensure consistency.
// They can always be overridden if needed.
@@ -86,7 +87,7 @@
```ts title="src/server.ts"
// Adding MyAPI here lets YggdrasilServer know what to expect so it
// can throw an error if you forget to implement a function.
-export const DemoServer = new YggdrasilServer<AppCtx, MyAPI>();
+export const DemoServer = new YggdrasilServer<AppType, MyAPI>();
```
### Implement your API
diff --git a/docs/docs/features/memo.md b/docs/docs/features/memo.md
new file mode 100644
index 0000000..e3fc00b
--- /dev/null
+++ b/docs/docs/features/memo.md
@@ -0,0 +1,63 @@
+---
+sidebar_position: 5
+---
+
+# Memoization
+
+Yggdrasil Server includes a memoization utility that can help you
+memoize expensive function calls you may make while handling
+requests.
+
+Results from memoization are stored in the `ygg` context, so
+each memoized task will run at most once per request.
+
+## Usage
+
+To memoize a function, simply use `ygg.memoize`:
+
+```ts title="src/utilities.ts"
+// Before memoization:
+export async function myExpensiveUtility() {
+ return await doExpensiveTask(); // Some arbitrary expensive task
+}
+
+// After memoization:
+export async function myExpensiveUtility(ygg: YggdrasilContext<AppType>) {
+ return ygg.memoize("myExpensiveUtility", async () => {
+ return await doExpensiveTask();
+ });
+}
+```
+
+Now, to call the function:
+
+```ts title="src/routes/memo.ts"
+import { DemoServer } from "../server";
+
+export const memo = DemoServer.defineRoute("GET", "/memo", async (ygg) => {
+ // We call myExpensiveUtility twice, but memoization means that
+ // the underlying operation is only performed once. When the operation
+ // finishes, both promises resolve with the same result. Subsequent
+ // calls immediately return the result.
+ const results = Promise.all([
+ myExpensiveUtility(ygg),
+ myExpensiveUtility(ygg)
+ ]);
+
+ return new Response("Expensive operation results: " + results.join(","), { status: 200 });
+});
+```
+
+## Memoization techniques
+
+When memoizing a function, please consider the following:
+
+1. Memoizing a function requires making it take the `ygg` context
+as a parameter so that the result can be associated with the request.
+2. Yggdrasil Server's memoization utility stores and identifies
+the request and response based on a key string. In the above example,
+this is simply `"myExpensiveUtility"`. However, if you want to memoize
+a function with parameters, a more complex scheme for creating a key
+will be required. For example, you could do `"myExpensiveUtility,23"`
+if your utility takes a number and is given `23`. Any scheme works, as
+long as the key is unique for the request/response pair to memoize.
diff --git a/docs/docs/index.md b/docs/docs/index.md
index 04308c1..89d30d5 100644
--- a/docs/docs/index.md
+++ b/docs/docs/index.md
@@ -22,14 +22,17 @@
```ts title="src/server.ts"
import { YggdrasilServer } from "@jottocraft/yggdrasil";
-// Any arbitrary custom data to pass to your request handlers
-// e.g. environment variables, database bindings, etc.
-export type AppCtx = {
- env: DemoEnv;
- ctx: ExecutionContext;
+export type AppType = {
+ // The ctx object defines any arbitrary custom data
+ // to pass to your request handlers.
+ // Examples include environment variables, database bindings, etc.
+ ctx: {
+ env: DemoEnv;
+ ctx: ExecutionContext;
+ };
};
-export const DemoServer = new YggdrasilServer<AppCtx>();
+export const DemoServer = new YggdrasilServer<AppType>();
```
### Step 3: Handle requests
@@ -51,9 +54,11 @@
status: 200
});
},
- // Your custom request context, available as ygg.ctx in request handlers.
{
- env, ctx
+ // Your custom request context, available as ygg.ctx in request handlers.
+ ctx: {
+ env, ctx
+ }
},
// Yggdrasil Server options. These are specified here rather than in
// the YggdrasilServer object to support multi-tenancy.
diff --git a/yggdrasil/package.json b/yggdrasil/package.json
index 3c8df66..081480b 100644
--- a/yggdrasil/package.json
+++ b/yggdrasil/package.json
@@ -1,7 +1,7 @@
{
"name": "@jottocraft/yggdrasil",
"description": "A simple and flexible TypeScript library for streamlining web request handling.",
- "version": "0.0.1-alpha.3",
+ "version": "0.0.1-alpha.4",
"license": "LGPL-2.1-only",
"author": "jottocraft <[email protected]>",
"main": "lib/index.js",
diff --git a/yggdrasil/src/YggdrasilConduitServer.ts b/yggdrasil/src/YggdrasilConduitServer.ts
index 4d53913..cacbbb5 100644
--- a/yggdrasil/src/YggdrasilConduitServer.ts
+++ b/yggdrasil/src/YggdrasilConduitServer.ts
@@ -3,53 +3,53 @@
import { YggdrasilConduitAPI, YggdrasilConduitRequest, YggdrasilConduitResponse } from "~/conduitClient";
import { YggdrasilConduitContext, YggdrasilServerContext } from "~/context";
-import { YggdrasilServer } from "~/YggdrasilServer";
+import { YggdrasilAppTypes, YggdrasilServer } from "~/YggdrasilServer";
type AnyFn = (...args: any[]) => any;
/**
* A function that executes the server's implementation of its Conduit function.
*/
-export type YggdrasilConduitAPIHandler<AppContext, ApiSpec extends YggdrasilConduitAPI<any, any>, API extends AnyFn> = (ygg: YggdrasilConduitContext<AppContext, ApiSpec>, ...parameters: Parameters<API>) => ReturnType<API>;
+export type YggdrasilConduitAPIHandler<AppTypes extends YggdrasilAppTypes, ApiSpec extends YggdrasilConduitAPI, API extends AnyFn> = (ygg: YggdrasilConduitContext<AppTypes, ApiSpec>, ...parameters: Parameters<API>) => ReturnType<API>;
/**
* An object that stores the server's Conduit function implementations.
*/
-export type YggdrasilConduitApiClientImpl<AppContext, ApiSpec extends YggdrasilConduitAPI<any, any>> = {
- [Property in keyof ApiSpec["client"]]: ApiSpec["client"][Property] extends AnyFn ? YggdrasilConduitAPIHandler<AppContext, ApiSpec, ApiSpec["client"][Property]> : YggdrasilConduitApiClientImpl<AppContext, ApiSpec>;
+export type YggdrasilConduitApiClientImpl<AppTypes extends YggdrasilAppTypes, ApiSpec extends YggdrasilConduitAPI> = {
+ [Property in keyof ApiSpec["client"]]: ApiSpec["client"][Property] extends AnyFn ? YggdrasilConduitAPIHandler<AppTypes, ApiSpec, ApiSpec["client"][Property]> : YggdrasilConduitApiClientImpl<AppTypes, ApiSpec>;
};
/**
* A helper object for defining Conduit function implementations with automatic type safety.
*/
-export type YggdrasilConduitApiClientBlueprint<AppContext, ApiSpec extends YggdrasilConduitAPI<any, any>> = {
- [Property in keyof ApiSpec["client"]]: ApiSpec["client"][Property] extends AnyFn ? (impl: YggdrasilConduitAPIHandler<AppContext, ApiSpec, ApiSpec["client"][Property]>) => YggdrasilConduitAPIHandler<AppContext, ApiSpec, ApiSpec["client"][Property]> : YggdrasilConduitApiClientBlueprint<AppContext, ApiSpec>;
+export type YggdrasilConduitApiClientBlueprint<AppTypes extends YggdrasilAppTypes, ApiSpec extends YggdrasilConduitAPI> = {
+ [Property in keyof ApiSpec["client"]]: ApiSpec["client"][Property] extends AnyFn ? (impl: YggdrasilConduitAPIHandler<AppTypes, ApiSpec, ApiSpec["client"][Property]>) => YggdrasilConduitAPIHandler<AppTypes, ApiSpec, ApiSpec["client"][Property]> : YggdrasilConduitApiClientBlueprint<AppTypes, ApiSpec>;
};
/**
* Internal type for recursing through arbitrary segments in the API object.
*/
-type APISegment<AppContext, ApiSpec extends YggdrasilConduitAPI<any, any>> = {
- [segment: string]: APISegment<AppContext, ApiSpec> | YggdrasilConduitAPIHandler<AppContext, ApiSpec, AnyFn>;
+type APISegment<AppTypes extends YggdrasilAppTypes, ApiSpec extends YggdrasilConduitAPI> = {
+ [segment: string]: APISegment<AppTypes, ApiSpec> | YggdrasilConduitAPIHandler<AppTypes, ApiSpec, AnyFn>;
};
/**
* A server for handling Conduit requests made to Yggdrasil Server.
*/
-export class YggdrasilConduitServer<AppContext, ApiSpec extends YggdrasilConduitAPI<any, any>> {
- constructor(server: YggdrasilServer<AppContext, ApiSpec>, api: YggdrasilConduitApiClientImpl<AppContext, ApiSpec>) {
+export class YggdrasilConduitServer<AppTypes extends YggdrasilAppTypes, ApiSpec extends YggdrasilConduitAPI> {
+ constructor(server: YggdrasilServer<AppTypes, ApiSpec>, api: YggdrasilConduitApiClientImpl<AppTypes, ApiSpec>) {
this.#server = server;
this.#api = api;
}
- async handleRequest(ygg: YggdrasilServerContext<AppContext>): Promise<Response> {
+ async handleRequest(ygg: YggdrasilServerContext<AppTypes>): Promise<Response> {
if (!ygg.options.conduitBasePath) throw ygg.status(500, "YGG_BADLY_CONFIGURED", "conduitBasePath must be configured to use Yggdrasil Server Conduit.");
let requestedPath = ygg.pathname.requested.replace(ygg.options.conduitBasePath, "");
if (!ygg.pathname.requested.startsWith(ygg.options.conduitBasePath) || (requestedPath === "/") || requestedPath.endsWith("/")) throw ygg.status(404, "YGG_API_NOT_FOUND", "The requested API can't be located.");
- let requestedApiSegment = this.#api as APISegment<AppContext, ApiSpec>;
- let requestedApi: YggdrasilConduitAPIHandler<AppContext, ApiSpec, AnyFn> | undefined;
+ let requestedApiSegment = this.#api as APISegment<AppTypes, ApiSpec>;
+ let requestedApi: YggdrasilConduitAPIHandler<AppTypes, ApiSpec, AnyFn> | undefined;
const segments = requestedPath.split("/");
for (const segment of segments) {
@@ -80,7 +80,7 @@
append: []
},
apiCtx: request.context
- } satisfies Omit<YggdrasilConduitContext<AppContext, ApiSpec>, keyof YggdrasilServerContext<AppContext>> as unknown as YggdrasilConduitContext<AppContext, ApiSpec>;
+ } satisfies Omit<YggdrasilConduitContext<AppTypes, ApiSpec>, keyof YggdrasilServerContext<AppTypes>> as unknown as YggdrasilConduitContext<AppTypes, ApiSpec>;
Object.setPrototypeOf(yggConduitCtx, ygg);
const data = await requestedApi(yggConduitCtx, ...request.parameters);
@@ -102,6 +102,6 @@
}
}
- #server: YggdrasilServer<AppContext>;
- #api: YggdrasilConduitApiClientImpl<AppContext, ApiSpec>;
+ #server: YggdrasilServer<AppTypes>;
+ #api: YggdrasilConduitApiClientImpl<AppTypes, ApiSpec>;
};
\ No newline at end of file
diff --git a/yggdrasil/src/YggdrasilRouter.ts b/yggdrasil/src/YggdrasilRouter.ts
index af2f3a5..2a77ef0 100644
--- a/yggdrasil/src/YggdrasilRouter.ts
+++ b/yggdrasil/src/YggdrasilRouter.ts
@@ -2,27 +2,27 @@
// Copyright (c) jottocraft 2024
import { YggdrasilRouterContext, YggdrasilServerContext } from "~/context";
-import { YggdrasilServer } from "~/YggdrasilServer";
+import { YggdrasilAppTypes, YggdrasilServer } from "~/YggdrasilServer";
/**
* An object that represents the route configuration made by YggdrasilServer.defineRoute().
*/
-export type YggdrasilRouteConfig<AppContext> = {
+export type YggdrasilRouteConfig<AppTypes extends YggdrasilAppTypes> = {
method: string;
route: string;
- handler: YggdrasilRouterHandler<AppContext>;
+ handler: YggdrasilRouterHandler<AppTypes>;
};
/**
* The structure used internally for storing and matching registered routes.
*/
-type RegisteredRoutes<AppContext> = {
+type RegisteredRoutes<AppTypes extends YggdrasilAppTypes> = {
param?: string;
handlers?: {
- [method: string]: YggdrasilRouterHandler<AppContext>;
+ [method: string]: YggdrasilRouterHandler<AppTypes>;
};
children: {
- [segment: string]: RegisteredRoutes<AppContext>;
+ [segment: string]: RegisteredRoutes<AppTypes>;
};
};
@@ -34,13 +34,13 @@
/**
* A function that handles a request made to a YggdrasilRouter route.
*/
-export type YggdrasilRouterHandler<AppContext> = (ygg: YggdrasilRouterContext<AppContext>) => Promise<Response>;
+export type YggdrasilRouterHandler<AppTypes extends YggdrasilAppTypes> = (ygg: YggdrasilRouterContext<AppTypes>) => Promise<Response>;
/**
* A server for routing requests made to YggdrasilServer.
*/
-export class YggdrasilRouter<AppContext> {
- constructor(server: YggdrasilServer<AppContext>, routes: { [key: string]: YggdrasilRouteConfig<AppContext>; }) {
+export class YggdrasilRouter<AppTypes extends YggdrasilAppTypes> {
+ constructor(server: YggdrasilServer<AppTypes>, routes: { [key: string]: YggdrasilRouteConfig<AppTypes>; }) {
this.#server = server;
for (const route of Object.values(routes)) {
@@ -62,7 +62,7 @@
}
}
- async handleRequest(ygg: YggdrasilServerContext<AppContext>): Promise<Response> {
+ async handleRequest(ygg: YggdrasilServerContext<AppTypes>): Promise<Response> {
let requestedPath = this.#registeredRoutes;
const params: YggdrasilRouterRequestParams = {};
@@ -79,7 +79,7 @@
}
if (requestedPath.handlers) {
- const yggRouterCtx = { params } as YggdrasilRouterContext<AppContext>;
+ const yggRouterCtx = { params } as YggdrasilRouterContext<AppTypes>;
Object.setPrototypeOf(yggRouterCtx, ygg);
if (requestedPath.handlers[ygg.request.method]) {
@@ -94,6 +94,6 @@
}
}
- #server: YggdrasilServer<AppContext>;
- #registeredRoutes: RegisteredRoutes<AppContext> = { children: {} };
+ #server: YggdrasilServer<AppTypes>;
+ #registeredRoutes: RegisteredRoutes<AppTypes> = { children: {} };
};
\ No newline at end of file
diff --git a/yggdrasil/src/YggdrasilServer.ts b/yggdrasil/src/YggdrasilServer.ts
index 2cbd909..67b40cb 100644
--- a/yggdrasil/src/YggdrasilServer.ts
+++ b/yggdrasil/src/YggdrasilServer.ts
@@ -11,27 +11,41 @@
import { YggdrasilConduitAPI } from "~/conduitClient";
/**
+ * Defines the app's context, memoization tasks, and more in one type.
+ */
+export type YggdrasilAppTypes = {
+ ctx: any;
+};
+
+/**
+ * Memoized functions.
+ */
+export type YggdrasilMemoizedFunctions = {
+ [fn: string]: (...args: any[]) => Promise<any>;
+};
+
+/**
* A function that handles a request made to Yggdrasil Server.
*/
-export type YggdrasilHandler<AppContext> = (ygg: YggdrasilServerContext<AppContext>) => Promise<Response>;
+export type YggdrasilHandler<AppTypes extends YggdrasilAppTypes> = (ygg: YggdrasilServerContext<AppTypes>) => Promise<Response>;
/**
* The main class for processing requests.
*/
-export class YggdrasilServer<AppContext, ApiSpec extends YggdrasilConduitAPI<any, any> = YggdrasilConduitAPI<unknown, unknown>> {
+export class YggdrasilServer<AppTypes extends YggdrasilAppTypes, ApiSpec extends YggdrasilConduitAPI = { client: unknown; context: unknown; }> {
constructor() { }
/**
* Defines a route to use with YggdrasilRouter.
*/
- defineRoute(method: string, route: string, handler: YggdrasilRouterHandler<AppContext>): YggdrasilRouteConfig<AppContext> {
+ defineRoute(method: string, route: string, handler: YggdrasilRouterHandler<AppTypes>): YggdrasilRouteConfig<AppTypes> {
return { method, route, handler };
}
/**
* Defines an API to use with YggdrasilConduitServer.
*/
- defineAPI(): YggdrasilConduitApiClientBlueprint<AppContext, ApiSpec> {
+ defineAPI(): YggdrasilConduitApiClientBlueprint<AppTypes, ApiSpec> {
const implProxy = new Proxy((impl: unknown) => impl, {
get: (target, name) => {
return implProxy;
@@ -44,7 +58,7 @@
/**
* Handles a request.
*/
- async handleRequest(request: Request, handler: YggdrasilHandler<AppContext>, ctx: AppContext, options: YggdrasilServerContextOptions<AppContext> = {}): Promise<Response> {
+ async handleRequest(request: Request, handler: YggdrasilHandler<AppTypes>, app: { ctx: AppTypes["ctx"] }, options: YggdrasilServerContextOptions<AppTypes> = {}): Promise<Response> {
const url = new URL(request.url);
const baseURL = options.baseURL ? new URL(options.baseURL) : undefined;
@@ -78,7 +92,9 @@
relativePath = normalizedPath;
}
- const ygg: YggdrasilServerContext<AppContext> = {
+ const memoizedResults: { [key: string]: { resolved: false; dispatcher: EventTarget; } | { resolved: true; outcome: unknown; }; } = {};
+
+ const ygg: YggdrasilServerContext<AppTypes> = {
status(...args) {
return new YggdrasilStatus(this, ...args);
},
@@ -100,17 +116,17 @@
},
baseURL,
get ctx() {
- const boundCtx: AppContext = {} as AppContext;
+ const boundCtx: AppTypes["ctx"] = {} as AppTypes["ctx"];
- for (const key in ctx) {
- if (typeof ctx[key] === "function") {
- boundCtx[key] = ctx[key].bind(this);
+ for (const key in app.ctx) {
+ if (typeof app.ctx[key] === "function") {
+ boundCtx[key] = app.ctx[key].bind(this);
} else {
- boundCtx[key] = ctx[key];
+ boundCtx[key] = app.ctx[key];
}
}
-
- return boundCtx;
+
+ return boundCtx;
},
options,
additionalHeaders: {
@@ -118,6 +134,41 @@
append: [
["X-Powered-By", "@jottocraft/yggdrasil"]
]
+ },
+ memoize: async <T>(key: string, task: () => Promise<T>) => {
+ const result = memoizedResults[key];
+ if (result) {
+ if (result.resolved) {
+ return result.outcome as T;
+ } else {
+ return await new Promise((resolve, reject) => {
+ result.dispatcher.addEventListener("resolved", () => {
+ const resolvedOutcome = memoizedResults[key];
+ if (!resolvedOutcome.resolved) {
+ reject(new Error("A resolved event was illegally fired before the memoized outcome was set."));
+ } else {
+ resolve(resolvedOutcome.outcome as any); // I have no idea why "as T" doesn't work here.
+ }
+ });
+ });
+ }
+ } else {
+ const dispatcher = new EventTarget();
+ memoizedResults[key] = {
+ resolved: false,
+ dispatcher
+ };
+
+ const outcome = await task();
+ memoizedResults[key] = {
+ resolved: true,
+ outcome
+ };
+
+ dispatcher.dispatchEvent(new CustomEvent("resolved"));
+
+ return outcome;
+ }
}
};
diff --git a/yggdrasil/src/YggdrasilStatus.ts b/yggdrasil/src/YggdrasilStatus.ts
index f36329f..8aa7eb0 100644
--- a/yggdrasil/src/YggdrasilStatus.ts
+++ b/yggdrasil/src/YggdrasilStatus.ts
@@ -2,6 +2,7 @@
// Copyright (c) jottocraft 2024
import { YggdrasilContext } from "~/context";
+import { YggdrasilAppTypes } from "~/YggdrasilServer";
/**
* YggdrasilStatus for clients without a server-side YggdrasilContext
@@ -34,14 +35,14 @@
/**
* An Error that will cause an HTTP status page to show.
*/
-export class YggdrasilStatus<AppContext> extends YggdrasilClientStatus {
- constructor(ygg: YggdrasilContext<AppContext>, status: number, statusCode: string, statusMessage?: string) {
+export class YggdrasilStatus<AppTypes extends YggdrasilAppTypes> extends YggdrasilClientStatus {
+ constructor(ygg: YggdrasilContext<AppTypes>, status: number, statusCode: string, statusMessage?: string) {
super(status, statusCode, statusMessage);
this.#ygg = ygg;
}
- #ygg: YggdrasilContext<AppContext>;
+ #ygg: YggdrasilContext<AppTypes>;
get ygg() {
return this.#ygg;
}
diff --git a/yggdrasil/src/conduitClient.ts b/yggdrasil/src/conduitClient.ts
index 6e51c5c..a1d4dbe 100644
--- a/yggdrasil/src/conduitClient.ts
+++ b/yggdrasil/src/conduitClient.ts
@@ -3,18 +3,19 @@
import { YggdrasilContext } from "~/context";
import { YggdrasilClientStatus } from "~/YggdrasilStatus";
+import { YggdrasilAppTypes } from "~/YggdrasilServer";
-export type YggdrasilConduitAPI<ApiClient, ApiCtx> = {
- client: ApiClient;
- context: ApiCtx;
+export type YggdrasilConduitAPI = {
+ client: any;
+ context: any;
};
// TODO: For now, the fact that YggdrasilConduitAPIClient requires the "this" context to be
// of type YggdrasilContext is hidden. This is because it is difficult to redefine with
// "this" set since YggdrasilContext and YggdrasilConduitAPIClient would both depend on each other.
-export type YggdrasilConduitAPIClient<ApiSpec extends YggdrasilConduitAPI<any, any>> = () => ApiSpec["client"];
-export type YggdrasilConduitAPIContext<ApiSpec extends YggdrasilConduitAPI<any, any>> = ApiSpec["context"];
+export type YggdrasilConduitAPIClient<ApiSpec extends YggdrasilConduitAPI> = () => ApiSpec["client"];
+export type YggdrasilConduitAPIContext<ApiSpec extends YggdrasilConduitAPI> = ApiSpec["context"];
export type YggdrasilConduitRequest<ApiCtx, T extends unknown[]> = {
parameters: T;
@@ -43,7 +44,7 @@
message?: string;
debug?: {
stack?: string;
- ygg?: Pick<YggdrasilContext<unknown>, "url" | "pathname" | "baseURL" | "additionalHeaders">;
+ ygg?: Pick<YggdrasilContext<YggdrasilAppTypes>, "url" | "pathname" | "baseURL" | "additionalHeaders">;
};
};
@@ -58,7 +59,7 @@
baseURL: string;
};
-async function doConduitRequest<ApiSpec extends YggdrasilConduitAPI<any, any>>(path: string[], args: unknown[], apiCtx: ApiSpec["context"], options: YggdrasilConduitClientOptions): Promise<{
+async function doConduitRequest<ApiSpec extends YggdrasilConduitAPI>(path: string[], args: unknown[], apiCtx: ApiSpec["context"], options: YggdrasilConduitClientOptions): Promise<{
response: Response;
outcome: YggdrasilConduitResponse<unknown>;
}> {
@@ -93,8 +94,8 @@
/**
* Creates a client for calling Yggdrasil Server Conduit-powered APIs from another Yggdrasil Server-powered web or API server.
*/
-export function createConduitServerSideClient<ApiSpec extends YggdrasilConduitAPI<any, any>>(apiCtx: ApiSpec["context"], options: YggdrasilConduitClientOptions): YggdrasilConduitAPIClient<ApiSpec> {
- return function conduitServerSideClient(this: YggdrasilContext<unknown>): ApiSpec["client"] {
+export function createConduitServerSideClient<ApiSpec extends YggdrasilConduitAPI>(apiCtx: ApiSpec["context"], options: YggdrasilConduitClientOptions): YggdrasilConduitAPIClient<ApiSpec> {
+ return function conduitServerSideClient(this: YggdrasilContext<YggdrasilAppTypes>): ApiSpec["client"] {
const createAppFn = (path: string[]) => {
return new Proxy(async (...args: unknown[]) => {
const { response, outcome } = await doConduitRequest(path, args, apiCtx, options);
@@ -129,7 +130,7 @@
/**
* Creates a client for calling Yggdrasil Server Conduit-powered APIs from a client application.
*/
-export function createConduitClientSideClient<ApiSpec extends YggdrasilConduitAPI<any, any>>(apiCtx: ApiSpec["context"], options: YggdrasilConduitClientOptions): YggdrasilConduitAPIClient<ApiSpec> {
+export function createConduitClientSideClient<ApiSpec extends YggdrasilConduitAPI>(apiCtx: ApiSpec["context"], options: YggdrasilConduitClientOptions): YggdrasilConduitAPIClient<ApiSpec> {
const createAppFn = (path: string[]) => {
return new Proxy(async (...args: unknown[]) => {
const { response, outcome } = await doConduitRequest(path, args, apiCtx, options);
diff --git a/yggdrasil/src/context.ts b/yggdrasil/src/context.ts
index c09d083..e9bdb21 100644
--- a/yggdrasil/src/context.ts
+++ b/yggdrasil/src/context.ts
@@ -3,10 +3,10 @@
import { YggdrasilAdditionalHeaders, YggdrasilConduitAPI, YggdrasilConduitAPIContext } from "~/conduitClient";
import { YggdrasilRouterRequestParams } from "~/YggdrasilRouter";
-import { YggdrasilServer } from "~/YggdrasilServer";
+import { YggdrasilAppTypes, YggdrasilServer } from "~/YggdrasilServer";
import { YggdrasilStatus } from "~/YggdrasilStatus";
-export type YggdrasilServerContextOptions<AppContext> = {
+export type YggdrasilServerContextOptions<AppTypes extends YggdrasilAppTypes> = {
/** True if debug information should be returned on the status pages. */
debug?: boolean;
/**
@@ -33,18 +33,18 @@
redirect?: boolean;
};
/** A function you can implement to generate HTML status pages for a given YggdrasilStatus object. By default, a plaintext status page will be shown. */
- generateHtmlStatusPage?: (e: YggdrasilStatus<AppContext>) => Promise<Response>;
+ generateHtmlStatusPage?: (e: YggdrasilStatus<AppTypes>) => Promise<Response>;
};
-export type YggdrasilContext<AppContext> = YggdrasilServerContext<AppContext> | YggdrasilRouterContext<AppContext> | YggdrasilConduitContext<AppContext, YggdrasilConduitAPI<unknown, unknown>>;
+export type YggdrasilContext<AppTypes extends YggdrasilAppTypes> = YggdrasilServerContext<AppTypes> | YggdrasilRouterContext<AppTypes> | YggdrasilConduitContext<AppTypes, { client: unknown; context: unknown; }>;
-export type YggdrasilServerContext<AppContext> = {
+export type YggdrasilServerContext<AppTypes extends YggdrasilAppTypes> = {
/** Constructs a YggdrasilStatus object based on the current context. */
- status: (status: number, statusCode: string, statusMessage?: string) => YggdrasilStatus<AppContext>;
+ status: (status: number, statusCode: string, statusMessage?: string) => YggdrasilStatus<AppTypes>;
/** Throws a YggdrasilStatus if the condition isn't met. */
assert: (condition: any, status: number, statusCode: string, statusMessage?: string) => asserts condition;
/** The Yggdrasil Server instance associated with this request. */
- server: YggdrasilServer<AppContext>;
+ server: YggdrasilServer<AppTypes>;
/** The original request. */
request: Request;
/** The requested and normalized URLs. */
@@ -61,19 +61,21 @@
/** This server's base URL. */
baseURL?: URL;
/** Custom app context associated with this request. */
- ctx: AppContext;
+ ctx: AppTypes["ctx"];
/** Yggdrasil Server options. */
- options: YggdrasilServerContextOptions<AppContext>;
+ options: YggdrasilServerContextOptions<AppTypes>;
/** Headers that will be set/appended to the final response. */
additionalHeaders: YggdrasilAdditionalHeaders;
+ /** Memoizes the result. */
+ memoize: <T>(key: string, task: () => Promise<T>) => Promise<T>;
};
-export type YggdrasilRouterContext<AppContext> = YggdrasilServerContext<AppContext> & {
+export type YggdrasilRouterContext<AppTypes extends YggdrasilAppTypes> = YggdrasilServerContext<AppTypes> & {
/** The parameters set by variable segments in the router's path. */
params: YggdrasilRouterRequestParams;
};
-export type YggdrasilConduitContext<AppContext, ApiSpec extends YggdrasilConduitAPI<any, any>> = YggdrasilServerContext<AppContext> & {
+export type YggdrasilConduitContext<AppTypes extends YggdrasilAppTypes, ApiSpec extends YggdrasilConduitAPI> = YggdrasilServerContext<AppTypes> & {
/** Headers that will be set/appended to the highest-level upstream request. */
upstreamHeaders: YggdrasilAdditionalHeaders;
/** Context from the Conduit request. */
diff --git a/yggdrasil/src/util/generateStatusPage.ts b/yggdrasil/src/util/generateStatusPage.ts
index 89f287c..6304c80 100644
--- a/yggdrasil/src/util/generateStatusPage.ts
+++ b/yggdrasil/src/util/generateStatusPage.ts
@@ -2,9 +2,10 @@
// Copyright (c) jottocraft 2024
import { YggdrasilConduitResponseError } from "~/conduitClient";
+import { YggdrasilAppTypes } from "~/YggdrasilServer";
import { YggdrasilStatus } from "~/YggdrasilStatus";
-export async function generateStatusPage<AppContext>(e: YggdrasilStatus<AppContext>): Promise<Response> {
+export async function generateStatusPage<AppTypes extends YggdrasilAppTypes>(e: YggdrasilStatus<AppTypes>): Promise<Response> {
const accept = e.ygg?.request.headers.get("Accept");
if (accept === "application/json+jottocraft-ygg-res") {
@@ -18,7 +19,7 @@
}
}
-async function generateConduitErrorPage<AppContext>(e: YggdrasilStatus<AppContext>): Promise<Response> {
+async function generateConduitErrorPage<AppTypes extends YggdrasilAppTypes>(e: YggdrasilStatus<AppTypes>): Promise<Response> {
const result: YggdrasilConduitResponseError = {
success: false,
error: e.statusCode,
@@ -46,7 +47,7 @@
});
}
-async function generateJsonStatusPage<AppContext>(e: YggdrasilStatus<AppContext>): Promise<Response> {
+async function generateJsonStatusPage<AppTypes extends YggdrasilAppTypes>(e: YggdrasilStatus<AppTypes>): Promise<Response> {
return new Response(JSON.stringify({
success: false,
status: e.status,
@@ -60,7 +61,7 @@
});
}
-async function generatePlaintextStatusPage<AppContext>(e: YggdrasilStatus<AppContext>): Promise<Response> {
+async function generatePlaintextStatusPage<AppTypes extends YggdrasilAppTypes>(e: YggdrasilStatus<AppTypes>): Promise<Response> {
return new Response(`Error ${e.status} ${e.statusCode}${e.statusMessage ? ": " + e.statusMessage : ""}`, {
status: e.status,
headers: {