Wormhole
TypeScript library for handle backend state between middlewares in Express / Express-based frameworks using Request object
Installation
npm install @iipekolict/wormhole
Usage
Configuring dynamic wormhole based on initial state object (highly recommended)
import { WormholeService, DynamicWormholeClass } from '@iipekolict/wormhole';
type State = {
todos: object[];
posts: object[];
missing?: boolean;
};
const state: State = {
todos: [],
posts: [],
};
const Wormhole: DynamicWormholeClass<State> = WormholeService.create(state);
Then use it inside middlewares and endpoints for set / get state fields
import { WormholeService, DynamicWormhole, DynamicWormholeClass } from '@iipekolict/wormhole';
import express, { Request, Response, NextFunction } from 'express';
import { fetchTodos } from 'project'
const app = express();
app.use(async (request: Request, response: Response, next: NextFunction) => {
const wormhole: DynamicWormhole<State> = new Wormhole(request);
const todos: object[] = await fetchTodos();
wormhole.set({ todos });
wormhole.setTodos(todos);
next();
});
app.use(async (request: Request, response: Response, next: NextFunction) => {
const wormhole: DynamicWormhole<State> = new Wormhole(request);
console.log(wormhole.get('todos'));
console.log(wormhole.getTodos());
console.log(wormhole.get('posts'));
console.log(wormhole.getPosts());
next();
});
app.get('/', async (request: Request, response: Response, next: NextFunction) => {
const wormhole: DynamicWormhole<State> = WormholeService.getInstance<State>(request);
console.log(wormhole.get('missing'));
response.json({ todos: wormhole.getTodos() });
});
app.listen(5000);
Creating custom setter
const wormhole: DynamicWormhole<State> = new Wormhole(request);
const setter = wormhole.createSetter((state: State, todo: object) => {
return { todos: [...state.todos, todo] };
});
setter({ text: 'some text' });
Creating custom spread setter
const wormhole: DynamicWormhole<State> = new Wormhole(request);
const spreadSetter = wormhole.createSpreadSetter((state: State, ...posts: Post[]) => {
return { posts: [...state.posts, ...posts] };
});
spreadSetter({ text: 'some text' }, { text: 'another text' });
Examples
Express