CipherStash
CipherStash Documentation

Update records

The putStream API performs an upsert on the record.

If the record ID provided in the request matches with an existing record ID, that record will be updated.

The streamRecords API is available to convert an array of objects into an Async iterator for putStream to use.

import {
  describeError,
  Stash,
  StashRecord,
  streamRecords,
} from "@cipherstash/stashjs";
import { v4 as uuidv4 } from "uuid";

interface Movie extends StashRecord {
  title: string;
  runningTime: number;
  year: number;
}

const movieRecordsExample: Movie[] = [
  {
      id: "889bf1f6-00b8-4b57-acbc-a39cba35d6e5",
      title: "The Matrix",
      year: 1999,
      runningTime: 136,
  },
  {
      id: "0addcb3c-80b2-45f5-a0f4-37fa44ab6d8e",
      title: "Sneakers",
      year: 1992,
      runningTime: 126,
  },
  {
      id: "12b4d9a8-d6fd-4b66-8cae-a618ef29e9d5",
      title: "Lost in Translation",
      year: 2003,
      runningTime: 102,
  },
  {
      id: "25b2b938-4919-44d3-a904-1fe3c861d488",
      title: "Everything Everywhere All at Once",
      year: 2022,
      runningTime: 136,
  },
];

export const updateRecords = async (
  movieRecords: Movie[]
): Promise<number | undefined> => {
  try {
    const stash = await Stash.connect();

    const movies = await stash.loadCollection<Movie>("movies");

    const result = await movies.putStream(streamRecords(movieRecords));
    
    console.info(`${result.numInserted} results updateed`);
    return result.numInserted;
  } catch (err) {
    console.error(`Could not update records. Reason: "${describeError(err)}`);
  }
};

updateRecords(movieRecordsExample);