Insert record
To insert a single record use the put
API.
The below follows on from the previous examples from defining and creating a collection.
There are currently 2 ways to insert a record.
- Specify an ID for the record.
- If an ID is not specified a random ID will be generated for the record.
This ID can be used to update or delete the record.
Insert a record with an ID
Provide an ID in UUID format.
import { Stash, StashRecord } from "@cipherstash/stashjs";
import { v4 as uuidv4 } from "uuid";
interface Movie extends StashRecord {
title: string;
runningTime: number;
year: number;
}
export const insertRecordWithId = async (): Promise<string> => {
try {
const stash = await Stash.connect();
const movies = await stash.loadCollection<Movie>("movies");
const id = await movies.put({
id: uuidv4(),
title: "The Matrix",
year: 1999,
runningTime: 136,
});
console.info(`Inserted record ${id}`);
return id;
} catch (err) {
console.error(`Failed to insert record. Reason: ${describeError(err)}`);
}
};
insertRecordWithId();
Insert a record without an ID
A random UUID4 id
will be generated for the record.
import { Stash, StashRecord } from "@cipherstash/stashjs";
interface Movie extends StashRecord {
title: string;
runningTime: number;
year: number;
}
export const insertRecordWithoutId = async (): Promise<string> => {
try {
const stash = await Stash.connect();
const movies = await stash.loadCollection<Movie>("movies");
const id = await movies.put({
title: "The Matrix",
year: 1999,
runningTime: 136,
});
console.info(`Inserted record ${id}`);
return id;
} catch (err) {
console.error(`Failed to insert record. Reason: ${describeError(err)}`);
}
};
insertRecordWithoutId();