Skip to content

Instantly share code, notes, and snippets.

@Robjam
Created August 23, 2018 04:20
Show Gist options
  • Save Robjam/d9853b553a04753f9a9073ef834bad1c to your computer and use it in GitHub Desktop.
Save Robjam/d9853b553a04753f9a9073ef834bad1c to your computer and use it in GitHub Desktop.
samples of @azure/cosmosdb with iterators
var CosmosClient = require('@azure/cosmos').CosmosClient;
const endpoint = "[serviceEndpoint]"; // Add the URI from azure portal
const masterKey = "[masterkey]"; // Add the primary key from azure portal
const client = new CosmosClient({ endpoint, auth: { masterKey } });
const databaseDefinition = { id: "myDatabase" }; // Add the databaseID
const collectionDefinition = { id: "myCollection" }; // Add the collectionId
async function run() {
const databaseResult = await client.databases.createIfNotExists(databaseDefinition);
const containerResult = await databaseResult.database.containers.createIfNotExists(collectionDefinition);
const queryGenerator = () => containerResult.container.items.query({ query: "select * from c" }, { maxItemCount: 2 });
console.log("beginning executeNext sample");
await runExecuteNextSample(queryGenerator());
console.log("beginning runNextItem sample");
await runNextItemSample(queryGenerator());
console.log("beginning asyncIterator sample");
await runAsynIteratorSample(queryGenerator());
}
async function runAsynIteratorSample(queryIterator) {
// async iterators need the --harmony-async-iteration flag enabled to run on versions < 10
for await (const document of queryIterator.getAsyncIterator()) {
console.log(document);
}
}
async function runExecuteNextSample(queryIterator) {
let { result: pagingResult } = await queryIterator.executeNext();
while (typeof pagingResult !== 'undefined') {
console.log(pagingResult);
let results = await queryIterator.executeNext();
pagingResult = results.result;
}
}
async function runNextItemSample(queryIterator) {
let currentItem = await queryIterator.nextItem();
while (typeof currentItem.result != 'undefined') {
console.log(currentItem);
currentItem = await queryIterator.nextItem();
}
}
run().catch(err => console.log(err));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment