Insert records
To insert multiple records asynchronously use the putStream
api.
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: uuidv4(),
title: "The Matrix",
year: 1999,
runningTime: 136,
},
{
id: uuidv4(),
title: "Sneakers",
year: 1992,
runningTime: 126,
},
{
id: uuidv4(),
title: "Lost in Translation",
year: 2003,
runningTime: 102,
},
{
id: uuidv4(),
title: "Everything Everywhere All at Once",
year: 2022,
runningTime: 136,
},
];
export const insertRecords = 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 inserted`);
return result.numInserted;
} catch (err) {
console.error(`Could not insert records. Reason: "${describeError(err)}`);
}
};
insertRecords(movieRecordsExample);