Examples

On this page you will find some more complex examples of using the Deta SDK.

Base

Put

const Deta = require('deta');
const deta = Deta(); //instantiate with Data Key or env DETA_PROJECT_KEY
const db = deta.Base("simple_db");
// Store objects.
// A key will be automatically generated.
await db.put({ name: "alex", age: 77 });
// We will use "one" as a key.
await db.put({ name: "alex", age: 77 }, "one");
// The key could also be included in the object itself.
await db.put({ name: "alex", age: 77, key: "one" });
// Store simple types.
await db.put("hello, worlds");
await db.put(7);
// "success" is the value and "smart_work" is the key.
await db.put("success", "smart_work");
await db.put(["a", "b", "c"], "my_abc");
// Put expiring items.
// Expire in 300 seconds.
await db.put({ name: "alex", age: 21 }, "alex21", { expireIn: 300 });
// Expire at date.
await db.put({ name: "max", age: 28 }, "max28", { expireAt: new Date("2023-01-01T00:00:00") });

Get

const item = await db.get('one'); // retrieving item with key "one"

If the record is found, the returned promise will resolve to an object, else null:

{
name: 'alex', age: 77, key: 'one'
}

Insert

const Deta = require('deta');
const deta = Deta(); //instantiate with Data Key or env DETA_PROJECT_KEY
const db = deta.Base("simple_db");
// Will succeed, a key will be auto-generated.
const res1 = await db.insert("hello, world");
// Will succeed.
const res2 = await db.insert({ message: "hello, world" }, "greeting1");
// Will raise an error as key "greeting1" already exists.
const res3 = await db.insert({ message: "hello, there" }, "greeting1");
// Expire in 300 seconds.
await db.insert({ message: "will be deleted" }, "temp_key", { expireIn: 300 });
// Expire at date.
await db.insert({ message: "will be deleted" }, "temp_key_2", { expireAt: new Date("2023-01-01T00:00:00") });

Put Many

await db.putMany([
{ name: "Beverly", hometown: "Copernicus City", key: "one" }, // Key provided.
["Namaskāra", "marhabaan", "hello", "yeoboseyo"], // Key auto-generated.
"dude", // Key auto-generated.
]);
// Put many to expire in 300 seconds.
await db.putMany(
[
{ key: "temp-1", name: "test-1" },
{ key: "temp-2", name: "test-2" },
],
{ expireIn: 300 },
);
// Put many with expiry date.
await db.putMany(
[
{ key: "temp-1", name: "test-1" },
{ key: "temp-2", name: "test-2" },
],
{ expireAt: new Date("2023-01-01T00:00:00") },
);

Example output:

{
"processed": {
"items": [
{
"hometown": "Copernicus City",
"key": "one",
"name": "Beverly"
},
{
"key": "5feqybn7lb05",
"value": ["Namaskāra", "hello", "marhabaan", "yeoboseyo"]
},
{
"key": "jyesxxlrezo0",
"value": "dude"
}
]
}
}

Update

Assume we have the following item in a Base:

{
"key": "user-a",
"username": "jimmy",
"profile": {
"age": 32,
"active": false,
"hometown": "pittsburgh"
},
"on_mobile": true,
"likes": ["anime"],
"purchases": 1
}

We will use update, via an updates dictionary / object.

const updates = {
"profile.age": 33, // Set "profile.age" to 33.
"profile.active": true, // Set "profile.active" to true.
"profile.email": "[email protected]", // Create a new attribute "profile.email".
"profile.hometown": users.util.trim(), // Remove "profile.hometown".
on_mobile: users.util.trim(), // Remove "on_mobile".
purchases: users.util.increment(2), // Increment "purchases" by 2.
likes: users.util.append("ramen"), // Append "ramen" to "likes".
};
const res = await db.update(updates, "user-a");

The above updates result in the following item in the Base:

{
"key": "user-a",
"username": "jimmy",
"profile": {
"age": 33,
"active": true,
"email": "[email protected]"
},
"likes": ["anime", "ramen"],
"purchases": 3
}

Fetch

If we have the following items in a Base:

[
{
"key": "key-1",
"name": "Wesley",
"age": 27,
"hometown": "San Francisco"
},
{
"key": "key-2",
"name": "Beverly",
"age": 51,
"hometown": "Copernicus City"
},
{
"key": "key-3",
"name": "Kevin Garnett",
"age": 43,
"hometown": "Greenville"
}
]

Then the following fetch calls:

const { items: firstResult } = await db.fetch({ "age?lt": 30 });
const { items: secondResult } = await db.fetch([{ "age?gt": 50 }, { hometown: "Greenville" }]);

will return following data:

firstResult:

[
{
"key": "key-1",
"name": "Wesley",
"age": 27,
"hometown": "San Francisco"
}
]

secondResult:

[
{
"key": "key-2",
"name": "Beverly",
"age": 51,
"hometown": "Copernicus City"
},
{
"key": "key-3",
"name": "Kevin Garnett",
"age": 43,
"hometown": "Greenville"
}
]

Fetch All Items

The following snippet will fetch all items from a Base:

let res = await db.fetch();
let allItems = res.items;
// Continue fetching until "res.last" is undefined.
while (res.last) {
res = await db.fetch({}, { last: res.last });
allItems = allItems.concat(res.items);
}

Drive

Put

// Provide content directly.
drive.put("hello.txt", {data: "Hello world"});
drive.put("hello.txt", {data: "Hello world", contentType: "text/plain"});
// Provide a content buffer.
drive.put("hello.txt", {data: Buffer.from("Hello World"), contentType: "text/plain"});
// Provide a path to a file.
drive.put("hello.txt", {path: "./my/file/path/file.txt"});
drive.put("hello.txt", {path: "./my/file/path/file.txt", contentType: "text/plain"});

Get

const buf = await drive.get("hello.txt");

Delete

const deletedFile = await drive.delete("hello.txt");

Delete Many

const result = await drive.DeleteMany(["file1.txt", "file2.txt", "file3.txt"]);

An output includes a list / array of successfully deleted files, and a dict / object of failures with reasons:

{
"deleted": ["file1.txt", "file2.txt"],
"failed": {
"file3.txt": "reason for failure"
}
}

List

The following snippet will list all files in a Drive:

let result = await drive.list();
let allFiles = result.names;
let last = result.paging.last;
while (last) {
// Provide "last" from previous call.
result = await drive.list({ last: result.paging.last });
allFiles = allFiles.concat(result.names);
last = result.paging.last;
}
console.log("all files:", allFiles);
const resultWithPrefix = await drive.list({ prefix: "blog/" });
const resultWithLimit = await drive.list({ limit: 100 });
const resultWithLimitAndPrefix = await drive.list({
limit: 100,
prefix: "blog/",
});

Outputs of list include a dict / object with paging and names keys.

{
"names": ["file1.txt", "file2.txt"],
"paging": {
"size": 2,
"last": "file2.txt"
}
}