@emberworks/context-container
v0.0.3
Published
## Installation
Downloads
1
Readme
A simple, versatile, Typescript context container
Installation
npm install @emberworks/context-container
bun add @emberworks/context-container
Basic Usage
// --- context.ts ---
import { createContextContainer } from '@emberworks/context-container';
import { type Database } from './db';
import { type SomeService, createSomeService } from './some-service';
import { type SomeOtherService } from './some-other-service';
type Ctx = {
db: Database;
someService: SomeService;
someOtherService: SomeOtherService;
};
// Due to TS limitations we need to provide a type for the complete container
export const ctx = createContextContainer<Ctx>({
// Set context properties directly
someService: (ctx) => createSomeService(ctx, {}),
// Or dynamically
db: () => import('./db').then((mod) => mod.db),
// Even do some weird loading shit
someOtherService: (ctx) => import('./some-other-service').then(async (mod) =>
mod.createSomeOtherService(ctx, {}),
),
});
// You can optionally preload context items
await ctx.loadItems(); // To load all
await ctx.loadItems(['db', 'someService']) // To load some
// --- some-other-service.ts ---
import { type ContextContainer } from '@emberworks/context-container';
// Define only the context that you need for the service
type Ctx = {
db: Database;
};
export const createSomeOtherService = (
ctx: ContextContainer<Ctx>,
options: {},
) => {
...
// Use the context
const db = await ctx.getItem('db');
...
};
// --- some-root-request-or-job-or-whatever-you-like-really.ts ---
import { ctx } from './context';
export const someRequestHandler = async (req: Request) => {
...
const someService = await ctx.getItem('someService');
...
}
Docs
Haven't got there yet, you'll figure it out.