Esercizio - Aggiungere codice JavaScript per lavorare con Cosmos DB

Completato

In questa unità verranno creati ed eseguiti script che usano parole chiave SQL come LIKE, JOIN e WHERE per trovare i dati con Cosmos SDK.

Creare lo script per trovare i prodotti nel contenitore

  1. In Visual Studio Code scegliere Nuovo file dal menu File.

  2. Scegliere Salva con nome dal menu File. Salvare il nuovo file con il nome 2-contoso-products-upload-data.js.

  3. Copiare il codice JavaScript seguente e incollarlo nel file:

    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. Nel terminale di Visual Studio Code eseguire il file JavaScript per trovare tutte le biciclette:

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

    Il termine bikes viene racchiuso con segni di percentuale, %, che indicano una corrispondenza parziale.

    La query SQL nel metodo per il contenitore executeSqlFind usa la parola chiave LIKE e i parametri di query per trovare tutti gli elementi con un categoryName che include Bikes.

  5. Eseguire un'altra query per trovare tutti i prodotti con la parola Blue nel nome.

    node 2-contoso-products-find.js find name '%Blue%'
    
  6. Eseguire un'altra query per trovare l’inventario dei prodotti per biciclette a Seattle.

    node 2-contoso-products-find.js find-inventory categoryName '%Bikes%' Seattle
    
  7. Eseguire un'altra query per trovare l'inventario di tutti i prodotti con la parola Blue nel nome a Dallas.

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

Creare lo script per eseguire l'upsert dei prodotti in un contenitore

  1. In Visual Studio Code scegliere Nuovo file di testo dal menu File.

  2. Scegliere Salva con nome dal menu File. Salvare il nuovo file con il nome 3-contoso-products-upload-data.js.

  3. Copiare il codice JavaScript seguente e incollarlo nel file:

    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. Creare un nuovo file per il prodotto 3-contoso-products-upsert-insert.json e incollare l'oggetto JSON seguente.

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

    Si noti che questo oggetto con ID 123 non dispone di alcun inventario.

  5. Creare un nuovo file per il prodotto 3-contoso-products-upsert-insert.json e incollare l'oggetto JSON seguente.

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

    Si noti che questo oggetto dispone dell'inventario.

  6. Nel terminale di Visual Studio Code eseguire il file JavaScript per eseguire l'upsert del nuovo prodotto.

    3-contoso-products-upsert.js
    

    Poiché il prodotto con l'ID non esiste, viene inserito. Quindi lo script aggiorna il prodotto con l'inventario. Sia l'inserimento che la funzionalità di aggiornamento usano lo stesso codice per eseguire l'upsert.