triplit icon indicating copy to clipboard operation
triplit copied to clipboard

[Feature] deleteWhere and updateWhere

Open daveycodez opened this issue 7 months ago • 0 comments

It would be amazing to be able to perform deletes and updates based on where conditions instead of just by ID's.

Here are 2 functions I created for the HttpClient, it would be really powerful to have this available on both the Triplit client and the HttpClient.

import type {
    CollectionNameFromModels,
    HttpClient,
    Models,
    UpdatePayload,
    WhereFilter
} from "@triplit/client"

export async function deleteWhere<M extends Models<M> = Models>(
    httpClient: HttpClient<M>,
    collectionName: CollectionNameFromModels<M>,
    where: WhereFilter<M, CollectionNameFromModels<M>>[],
    batchSize = 500
) {
    let total = 0

    while (true) {
        const entities = (await httpClient.fetch({
            collectionName,
            where,
            limit: batchSize
        })) as unknown as { id: string }[]

        await Promise.all(entities.map((entity) => httpClient.delete(collectionName, entity.id)))

        total += entities.length

        if (entities.length < batchSize) break
    }

    return total
}

export async function updateWhere<M extends Models<M> = Models>(
    httpClient: HttpClient<M>,
    collectionName: CollectionNameFromModels<M>,
    where: WhereFilter<M, CollectionNameFromModels<M>>[],
    update: UpdatePayload<M, CollectionNameFromModels<M>>,
    batchSize = 500
) {
    let total = 0

    while (true) {
        const entities = (await httpClient.fetch({
            collectionName,
            where,
            limit: batchSize
        })) as unknown as { id: string }[]

        await Promise.all(
            entities.map((entity) => httpClient.update(collectionName, entity.id, update))
        )

        total += entities.length

        if (entities.length < batchSize) break
    }

    return total
}

daveycodez avatar May 20 '25 20:05 daveycodez