diff --git a/docs/examples/index.md b/docs/examples/index.md index a7b1645c..a9d81c34 100644 --- a/docs/examples/index.md +++ b/docs/examples/index.md @@ -12,3 +12,4 @@ like to see here, please open - [Setting the language](./examples/setting-the-language) - [Writing tests](./examples/writing-tests) - [Changing the source directory](./examples/changing-the-src-dir) +- [Initializing the server](./examples/init-the-server) diff --git a/docs/examples/init-the-server.md b/docs/examples/init-the-server.md new file mode 100644 index 00000000..855067c3 --- /dev/null +++ b/docs/examples/init-the-server.md @@ -0,0 +1,79 @@ +--- +description: | + For when you have some complicated setup that needs to be performed once. +--- + +Let's pretend you've just initialized a new Fresh project. You want to do some +complicated setup that runs once, before the server is started. This is, +fortunately, quite easy. Here's how: + +```diff + import { start } from "$fresh/server.ts"; + import manifest from "./fresh.gen.ts"; ++import { Context } from "./routes/_middleware.ts"; + ++await Context.init(); + await start(manifest); +``` + +So your full `main.ts` should look like this: + +```ts +/// +/// +/// +/// +/// + +import "$std/dotenv/load.ts"; + +import { start } from "$fresh/server.ts"; +import manifest from "./fresh.gen.ts"; +import { Context } from "./routes/_middleware.ts"; + +await Context.init(); +await start(manifest); +``` + +But what's going on in this new `_middleware.ts` we've created? + +```ts +import { MiddlewareHandlerContext } from "$fresh/server.ts"; + +export interface State { + context: Context; +} + +export class Context { + private static context: Context; + private complicatedStartupValue: number; + + public constructor() { + // presumably this involves connecting to a + // database or doing some heavy computation + this.complicatedStartupValue = 42; + } + + public static async init() { + Context.context = new Context(); + } + + public static instance() { + if (this.context) return this.context; + else throw new Error("Context is not initialized!"); + } +} + +export async function handler( + req: Request, + ctx: MiddlewareHandlerContext, +) { + ctx.state.context = Context.instance(); + const resp = await ctx.next(); + return resp; +} +``` + +So now in this `handler` (or any other `handler` functions you create) you can +have access to the complicated initialization step by calling +`Context.instance()`. diff --git a/docs/toc.json b/docs/toc.json index 5238120a..62dcb437 100644 --- a/docs/toc.json +++ b/docs/toc.json @@ -44,7 +44,8 @@ ["modifying-the-head", "Modifying the "], ["setting-the-language", "Setting the language"], ["writing-tests", "Writing tests"], - ["changing-the-src-dir", "Changing the source directory"] + ["changing-the-src-dir", "Changing the source directory"], + ["init-the-server", "Initializing the server"] ] } }