laval
TypeScript icon, indicating that this package has built-in type declarations

1.4.9 • Public • Published

⚠️ License: Licensed under CC BY-NC 4.0 become a Sponsor to get licensed for commercial use.

laval

laval

Demo npm

Offline-enabled Storage Interface for the Web with IndexedDB & GraphQL.

  • 🔌 & Play
  • Works offline
  • async / await
  • Uses indexedDB and GraphQL
  • Generates GraphQL queries from schema
  • Integration for Hasura available

Installation

npm i laval

Usage

Create a store to read and store data on multiple tables.

import { create, Model } from 'laval'

const bookModel: Model[] = [{ name: 'book' }]

const store = await create<'book'>(bookModel, {
  url: 'http://localhost:3000/graphql',
})

await store.book.insert({ id: '0', name: 'Some book' })
await store.book.list() // => { local: [{ id: '0', name: 'Some book' }], server: Promise<any> }
await store.book.update({ id: '0', name: 'Renamed book' })
await store.book.get({ id: '0' }) // => { local: { id: '0', name: 'Renamed book' }, server: Promise<any> }
await store.book.remove({ id: '0' })
await store.book.list() // => { local: [], server: Promise<any> }

Methods

For each model the store provides a number of methods to work with the data.

const { local, server } = await store.book.list()
expect(local[0].name).toBe('laval')
const serverData = await server
expect(local[0].name).toBe('laval')

list()

Returns all items.

get({ id: number | string })

Returns a single item, will return local result if found.

insert(item)

Inserts a new item. If no id is provided one will be generated randomly for local insert and once the id from the server is known the local id will be replaced.

update({ id: number | string, ... })

Updates an item identified through it's id which is required.

remove({ id: number | string })

Removes an item identified through it's id.

Model Definition

Each table requires a model definition. The model consists mainly of a name from which it is the referenced on the store.

import { create, Model } from 'laval'

const multipleModels: Model[] = [{ name: 'book' }, { name: 'car' }, { name: 'phone' }]

const store = await create<'book' | 'car' | 'phone'>(multipleModels, { ... })

Each model can be customized according to the context of the application.

import { Model } from 'laval'
import { hasura } from 'laval/hasura'

const customModel: Model = {
  // The name of the model, this will also be the name of the indexedDB table.
  name: 'book',
  // Allow subscription to server side updates from actions on a model, default "false".
  canSubscribe: true,
  // An existing GraphQL integration or a custom integration, configurable for each model.
  integration: hasura,
  // Cache duration until table will be syned with server before modification or read.
  // close => until tab is closed with beforeunload
  // number => minutes
  cache: 'forever' | 'close' | 60,
  // Fail server requests when offline, instead of queueing for later, default "false".
  requiresNetwork: boolean,
}

Offline Usage

Data is persisted first locally in an indexedDB called laval and then to a GraphQL based external database. Calling a method on the store will immediately apply the changes to the client database in the browser. The data from this operation is returned as local and can be further used (i.e. to access the generated id). The data will only be persisted to the server when the server promise is invoked.

import { nestable } from 'epic-mobx'

const myBooks = nestable<string, { id: string; name: string }>([])

const { local, server } = await store.book.list()
myBooks.replace(local) // First add local data to the store used for rendering the UI.
const serverData = await server
if (serverData !== 'offline') {
  myBooks.replace(serverData) // Update state with up-to-date data from server.
}

In this case we want the UI immediately to render the locally stored data if any is available and replace it with the server data as soon as it arrives. Even if the user is currently offline we still want to replace the state with the data from the server as soon as the user is back online.

const { local, server } = await store.book.update({ id: '1', name: 'Offline Book' })
myBooks[0].name = local.name // Update state once persisted locally to reflect changes in UI.
const serverData = await server
if (serverData !== 'offline') {
  myBooks[0].updated_at = serverData.updated_at // updated_at property is generated only on the server, name doesn't change.
}

When canSubscribe: true is set on the model, it's possible to subscribe to server updates on the model. subscribe will also receive updates that already occurred before the method was called.

store.book.subscribe(Method.list, (data) => myBooks.replace(data))
store.book.subscribe(Method.get, (data) => myBooks.byId(data.id).update(data))
store.book.subscribe(Method.insert, (data) => myBooks.extend(data))
store.book.subscribe(Method.update, (data) => myBooks.byId(data.id).update(data))
store.book.subscribe(Method.remove, (data) => myBooks.byId(data.id).remove())

Integration

To match the queries with the one's provided by the GraphQL server you can use existing integrations or create your own to match the GraphQL API.

Hasura

If the GraphQL server provides an introspection schema to download (usually not the case for production environments) the client will automatically download it.

import { hasura } from 'laval/hasura'

const store = await create<'book'>(singleModel, {
  url: 'http://localhost:8080/v1/graphql',
  integration: hasura,
})

For production use the schema can also be added to the bundle and passed directly:

import { hasura } from 'laval/hasura'

const schema = { types: [...] }

const store = await create<'book'>(singleModel, {
  url: 'http://localhost:8080/v1/graphql',
  integration: hasura,
  schema,
})

Custom

import { Method } from 'laval'

export const myIntegration = {
  [Method.list]: {
    name: 'PLURAL',
  },
  [Method.get]: {
    name: 'SINGULAR',
    root: 'query_root',
    variables: {
      where: (data) => ({
        id: {
          _eq: data.id,
        },
      }),
    },
  },
  [Method.insert]: {
    name: 'insert_PLURAL',
    root: 'mutation_root',
  },
  [Method.update]: {
    name: 'updateSINGULAR',
    variables: {
      _set: (data) => ({ ...data, id: undefined }),
    },
  },
  [Method.remove]: {
    name: 'delete_SINGULAR',
  },
}

and then pass your integration to the client just like an existing integration.

Concept

Each store has five methods: list, get, insert, update and remove. Every method consists of two stages first the method is applied locally to the client database (usually IndexedDB) and afterwards the same method is applied to the server (usually GraphQL). Depending on the network and the cache configuration of the model the method will return either the local or the server result. The local operation will always be applied immediately while the server method may be deferred while still updating the local database afterwards to match the server state.

list

Contact server immediately if: online or cache outdated

Dependencies for server request: insert, update, remove

get

Contact server immediately if: not found locally or cache outdated

Dependencies for server request: insert, update, remove

insert

Contact server immediately if: never

In case deferred server request returns an error the local insert should be updated with the get-Method.

Dependencies for server request: insert, (update), remove

update

Contact server immediately if: not found locally

Dependencies for server request: insert, (update), remove

remove

Contact server immediately if: not found locally (only return error if also missing on server)

Dependencies for server request: insert

Development Notes

At least for tests @apollo/client requires react installed. Check GitHub action for documentation to start Hasura server with Docker on localhost:8080. Some tests and demo will not work without. To reseed an empty database run npx hasura migrate apply --up 1. Avoid npx hasura seed apply as it will use the seed file that's not used during initialization and isn't up to date.

Readme

Keywords

none

Package Sidebar

Install

npm i laval

Weekly Downloads

3

Version

1.4.9

License

CC-BY-NC-4.0

Unpacked Size

38.2 kB

Total Files

24

Last publish

Collaborators

  • tobua