Developers · Gallery

Gallery

Store images as blobs and keep a reference to each one in a collection. With blobPolicy: 'lazy', a device syncs the photo records first and downloads image bytes only when it shows them.

// store.ts
import { CloudStore } from '@civility/cloud'
import { IDBBlobStorage, IDBStorage } from '@civility/cloud/storage/idb'

const APP_ID = 'app-k3m7q2x4p6w5z7n3b2v4c6h5' // from `civ id`

type Photo = { caption: string; hash: string; mime: string; size: number }

export const cloud = new CloudStore({
  id: APP_ID,
  storage: { db: new IDBStorage(), blobs: new IDBBlobStorage() },
  collections: ['photos'],
  versions: [{
    version: '1.0.0',
    schema: { type: 'object', properties: { photos: { type: 'object' } } },
  }],
  cloud: { appId: APP_ID, blobPolicy: 'lazy' },
})

export const photos = cloud.collection<Photo>('photos')

export async function addPhoto(file: File, caption: string) {
  // Returns 'sha256:<hex>'. The same bytes are stored once.
  const hash = await cloud.blobs.byteStore.put(file, file.type)
  await photos.set(crypto.randomUUID(), {
    caption,
    hash,
    mime: file.type,
    size: file.size,
  })
}

Show an image

cloud.blob(hash) returns the local copy, or downloads it from the server if this device does not have it.

async function photoUrl(photo: Photo): Promise<string> {
  const blob = await cloud.blob(photo.hash)
  return URL.createObjectURL(blob)
}

Call URL.revokeObjectURL when you remove the image. cloud.blob reads local bytes without a connection. It throws if the blob is not local and the store is not signed in.

If your app has a service worker, the blob proxy lets you write <img src="/blob/<hash>"> instead.

Free space

  • cloud.evictBlob(hash) deletes the local copy of a blob the server has.
  • cloud.compactBlobs() deletes local blobs that no record references, such as images of deleted photos.

Next: AI import