-
Notifications
You must be signed in to change notification settings - Fork 49
/
app.js
91 lines (72 loc) · 2.42 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// @ts-check
// <ImportConfiguration>
const CosmosClient = require("@azure/cosmos").CosmosClient;
const config = require("./config");
const dbContext = require("./data/databaseContext");
// </ImportConfiguration>
// <DefineNewItem>
const newItem = {
id: "3",
category: "fun",
name: "Cosmos DB",
description: "Complete Cosmos DB Node.js Quickstart ⚡",
isComplete: false
};
// </DefineNewItem>
async function main() {
// <CreateClientObjectDatabaseContainer>
const { endpoint, key, databaseId, containerId } = config;
const client = new CosmosClient({ endpoint, key });
const database = client.database(databaseId);
const container = database.container(containerId);
// Make sure Tasks database is already setup. If not, create it.
await dbContext.create(client, databaseId, containerId);
// </CreateClientObjectDatabaseContainer>
try {
// <QueryItems>
console.log(`Querying container: Items`);
// query to return all items
const querySpec = {
query: "SELECT * from c"
};
// read all items in the Items container
const { resources: items } = await container.items
.query(querySpec)
.fetchAll();
items.forEach(item => {
console.log(`${item.id} - ${item.description}`);
});
// </QueryItems>
// <CreateItem>
/** Create new item
* newItem is defined at the top of this file
*/
const { resource: createdItem } = await container.items.create(newItem);
console.log(`\r\nCreated new item: ${createdItem.id} - ${createdItem.description}\r\n`);
// </CreateItem>
// <UpdateItem>
/** Update item
* Pull the id and partition key value from the newly created item.
* Update the isComplete field to true.
*/
const { id, category } = createdItem;
createdItem.isComplete = true;
const { resource: updatedItem } = await container
.item(id, category)
.replace(createdItem);
console.log(`Updated item: ${updatedItem.id} - ${updatedItem.description}`);
console.log(`Updated isComplete to ${updatedItem.isComplete}\r\n`);
// </UpdateItem>
// <DeleteItem>
/**
* Delete item
* Pass the id and partition key value to delete the item
*/
const { resource: result } = await container.item(id, category).delete();
console.log(`Deleted item with id: ${id}`);
// </DeleteItem>
} catch (err) {
console.log(err.message);
}
}
main();