Skip to content

Commit 07f3ad3

Browse files
authored
Merge pull request #3 from burkeholland/master
Refactor sample to match Quickstart
2 parents e135fd6 + 70e3f6a commit 07f3ad3

File tree

4 files changed

+116
-258
lines changed

4 files changed

+116
-258
lines changed

README.md

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,42 @@
11
---
22
page_type: sample
33
languages:
4-
- javascript
4+
- javascript
55
products:
6-
- azure
6+
- azure
77
description: "Azure Cosmos DB is a globally distributed multi-model database."
88
urlFragment: azure-cosmos-db-sql-api-nodejs-getting-started
99
---
1010

1111
# Developing a Node.js app using the Azure Cosmos DB SQL API
12+
1213
Azure Cosmos DB is a globally distributed multi-model database. One of the supported APIs is the SQL API, which provides a JSON document model with SQL querying and JavaScript procedural logic. This sample shows you how to use Azure Cosmos DB with the SQL API to store and access data from a Node.js application.
1314

1415
## Running this sample
15-
* Before you can run this sample, you must have the following perquisites:
16-
* An active Azure Cosmos DB account - If you don't have an account, refer to the [Create an Azure Cosmos DB account](https://docs.microsoft.com/en-us/azure/cosmos-db/create-sql-api-nodejs#create-a-database-account) article.
17-
* [Node.js](https://nodejs.org/en/) version v0.10.29 or higher.
18-
* [Git](http://git-scm.com/).
1916

17+
This sample is designed to be run as part of the article, "[Quickstart: use Node.js to query an Azure Cosmos DB SQL API Database](https://docs.microsoft.com/en-us/azure/cosmos-db/create-sql-api-nodejs)".
18+
19+
- Before you can run this sample, you must have the following perquisites:
20+
_ An active Azure Cosmos DB account - If you don't have an account, refer to the [Create an Azure Cosmos DB account](https://docs.microsoft.com/en-us/azure/cosmos-db/create-sql-api-nodejs#create-a-database-account) article.
21+
_ [Node.js](https://nodejs.org/en/) version v0.10.29 or higher. \* [Git](http://git-scm.com/).
2022

2123
1. Clone this repository using `git clone git@github.com:Azure-Samples/azure-cosmos-db-sql-api-nodejs-getting-started.git cosmosdb`
2224

23-
2. Change directories to the repo using `cd cosmosdb`
25+
1. Change directories to the repo using `cd cosmosdb`
2426

25-
3. Next, substitute the endpoint and authorization key in `config.js` with your Azure Cosmos DB account's values.
27+
1. Next, substitute the endpoint and authorization key in `app.js` with your Azure Cosmos DB account's values.
2628

27-
```
28-
config.endpoint = "~your Azure Cosmos DB endpoint here~";
29-
config.primaryKey = "~your auth key here~";
30-
```
29+
```
30+
const endpoint = "<Your Azure Cosmos account URI>";
31+
const key = "<Your Azure Cosmos account key>";
32+
```
3133

32-
5. Run `npm install` in a terminal to install required npm modules
33-
34-
6. Run `node app.js` in a terminal to start your start your node application.
34+
1. Run `npm install` in a terminal to install required npm modules
35+
36+
1. Run `node app.js` in a terminal to start your start your node application.
3537

3638
## About the code
39+
3740
The code included in this sample is intended to get you quickly started with a Node.js console application that connects to Azure Cosmos DB with the SQL API.
3841

3942
## More information

app.js

Lines changed: 58 additions & 156 deletions
Original file line numberDiff line numberDiff line change
@@ -1,159 +1,61 @@
1-
//@ts-check
2-
const CosmosClient = require('@azure/cosmos').CosmosClient
3-
4-
const config = require('./config')
5-
const url = require('url')
6-
7-
const endpoint = config.endpoint
8-
const key = config.key
9-
10-
const databaseId = config.database.id
11-
const containerId = config.container.id
12-
const partitionKey = { kind: 'Hash', paths: ['/Country'] }
13-
14-
const client = new CosmosClient({ endpoint, key })
15-
16-
/**
17-
* Create the database if it does not exist
18-
*/
19-
async function createDatabase() {
20-
const { database } = await client.databases.createIfNotExists({
21-
id: databaseId
22-
})
23-
console.log(`Created database:\n${database.id}\n`)
24-
}
25-
26-
/**
27-
* Read the database definition
28-
*/
29-
async function readDatabase() {
30-
const { resource: databaseDefinition } = await client
31-
.database(databaseId)
32-
.read()
33-
console.log(`Reading database:\n${databaseDefinition.id}\n`)
34-
}
35-
36-
/**
37-
* Create the container if it does not exist
38-
*/
39-
async function createContainer() {
40-
const { container } = await client
41-
.database(databaseId)
42-
.containers.createIfNotExists(
43-
{ id: containerId, partitionKey },
44-
{ offerThroughput: 400 }
45-
)
46-
console.log(`Created container:\n${config.container.id}\n`)
47-
}
48-
49-
/**
50-
* Read the container definition
51-
*/
52-
async function readContainer() {
53-
const { resource: containerDefinition } = await client
54-
.database(databaseId)
55-
.container(containerId)
56-
.read()
57-
console.log(`Reading container:\n${containerDefinition.id}\n`)
58-
}
59-
60-
/**
61-
* Create family item if it does not exist
62-
*/
63-
async function createFamilyItem(itemBody) {
64-
const { item } = await client
65-
.database(databaseId)
66-
.container(containerId)
67-
.items.upsert(itemBody)
68-
console.log(`Created family item with id:\n${itemBody.id}\n`)
69-
}
70-
71-
/**
72-
* Query the container using SQL
73-
*/
74-
async function queryContainer() {
75-
console.log(`Querying container:\n${config.container.id}`)
76-
77-
// query to return all children in a family
78-
const querySpec = {
79-
query: 'SELECT VALUE r.children FROM root r WHERE r.lastName = @lastName',
80-
parameters: [
81-
{
82-
name: '@lastName',
83-
value: 'Andersen'
84-
}
85-
]
1+
// @ts-check
2+
const CosmosClient = require("@azure/cosmos").CosmosClient;
3+
const config = require("./config");
4+
const dbContext = require("./data/databaseContext");
5+
6+
const newItem = {
7+
id: "3",
8+
category: "fun",
9+
name: "Cosmos DB",
10+
description: "Complete Cosmos DB Node.js Quickstart ⚡",
11+
isComplete: false
12+
};
13+
14+
async function main() {
15+
const { endpoint, key, databaseId, containerId } = config;
16+
17+
const client = new CosmosClient({ endpoint, key });
18+
19+
const database = client.database(databaseId);
20+
const container = database.container(containerId);
21+
22+
// Make sure Tasks database is already setup. If not, create it.
23+
await dbContext.create(client, databaseId, containerId);
24+
25+
try {
26+
console.log(`Querying container: Items`);
27+
28+
// query to return all items
29+
const querySpec = {
30+
query: "SELECT * from c"
31+
};
32+
33+
// read all items in the Items container
34+
const { resources: items } = await container.items
35+
.query(querySpec)
36+
.fetchAll();
37+
38+
console.log(items);
39+
40+
// Create a new item
41+
const { resource: createdItem } = await container.items.create(newItem);
42+
console.log(`Created item: %s`, createdItem);
43+
44+
const { id, category } = createdItem;
45+
46+
// Update the item
47+
createdItem.isComplete = true;
48+
const { resource: updatedItem } = await container
49+
.item(id, category)
50+
.replace(createdItem);
51+
console.log(`Updated item: %s`, updatedItem);
52+
53+
// Delete the item
54+
const { resource: result } = await container.item(id, category).delete();
55+
console.log("Deleted item with id: %s", id);
56+
} catch (err) {
57+
console.log(err.message);
8658
}
87-
88-
const { resources: results } = await client
89-
.database(databaseId)
90-
.container(containerId)
91-
.items.query(querySpec)
92-
.fetchAll()
93-
for (var queryResult of results) {
94-
let resultString = JSON.stringify(queryResult)
95-
console.log(`\tQuery returned ${resultString}\n`)
96-
}
97-
}
98-
99-
/**
100-
* Replace the item by ID.
101-
*/
102-
async function replaceFamilyItem(itemBody) {
103-
console.log(`Replacing item:\n${itemBody.id}\n`)
104-
// Change property 'grade'
105-
itemBody.children[0].grade = 6
106-
const { item } = await client
107-
.database(databaseId)
108-
.container(containerId)
109-
.item(itemBody.id, itemBody.Country)
110-
.replace(itemBody)
111-
}
112-
113-
/**
114-
* Delete the item by ID.
115-
*/
116-
async function deleteFamilyItem(itemBody) {
117-
await client
118-
.database(databaseId)
119-
.container(containerId)
120-
.item(itemBody.id, itemBody.Country)
121-
.delete(itemBody)
122-
console.log(`Deleted item:\n${itemBody.id}\n`)
123-
}
124-
125-
/**
126-
* Cleanup the database and collection on completion
127-
*/
128-
async function cleanup() {
129-
await client.database(databaseId).delete()
130-
}
131-
132-
/**
133-
* Exit the app with a prompt
134-
* @param {string} message - The message to display
135-
*/
136-
function exit(message) {
137-
console.log(message)
138-
console.log('Press any key to exit')
139-
process.stdin.setRawMode(true)
140-
process.stdin.resume()
141-
process.stdin.on('data', process.exit.bind(process, 0))
14259
}
14360

144-
createDatabase()
145-
.then(() => readDatabase())
146-
.then(() => createContainer())
147-
.then(() => readContainer())
148-
.then(() => createFamilyItem(config.items.Andersen))
149-
.then(() => createFamilyItem(config.items.Wakefield))
150-
.then(() => queryContainer())
151-
.then(() => replaceFamilyItem(config.items.Andersen))
152-
.then(() => queryContainer())
153-
.then(() => deleteFamilyItem(config.items.Andersen))
154-
.then(() => {
155-
exit(`Completed successfully`)
156-
})
157-
.catch(error => {
158-
exit(`Completed with error ${JSON.stringify(error)}`)
159-
})
61+
main();

config.js

Lines changed: 9 additions & 87 deletions
Original file line numberDiff line numberDiff line change
@@ -1,89 +1,11 @@
1-
var config = {}
1+
// @ts-check
22

3-
config.endpoint = '~your Azure Cosmos DB account endpoint uri here~'
4-
config.key = '~your primary key here~'
3+
const config = {
4+
endpoint: "<Your Azure Cosmos account URI>",
5+
key: "<Your Azure Cosmos account key>",
6+
databaseId: "Tasks",
7+
containerId: "Items",
8+
partitionKey: { kind: "Hash", paths: ["/category"] }
9+
};
510

6-
config.database = {
7-
id: 'FamilyDatabase'
8-
}
9-
10-
config.container = {
11-
id: 'FamilyContainer'
12-
}
13-
14-
config.items = {
15-
Andersen: {
16-
id: 'Anderson.1',
17-
Country: 'USA',
18-
lastName: 'Andersen',
19-
parents: [
20-
{
21-
firstName: 'Thomas'
22-
},
23-
{
24-
firstName: 'Mary Kay'
25-
}
26-
],
27-
children: [
28-
{
29-
firstName: 'Henriette Thaulow',
30-
gender: 'female',
31-
grade: 5,
32-
pets: [
33-
{
34-
givenName: 'Fluffy'
35-
}
36-
]
37-
}
38-
],
39-
address: {
40-
state: 'WA',
41-
county: 'King',
42-
city: 'Seattle'
43-
}
44-
},
45-
Wakefield: {
46-
id: 'Wakefield.7',
47-
Country: 'Italy',
48-
parents: [
49-
{
50-
familyName: 'Wakefield',
51-
firstName: 'Robin'
52-
},
53-
{
54-
familyName: 'Miller',
55-
firstName: 'Ben'
56-
}
57-
],
58-
children: [
59-
{
60-
familyName: 'Merriam',
61-
firstName: 'Jesse',
62-
gender: 'female',
63-
grade: 8,
64-
pets: [
65-
{
66-
givenName: 'Goofy'
67-
},
68-
{
69-
givenName: 'Shadow'
70-
}
71-
]
72-
},
73-
{
74-
familyName: 'Miller',
75-
firstName: 'Lisa',
76-
gender: 'female',
77-
grade: 1
78-
}
79-
],
80-
address: {
81-
state: 'NY',
82-
county: 'Manhattan',
83-
city: 'NY'
84-
},
85-
isRegistered: false
86-
}
87-
}
88-
89-
module.exports = config
11+
module.exports = config;

0 commit comments

Comments
 (0)