Published
Edited
Nov 24, 2020
1 fork
3 stars
Insert cell
md`# ThreadDB Usage Demo

Welcome to ThreadDB. Here is a brief demo of some of the basic usage of ThreadDB. This demo should run in observablehq, so there are a few syntax differences to keep in mind.
`
Insert cell
threads = import("https://unpkg.com/@textile/threaddb@0.0.4/dist/index.esm.js")
Insert cell
schema = ({
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Person",
"description": "A simple person schema",
"type": "object",
"properties": {
"_id": {
"description": "Field to contain ulid-based instance id",
"type": "string",
},
"name": {
"description": "Name of the person",
"type": "string",
},
"age": {
"type": "integer",
"minimum": 1,
},
},
"required": ["_id", "name", "age"],
});
Insert cell
// Create an empty db, with a defined schema, and open it
db = new threads.Database("demo-1", { name: "Person", schema }).open(1); // Versioned dbs
Insert cell
// Just start using it!
Person = db.collection("Person");
Insert cell
Person.insert({ name: "Carson", age: 37 });
Insert cell
entity = Person.create({ name: "Other", age: 2 });
Insert cell
entity.exists() // false
Insert cell
Person.has(entity._id); // false
Insert cell
entity.save();
Insert cell
entity.exists();
Insert cell
Person.find({}).count();
Insert cell
person = ({ name: "Someting", age: 4 })
Insert cell
txn = Person.writeTransaction(async function () {
await Person.insert(person);
});
Insert cell
people = Person.find({
$or: [{ age: { $gt: 2 } }, { name: { $eq: "Something" } }],
});
Insert cell
people.toArray();
Insert cell
remote = db.remote.setKeyInfo({ key: Secret("HUB_KEY") })
Insert cell
// New random identity
privateKey = threads.PrivateKey.fromRandom()
Insert cell
// Grab the token, save it, or just use it
token = remote.authorize(privateKey);
Insert cell
id = remote.initialize(); // Create random thread
Insert cell
remote.push("Person");
Insert cell
client = await threads.Client.withKeyInfo({ key: Secret("HUB_KEY") })
Insert cell
context = client.context.withToken(token)
Insert cell
found = await client.find(threads.ThreadID.fromString(id), "Person", {})
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more