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

@ably-labs/models

v0.0.4

Published

<p align="left"> <a href=""> <img src="https://badgen.net/badge/development-status/alpha/yellow?icon=github" alt="Development status" /> </a> <a href=""> <img src="https://github.com/ably-labs/models/actions/workflows/dev-ci.yml/badge.svg?

Downloads

758

Readme

Ably Models SDK



Overview

The Ably Models SDK is a key component of the LiveSync product that lets you stream realtime updates from your database at scale to frontend clients.

LiveSync Diagram

The Models SDK is a frontend library that simplifies subscribing to the changes in data models, applying optimistic updates and merging them with confirmed updates. It is a standalone SDK built on Ably’s JavaScript SDK with full TypeScript support.

The Database Connector and Ably Channels are the other two components of LiveSync that help publish changes from your database to frontend clients.

A model represents a data model of a specific part of your frontend application. Each frontend client can have multiple data models within the same application.

Models SDK Diagram

When creating a new Model using the Models SDK you provide two functions to the Model a sync() function and a merge() function:

  • The sync() function is used by the SDK to retrieve the current state of the data model from your backend.
  • The merge() function is used by the SDK to merge state change events published by the Database Connector with the existing frontend state in the Model.

You can use the Models SDK as a standalone library to merge new update events with existing frontend state, but the SDK works best as part of LiveSync.

The data models as part of the Models SDK remain synchronized with the state of your database, in realtime. You can easily integrate this SDK into your project regardless of which frontend framework you use.

Development Status

LiveSync, and the Models SDK, is in public alpha so that you can explore its capabilities. Your feedback will help prioritize improvements and fixes for later releases. The features in this release have been built to work under real-world situations and load, and for real-world use-cases, but there may still be some rough edges in this alpha.

Quickstart

Prerequisites

To begin, you will need the following:

  • An Ably account. You can sign up for free.
  • An Ably API key. You can create API keys in an app within your Ably account.

Installation and authentication

Install the Ably JavaScript SDK and the Realtime Data Models SDK:

npm install ably @ably-labs/models

Though you can test your installation and authentication with basic authentication, we strongly recommend token authentication for in production environments.

Instantiation

To instantiate the Realtime Data Models SDK, create an Ably client and pass it into the ModelsClient constructor:

import ModelsClient from '@ably-labs/models';
import { Realtime } from 'ably';

const ably = new Realtime({ key: 'YOUR_ABLY_API_KEY' });
const modelsClient = new ModelsClient({ ably });

Creating a Model

A Model represents a live, observable data model supported by the database.

To create a model, you need to:

  1. Define the model's data structure in the frontend application.
  2. Initialize the model.
  3. Update the model based on events from the backend.
  4. Determine how end-users can modify the model.
// this is the type for our model's data as represented in the frontend application
type Post = {
  id: number;
  text: string;
  comments: string[];
};

// a function used by the model to initialise with the correct data from your backend
async function sync() {
  const result = await fetch('/api/post');
  return result.json(); // e.g. { sequenceId: 1, data: { ... } }
}

// a function used by the model to merge a change event that is received and the existing model state
function merge(state: Post, event: OptimisticEvent | ConfirmedEvent) {
  return {
    ...state,
    text: event.data, // replace the previous post text field with the new value
  }
}

// a function that you might use to mutate the model data in your backend
async function updatePost(mutationId: string, content: string) {
  const result = await fetch(`/api/post`, {
    method: 'PUT',
    body: JSON.stringify({ mutationId, content }),
  });
  return result.json();
}

// create a new model instance called 'post' by passing the sync and merge functions
const model = modelsClient.models.get({
  channelName: 'models:posts',
  sync: sync,
  merge: merge,
})

// subscribe to live changes to the model data!
model.subscribe((err, post) => {
  if (err) {
    throw err;
  }
  console.log('post updated:', post);
});


// apply an optimistic update to the model
// confirmation is a promise that resolves when the optimistic update is confirmed by the backend.
// cancel is a function that can be used to cancel and rollback the optimistic update.
const [confirmation, cancel] = await model.optimistic({
    mutationId: 'my-mutation-id',
    name: 'updatePost',
    data: 'new post text',
})

// call your backend to apply the actual change
updatePost('my-mutation-id', 'new post text')

// wait for confirmation of the change from the backend
await confirmation;

For more information, see usage docs within this repository.

Documentation and examples

Feedback

The Models SDK is currently in public alpha. We'd love to hear your feedback.