Alıştırma - Cosmos DB ile çalışmak için JavaScript kodu ekleme

Tamamlandı

Bu ünitede LIKE, JOIN ve WHERE gibi SQL anahtar sözcüklerini kullanarak Cosmos SDK ile veri bulabileceğiniz betikler oluşturup çalıştıracaksınız.

Kapsayıcıdaki ürünleri bulmak için betiği oluşturma

  1. Visual Studio Code'da, Dosya menüsünde Yeni Metin Dosyası'nı seçin.

  2. Dosya menüsünde Farklı Kaydet’i seçin. Yeni dosyayı 2-contoso-products-find.js adıyla kaydedin.

  3. Aşağıdaki JavaScript'i kopyalayın ve bu dosyaya yapıştırın:

    import * as path from "path";
    import { promises as fs } from "fs";
    import { fileURLToPath } from "url";
    const __dirname = path.dirname(fileURLToPath(import.meta.url));
    
    // Get environment variables from .env
    import * as dotenv from "dotenv";
    dotenv.config();
    
    // Get Cosmos Client
    import { CosmosClient } from "@azure/cosmos";
    
    // Provide required connection from environment variables
    const cosmosSecret = process.env.COSMOS_CONNECTION_STRING;
    
    // Authenticate to Azure Cosmos DB
    const cosmosClient = new CosmosClient(cosmosSecret);
    
    // Set Database name and container name
    const databaseName = process.env.COSMOS_DATABASE_NAME;
    const containerName = process.env.COSMOS_CONTAINER_NAME;
    
    // Get Container
    const container = await cosmosClient
      .database(databaseName)
      .container(containerName);
    
    // Find all products that match a property with a value like `value`
    async function executeSqlFind(property, value) {
      // Build query
      const querySpec = {
        query: `select * from products p where p.${property} LIKE @propertyValue`,
        parameters: [
          {
            name: "@propertyValue",
            value: `${value}`,
          },
        ],
      };
    
      // Show query
      console.log(querySpec);
    
      // Get results
      const { resources } = await container.items.query(querySpec).fetchAll();
    
      let i = 0;
    
      // Show results of query
      for (const item of resources) {
        console.log(`${++i}: ${item.id}: ${item.name}, ${item.sku}`);
      }
    }
    
    // Find inventory of products with property/value and location
    async function executeSqlInventory(propertyName, propertyValue, locationPropertyName, locationPropertyValue) {
      // Build query
      const querySpec = {
        query: `select p.id, p.name, i.location, i.inventory from products p JOIN i IN p.inventory where p.${propertyName} LIKE @propertyValue AND i.${locationPropertyName}=@locationPropertyValue`,
    
        parameters: [
          {
            name: "@propertyValue",
            value: `${propertyValue}`,
          },
          { 
            name: "@locationPropertyValue", 
            value: `${locationPropertyValue}` },
        ],
      };
    
      // Show query
      console.log(querySpec);
    
      // Get results
      const { resources } = await container.items.query(querySpec).fetchAll();
    
      let i = 0;
    
      // Show results of query
      console.log(`Looking for ${propertyName}=${propertyValue}, ${locationPropertyName}=${locationPropertyValue}`);
      for (const item of resources) {
        console.log(
          `${++i}: ${item.id}: '${item.name}': current inventory = ${
            item.inventory
          }`
        );
      }
    }
    
    // Example queries
    /*
    
    // find all bikes based on partial match to property value
    
    node 2-contoso-products-find.js find categoryName '%Bikes%'
    node 2-contoso-products-find.js find name '%Blue%'
    
    // find inventory at location on partial match to property value and specific location
    
    node 2-contoso-products-find.js find-inventory categoryName '%Bikes%' location Seattle
    node 2-contoso-products-find.js find-inventory name '%Blue%' location Dallas
    
    */
    const args = process.argv;
    
    if (args && args[2] == "find") {
      await executeSqlFind(args[3], args[4]);
    } else if (args && args[2] == "find-inventory") {
      await executeSqlInventory(args[3], args[4], args[5], args[6]);
    } else {
      console.log("products: no args used");
    }
    
  4. Visual Studio Code terminalinde javascript dosyasını yürüterek tüm bisikletleri bulun:

    node 2-contoso-products-find.js find categoryName '%Bikes%'
    

    Terim bikes , %kısmi eşleştirmeyi gösteren yüzde işaretleri ile sarmalanır.

    Kapsayıcının yöntemindeki executeSqlFind SQL sorgusu like anahtar sözcüğünü ve sorgu parametrelerini kullanarak içeren BikescategoryName adlı öğeleri bulur.

  5. Adında sözcüğü Blue olan tüm ürünleri bulmak için başka bir sorgu çalıştırın.

    node 2-contoso-products-find.js find name '%Blue%'
    
  6. Seattle'da bisikletler için ürün envanteri bulmak için başka bir sorgu çalıştırın.

    node 2-contoso-products-find.js find-inventory categoryName '%Bikes%' location Seattle
    
  7. Dallas'ta adında sözcüğü Blue olan tüm ürünlerin envanterini bulmak için başka bir sorgu çalıştırın.

    node 2-contoso-products-find.js find-inventory name '%Blue%' location Dallas
    

