npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@fakehost/state-emitter

v1.0.0-beta.2

Published

Create a state emitter for CRUD event fake services

Downloads

1

Readme

@fakehost/state-emitter

Useful pattern for building fakes that have a collection of items, especially for endpoints that notify of CRUD events to the collection.

Example Usage

type Entity = {
    orderId: bigint,
    payload: {
        name: string
    }
}

const state = createEntityState<Entity>()
    // the property that is the unique identifier for the object. Accepts dot notation e.g. "payload.id":
    .idField('orderId') 
    // factory methods for creating new items:
    .entityFactory(createEntity)
    // how to generate the next id (numberGenerator (1, 2, ...), bigintGenerator (1n, 2n, ...), uuidLikeGenerator are supplied):
    .nextIdFactory(bigintGenerator())
    // how many to create initially:
    .initialState({ count: 2 })
    // create "1" new entity every "10_000"ms. See [Generate](#generate).
    .generate(10_000, { create: 1 })
    // generate the state object:
    .build()

The state object then has the following methods & properties:

  • get(id): T | undefined: get the entity with the id.
  • getAll(): T[]: get all the entities.
  • filter(predicate): T[]: filter the entities
  • find(predicate): T | undefined: find an entity
  • create(delta?): T: create a new entity, with any possible values you need.
  • delete(id): T: delete the entity.
  • update(partialEntityWithIdField): T: updates the entity. Note, the identifier (set from idField) is required to be set.
  • reset(): void: resets the state to the initial state
  • stream$: Observable(['create' | 'update' | 'delete', T]) : stream of events from the state, notifying create, update, and delete of entities.
  • generate: See Generate.

entityFactory

import { DeepPartial } from '@fakehost/state-emitter'
import faker from '@faker-js/faker'

// ...

const createEntity = (orderId: bigint, delta: DeepPartial<Entity>): Entity => {
    // Set the faker seed. 
    // This will ensure the exact same fake data is generated for the same id
    faker.seed(Number(orderId))

    return {
        orderId,
        payload: {
            name: faker.company.companyName(),
            ...delta.payload,
        }
    }
}

Generate

Using the builder, to create 2 new entities every 1 second:

const state = createEntityState<Entity>()
    // ...
    .generate(1_000, { create: 2 })
    .build()

Or, for a fixed list (e.g. stock symbol prices we can update the prices every 0.5s)

const symbolState =  createEntityState<Symbol>()
    .initialState({ count: 100 })
    .generator(500, (state, counter) => {
        // ensure consistent sequence of changes
        faker.seed(counter)
        state.getAll().forEach(symbol => {
            // update half of prices
            if(!faker.datatype.boolean()) return
            // get the price delta, a max 1% up/down
            const delta = faker.datatype.number({
                min: symbol.price / 100 * -1,
                max: symbol.price / 100, 
                precision: 0.0001
            })
            const newPrice = symbol.price + delta
            state.update({
                ...symbol,
                price: newPrice > 0 ? newPrice : 0
            })
        })
    })

The EntityState has a generator property:

  • enabled: readonly boolean
  • stop: stop generation, it is useful in tests to not have generation happening by default.
  • start: reset any generation. By default the generator will be running.
  • set(interval: number, fn: (state: EntityState) => void): set a new function to generate.

License

@fakehost/state-emitter is licensed under the MIT License.