A projection model represents a typesafe state and individual (possibly unique) projections on top of that state, including the corresponding actions that can be taken to alter the original state and trigger updates on the projections. The projections are updated through patches, which are deltas between the previous projection and the new projection.

The projection also support optimistic updates, which are updates that are applied to the projection before the server has confirmed the update to the state.

Note: Keep in mind that the projection should be safe to JSON decode and encode. Only use primitives, don't use classes, functions, or other complex types as part of your projection.

Type Parameters

  • State
  • Projection

Constructors

Properties

actionDefinitions: ActionDefinitions<State, Projection> = {}
immutable: boolean = false
initialState: State

The initial server-side state.

projectionMapper: ((state, username) => Projection)

A function that maps the state to a projection for a specific user. This function will be called for each client whenever the state changes. The delta from the previous projection to the new projection will be sent to the client in the form of a delta.

Type declaration

    • (state, username): Projection
    • A function that maps the state to a projection for a specific user. This function will be called for each client whenever the state changes. The delta from the previous projection to the new projection will be sent to the client in the form of a delta.

      Parameters

      • state: State
      • username: string

      Returns Projection

Methods

  • Adds a new handler for when a specific type of action is dispatched.

    Type Parameters

    • Type extends string
    • PayloadSchema extends ZodType<any, any, any>

    Parameters

    • type: Type

      The identifier of the action. This must be unique for this model. For example: 'increment'

    • payloadSchema: PayloadSchema

      The Zod schema to use for the payload of the action. For example z.number().int().min(1).max(5)

    • handler: ((state, dispatcher, payload) => void | State)

      The handler that applies the payload to the state. This method receives the state, the dispatcher, and the payload.

    • Optional optimisticHandler: ((projection, dispatcher, payload) => void | Projection)

      An optional handler that immediately applies the payload to the projection. This method receives the projection, the dispatcher, and the payload.

      Note: In the handlers you can safely manipulate the state and projection objects directly. Alternatively, you can return a new object from these handlers.

    Returns PayloadSchema extends ZodUndefined
        ? (() => {
            payload: undefined;
            type: Type;
        })
        : ((payload) => {
            payload: TypeOf<PayloadSchema>;
            type: Type;
        })

    Returns a constructor for creating type safe actions for this type of action.