Ürünleri kapsayıcıya eklemek için betiği oluşturma

  1. Visual Studio Code'da, Dosya menüsünde Yeni Metin Dosyası'nı seçin.

  2. Dosya menüsünde Farklı Kaydet’i seçin. Yeni dosyayı 3-contoso-products-upsert.js adıyla kaydedin.

  3. Aşağıdaki JavaScript'i kopyalayın ve bu dosyaya yapıştırın:

    import * as path from "path";
    import { promises as fs } from "fs";
    import { fileURLToPath } from "url";
    const __dirname = path.dirname(fileURLToPath(import.meta.url));
    
    // Get environment variables from .env
    import * as dotenv from "dotenv";
    dotenv.config();
    
    // Get Cosmos Client
    import { CosmosClient } from "@azure/cosmos";
    
    // Provide required connection from environment variables
    const cosmosSecret = process.env.COSMOS_CONNECTION_STRING;
    
    // Authenticate to Azure Cosmos DB
    const cosmosClient = new CosmosClient(cosmosSecret);
    
    // Set Database name and container name
    const databaseName = process.env.COSMOS_DATABASE_NAME;
    const containerName = process.env.COSMOS_CONTAINER_NAME;
    
    // Get Container
    const container = await cosmosClient.database(databaseName).container(containerName);
    
    // Either insert or update item
    async function upsert(fileAndPathToJson, encoding='utf-8') {
    
      // Get item from file
      const data = JSON.parse(await fs.readFile(path.join(__dirname, fileAndPathToJson), encoding));
    
      // Process request
      // result.resource is the returned item
      const result = await container.items.upsert(data);
    
      if(result.statusCode===201){
        console.log("Inserted data");
      } else if (result.statusCode===200){
        console.log("Updated data");
      } else {
        console.log(`unexpected statusCode ${result.statusCode}`);
      }
    }
    
    // Insert data - statusCode = 201
    await upsert('./3-contoso-products-upsert-insert.json');
    
    // Update data - statusCode = 200
    await upsert('./3-contoso-products-upsert-update.json');
    
    // Get item from container and partition key
    const { resource } = await container.item("123", "xyz").read();
    
    // Show final item
    console.log(resource);
    
  4. Ürün için yeni bir dosya oluşturun, 3-contoso-products-upsert-insert.json ve aşağıdaki JSON nesnesini yapıştırın.

    {
        "id": "123",
        "categoryName": "xyz",
        "name": "_a new item inserted"
    }
    

    Kimliği 123 olan bu nesnenin envanteri olmadığını görebilirsiniz.

  5. Ürün için yeni bir dosya oluşturun, 3-contoso-products-upsert-update.json ve aşağıdaki JSON nesnesini yapıştırın.

    {
      "id": "123",
      "categoryName": "xyz",
      "name": "_a new item updated",
      "inventory": [
        {
          "location": "Dallas",
          "inventory": 100
        }
      ]
    }
    

    Bu nesnenin envanteri olduğunu görebilirsiniz.

  6. Visual Studio Code terminalinde JavaScript dosyasını yürüterek yeni ürünü ekleyin.

    node 3-contoso-products-upsert.js
    

    Bu kimlikli ürün mevcut olmadığından ürün eklenir. Ardından betik ürünü envanterle güncelleştirir. Hem ekleme hem de güncelleştirme işlevi, upsert için aynı kodu kullanır.