UNPKG

remix-utils

Version:

This package contains simple utility functions to use with [React Router](https://reactrouter.com/).

32 lines 1.33 kB
import { unstable_createContext } from "react-router"; /** * Creates a singleton middleware that creates an instance of a class and stores * it in the context. If the instance already exists in the context, it will * return the existing instance. * * @param options - Options for the singleton middleware. * @param options.Class - The class to create an instance of. * @param options.arguments - Arguments to pass to the class constructor. * @returns A tuple containing the middleware function and a function to get the * singleton instance from the context. */ export function unstable_createSingletonMiddleware(options) { let singletonContext = unstable_createContext(null); return [ async function singletonMiddleware({ context }, next) { let instance = context.get(singletonContext); if (instance) return await next(); instance = new options.Class(...options.arguments); context.set(singletonContext, instance); return await next(); }, function getSingletonInstance(context) { let instance = context.get(singletonContext); if (!instance) throw new Error("Singleton instance not found"); return instance; }, ]; } //# sourceMappingURL=singleton.js.map