CipherStash
CipherStash Documentation

Create a collection

Before creating a collection you will need to define the collection and generate a schema.

The example below creates a collection using JSON.

import {
  Stash,
  CollectionSchema,
  generateSchemaDefinitionFromJSON,
  describeError,
  StashRecord,
} from "@cipherstash/stashjs";

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

export const generateSchemaUsingJSON = async () => {
  const collectionName = "movies";

  const jsonMapping = JSON.stringify({
      "type": {
        "title": "string",
        "runningTime": "uint64",
        "year": "uint64",
        "summary": "string"
      },
      "indexes": {
        "exactTitle": { "kind": "exact", "field": "title" },
        "runningTime": { "kind": "range", "field": "runningTime" },
        "year": { "kind": "range", "field": "year" },
        "title": {
          "kind": "match",
          "fields": ["title"],
          "tokenFilters": [
            { "kind": "downcase" },
            { "kind": "ngram", "tokenLength": 3 }
          ],
          "tokenizer": { "kind": "standard" }
        },
        "summaryDynamicMatch": {
          "kind": "dynamic-match",
          "tokenFilters": [
            { "kind": "downcase" }
          ],
          "tokenizer":  { "kind": "ngram", "tokenLength": 3 }
        },
        "allTextDynamicMatch": {
          "kind": "field-dynamic-match",
          "tokenFilters": [
            { "kind": "downcase" }
          ],
          "tokenizer":  { "kind": "ngram", "tokenLength": 3 }
        }
      }
    }
  );

  try {
    const schemaDefinition = await generateSchemaDefinitionFromJSON(
      jsonMapping
    );

    return CollectionSchema.define<Movie>(
      collectionName
    ).fromCollectionSchemaDefinition(schemaDefinition);
  } catch (err) {
    console.error(`Could not define schema. Reason: ${describeError(err)}`);
    return;
  }
};

async function createCollection() {
  const movieSchema = await generateSchemaUsingJSON();

  if (!movieSchema) {
    console.error("Schema undefined");
    return;
  }

  try {
    const stash = await Stash.connect();

    const movies = await stash.createCollection(movieSchema);

    console.log(`Collection "${movies.name}" created`);
  } catch (err) {
    console.error(`Could not create collection! Reason: ${describeError(err)}`);
  }
}

createCollection();