1.0.6 • Published 12 months ago

@iipekolict/wormhole v1.0.6

Weekly downloads
-
License
MIT
Repository
github
Last release
12 months ago

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;
};

// initial state object
const state: State = {
  todos: [],
  posts: [],
};

// create dynamic wormhole class with utility methods based on initial state object
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'

// ...previous example

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 }); // set todos field in backend state
  wormhole.setTodos(todos); // same as previous, method generates dynamically based on initial state object
  next();
});

app.use(async (request: Request, response: Response, next: NextFunction) => {
  const wormhole: DynamicWormhole<State> = new Wormhole(request);
  
  console.log(wormhole.get('todos')); // [...todos]
  console.log(wormhole.getTodos()); // [...todos]
  console.log(wormhole.get('posts')); // []
  console.log(wormhole.getPosts()); // []
  
  next();
});

app.get('/', async (request: Request, response: Response, next: NextFunction) => {
  // wormhole factory, same as new Wormhole()
  const wormhole: DynamicWormhole<State> = WormholeService.getInstance<State>(request);
  
  console.log(wormhole.get('missing')); // undefined
  
  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

1.0.6

12 months ago

1.0.5

1 year ago

1.0.4

1 year ago

1.0.3

1 year ago

1.0.2

1 year ago

1.0.1

1 year ago