fresh
fresh copied to clipboard
document server initialization step
It turns out something that is fairly difficult to set up in sveltekit its pretty easy to add in fresh. I am referring to having an explicit server initialization step (e.g. connect to databases, pull down assets, etc). It looks like this:
main.ts:
/// <reference no-default-lib="true" />
/// <reference lib="dom" />
/// <reference lib="dom.asynciterable" />
/// <reference lib="deno.ns" />
/// <reference lib="deno.unstable" />
import { start } from "$fresh/server.ts";
import manifest from "./fresh.gen.ts";
import { Context } from './routes/_middleware.ts'
await Context.init()
await start(manifest);
routes/_middleware.ts:
import { MiddlewareHandlerContext } from "$fresh/server.ts";
import { Database } from '../database.ts'
export interface State {
context: Context
}
export class Context {
private static context: Context
public constructor() {
this.database = new Database('sqlite.db')
}
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<State>,
) {
ctx.state.context = Context.instance()
const resp = await ctx.next();
return resp;
}
I can see this being useful for a lot of devs, since setup steps are pretty universal to fullstack apps. Imo its probably worth documenting.
That makes sense. @dsherret, I think you were looking for some documentation on this too, right?
I'd be happy to merge a PR that adds a doc page for this pattern.