The entrypoint for all actions that relate to data stored by Ditto. Provides access to collections, a write transaction API, and a query hash API.

You don't create one directly but can access it from a particular Ditto instance via its store property.

Properties

attachmentFetchers: readonly AttachmentFetcher[]

All currently active attachment fetchers.

Note: Manage attachment fetchers using fetchAttachment() to start a new attachment fetch and AttachmentFetcher.stop() to cancel an existing attachment fetch.

ditto: Ditto

The Ditto instance this store belongs to.

observers: readonly StoreObserver<any, any>[]

All currently active store observers.

Note: Manage store observers using registerObserver() to register a new store observer and StoreObserver.cancel() to remove an existing store observer.

Methods

  • Returns the collection for the given name. If the collection doesn't exist yet, it will be created automatically as soon as the first entry is inserted. A collection name is valid if:

    • its length is less than 100
    • it is not empty
    • it does not contain the char '\0'
    • it does not begin with "$TS_"

    Parameters

    • name: string

    Returns Collection

  • Returns the names of all available collections in the store of the related Ditto instance.

    Returns Promise<string[]>

  • Executes a DQL query and returns matching items as a query result.

    Note: only returns results from the local store without waiting for any sync subscriptions to have caught up with the latest changes. Only use this method if your program must proceed with immediate results. Use a store observer to receive updates to query results as soon as they have been synced to this peer.

    Type Parameters

    • T = any

      The type of items returned by the query. This is a convenience type that is neither inferred from the query parameter nor validated against it.

    • U extends DQLQueryArguments = DQLQueryArguments

      The type of the query arguments

    Parameters

    • query: string

      A string containing a valid query expressed in DQL.

    • Optional queryArguments: U

      An object of values keyed by the placeholder name without the leading :. Example: { "name": "John" } for a query like SELECT * FROM people WHERE name = :name.

    Returns Promise<QueryResult<T>>

    A promise for a QueryResult containing a QueryResultItem for each match.

    Throws

    DittoError query/invalid: if query argument is not a string or not valid DQL.

    Throws

    DittoError query/arguments-invalid: if queryArguments argument is invalid (e.g. contains unsupported types).

    Throws

    DittoError may throw other errors.

  • Trigger an attachment to be downloaded locally to the device and observe its progress as it does so.

    When you encounter a document that contains an attachment, the attachment will not automatically be downloaded along with the document. You trigger an attachment to be downloaded locally to a device by calling this method. It will report events relating to the attachment fetch attempt as it tries to download it. The eventHandler block may be called multiple times with progress events. It will then be called with either a Completed event or a Deleted event. If downloading the attachment succeeds then the Completed event that the eventHandler will be called with will hold a reference to the downloaded attachment.

    The attachment to be fetched is identified by the token parameter. This may either be an AttachmentToken instance received from a Document or a plain object as is returned in a QueryResultItem (see example below).

    Parameters

    • token: AttachmentToken | {
          id: string;
          len: number | BigInt;
          metadata: AttachmentMetadata;
      }

      The AttachmentToken instance or plain object representation of the attachment to be downloaded.

    • Optional eventHandler: ((event) => void)

      An optional callback that will be called when there is an update to the status of the attachment fetch attempt.

    Returns AttachmentFetcher

    An AttachmentFetcher object, which is PromiseLike so that you can await it to wait for the attachment to be downloaded. It also provides a stop() method to cancel the fetch attempt.

    Example: Fetch an attachment from a document in the store

    // Fetch the attachment token from a document in the store
    const result = await ditto.store.execute(`
    SELECT *
    FROM COLLECTION cars (my_attachment ATTACHMENT)
    WHERE my_attachment.id = :id`,
    { id: "123" }
    )
    const attachmentToken = result.items[0].my_attachment

    // Trigger the attachment to be downloaded
    const attachment = await ditto.store.fetchAttachment(attachmentToken)

    // Extract the attachment data
    const attachmentData = await attachment.data()

    Throws

    DittoError store/attachment-not-found when the attachment could not be found.

    Throws

    DittoError store/attachment-token-invalid when the given attachment token is invalid.

    Throws

    DittoError store/failed-to-fetch-attachment when fetching the attachment fails for other reasons.

  • Creates a new Attachment object, which can then be inserted into a document.

    The file residing at the provided path will be copied into Ditto's store. The Attachment object that is returned is what you can then use to insert an attachment into a document.

    Note: Relative paths for file sources are resolved from the current working directory.

    You can provide metadata about the attachment, which will be replicated to other peers alongside the file attachment.

    Parameters

    • pathOrData: string | Uint8Array

      The path to the file that you want to create an attachment with or the raw data.

    • Optional metadata: AttachmentMetadata

      Optional metadata that will be stored alongside the attachment.

    Returns Promise<Attachment>

    A promise for an Attachment object that can be used to insert the attachment into a document.

    Example: Inserting an attachment into a document

    // Copy the file into Ditto's store and create an attachment object.
    const attachment = await ditto.store.newAttachment(
    '/path/to/my/file.pdf',
    { my_field: 'optional metadata' }
    )

    // Prepare the document value including the attachment.
    const doc = {
    _id: '123',
    my_attachment: attachment,
    other: 'some-string'
    }

    // Insert the document into the collection, marking `my_attachment` as an
    // attachment field.
    await ditto.store.execute(
    `INSERT INTO my_collection (my_attachment ATTACHMENT)
    VALUES (:doc)`,
    { doc }
    )

    Throws

    DittoError store/attachment-file-permission-denied when the file at the given path could not be read because of insufficient permissions.

    Throws

    DittoError store/attachment-file-not-found when the file at the given path could not be found.

    Throws

    DittoError store/failed-to-create-attachment when the attachment could not be created for other reasons.

    Throws

    DittoError sdk/unsupported when trying to create an attachment from a file path in a web browser.

  • Register a handler to be called whenever a query's results change in the local store.

    Convenience method, same as registerObserverWithSignalNext(), except that here, the next invocation of the observation handler is triggered automatically instead of having to call the passed in signalNext function.

    Type Parameters

    • T = any

      The type of items returned by the query. This is a convenience type that is neither inferred from the query parameter nor validated against it.

    • U extends DQLQueryArguments = DQLQueryArguments

      The type of the query arguments.

    Parameters

    • query: string

      A string containing a valid query expressed in DQL.

    • observationHandler: StoreObservationHandler<T>

      A function that is called whenever the query's results change. The function is passed a QueryResult containing a QueryResultItem for each match.

    • Optional queryArguments: U

      An object of values keyed by the placeholder name without the leading :. Example: { "name": "Joanna" } for a query like SELECT * FROM people WHERE name = :name.

    Returns StoreObserver<T, U>

    A StoreObserver that can be used to cancel the observation.

    Throws

    DittoError query/invalid: if query argument is not a string or not valid DQL.

    Throws

    DittoError query/arguments-invalid: if queryArguments argument is invalid (e.g. contains unsupported types).

    Throws

    DittoError query/unsupported: if the query is not a SELECT query.

    Throws

    DittoError may throw other errors.

  • Registers and returns a store observer for a query, configuring Ditto to trigger the passed in observation handler whenever documents in the local store change such that the result of the matching query changes. The passed in query must be a SELECT query.

    Here, a function is passed as an additional argument to the observation handler. Call this function as soon as the observation handler is ready to process the the next change event. This allows the observation handler to control how frequently it is called. See registerObserver() for a convenience method that automatically signals the next invocation.

    The first invocation of observationHandler will always happen after this method has returned.

    Type Parameters

    • T = any

      The type of items returned by the query. This is a convenience type that is neither inferred from the query parameter nor validated against it.

    • U extends DQLQueryArguments = DQLQueryArguments

      The type of the query arguments

    Parameters

    • query: string

      A string containing a valid query expressed in DQL.

    • observationHandler: StoreObservationHandlerWithSignalNext<T>

      An observation handler function that is called whenever the query's results change. The function is passed a QueryResult containing a QueryResultItem for each match.

    • Optional queryArguments: U

      An object of values keyed by the placeholder name without the leading :. Example: { "name": "Joanna" } for a query like SELECT * FROM people WHERE name = :name.

    Returns StoreObserver<T, U>

    A StoreObserver that can be used to cancel the observation.

    Throws

    DittoError query/invalid: if query argument is not a string or not valid DQL.

    Throws

    DittoError query/arguments-invalid: if queryArguments argument is invalid (e.g. contains unsupported types).

    Throws

    DittoError query/unsupported: if the query is not a SELECT query.

    Throws

    DittoError may throw other errors.

  • Initiate a write transaction in a callback.

    Allows you to group multiple operations together that affect multiple documents, potentially across multiple collections.

    Parameters

    • callback: ((transaction) => Promise<void>)

      is given access to a write transaction object that can be used to perform operations on the store.

        • (transaction): Promise<void>
        • Parameters

          Returns Promise<void>

    Returns Promise<WriteTransactionResult[]>

    a list of WriteTransactionResults. There is a result for each operation performed as part of the write transaction.