Code Monkey home page Code Monkey logo

ably-labs / models Goto Github PK

View Code? Open in Web Editor NEW
4.0 11.0 1.0 2.3 MB

The Models SDK enables you to implement live, observable data models in your application. It works with Ably's Database Connector and helps merge updates with the existing state and supports optimistic updates to ensure a snappy interface.

Home Page: https://models-blush.vercel.app

License: Apache License 2.0

JavaScript 0.76% Shell 0.03% TypeScript 99.21%
frontend-web realtime realtime-synchronization pubsub realtime-database websockets

models's Introduction

Ably Realtime Data Models SDK

Development status CI status

Build collaborative, stateful applications with the Ably Realtime Data Models SDK. Backed by your database, you can define live, observable data models in your client applications. You can also render live changes to data from your database in realtime.

Models SDK Diagram

Bring your own database

Store the data displayed in your frontend application in any database you choose or the one you already use.

Collaborative by default

Concurrently render live updates made by multiple users through your database.

Optimistic events

Deliver a super-responsive user experience. Show changes instantly, bypassing the wait for a network round trip or your database to confirm mutations. The Realtime Data Models SDK confirms changes behind the scenes, manages rollbacks, and flags any errors or conflicts to your app.

Backed by Ably

The Realtime Data Models SDK uses Ably’s fast, global message distribution network to update numerous clients across different regions with the freshest database state.



Overview

The Realtime Data Models SDK simplifies syncing application state from the database to the client in realtime. It constantly displays changes made simultaneously by others, creating a reactive, realtime, multiplayer application experience.

The Realtime Data Models SDK is a JavaScript (TypeScript) library that enables you to create live and observable data models in your frontend application. These models remain synchronized with the realtime state of your database model. You can easily integrate this SDK into your project regardless of your frontend framework preference. To learn how to use the SDK in a React/Next.js application, see examples.

Your backend publishes mutation events to Ably. The Realtime Data Models SDK updates your frontend app's local state. You can also pair the SDK with Ably's Database Connector to transmit transactional change events with your database mutations.

Note: Ably's realtime messaging platform integrates with the Realtime Data Models SDK to provide a fast, reliable, scalable global distribution network with seamless recovery.

Development Status

The Models SDK is in the public alpha stage. It's designed primarily for experimental use and is currently unsuitable for production use. Your valuable feedback will help us focus on enhancements and resolve issues for upcoming versions.

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/promises';

const ably = new Realtime.Promise({ 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({
  name: 'post',
  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.

Documentation and examples

Feedback

The Models SDK is currently under development. We'd love to hear your feedback.

models's People

Contributors

andydunstall avatar dependabot[bot] avatar franrob-projects avatar kaschula avatar mschristensen avatar snikidev avatar srushtika avatar zknill avatar

Stargazers

 avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Forkers

gregholmes

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.