azure_cosmosdb 1.6.1 copy "azure_cosmosdb: ^1.6.1" to clipboard
azure_cosmosdb: ^1.6.1 copied to clipboard

Connector for Azure Cosmos DB on Dart and Flutter platforms. Supports Cosmos DB SQL API, indexing policies, users, permissions, and spatial types.

Pub Package Dart Platforms Flutter Platforms

License Null Safety Dart Style Pub Points Likes Popularity

Last Commit Dart Workflow Code Lines Code Coverage

Connector for Azure Cosmos DB on Dart and Flutter platforms. Supports Cosmos DB SQL API, indexing policies, users, permissions, and spatial types.

Summary #

Features #

CosmosDbServer: the main class used to communicate with your Azure Cosmos DB instance.

CosmosDbDatabase: class representing a Azure Cosmos DB database hosted in CosmosDbServer.

CosmosDbCollection: class representing a Azure Cosmos DB collection from a CosmosDbDatabase.

BaseDocument: class representing a Azure Cosmos DB document stored in a CosmosDbCollection.

Query: class representing a Azure Cosmos DB SQL query to search documents in a CosmosDbCollection.

CosmosDbUsers and CosmosDbPermissions: to manage users and rights in the Azure Cosmos DB database.

Getting Started #

Import azure_cosmosdb from your pubspec.yaml file:

dependencies:
   azure_cosmosdb: ^1.6.0

Usage #

You should first define a class deriving from BaseDocumentor BaseDocumentWithEtag to model the data you need to store in Azure Cosmos DB.

This class must have an id and a toJson() method returning a Map<String, dynamic> JSON object.

It should also implement a static fromJson(Map json) method to build instances from a Map JSON objects returned by Azure Cosmos DB.

For instance:

import 'package:azure_cosmosdb/azure_cosmosdb.dart';

class ToDo extends BaseDocumentWithEtag {
  ToDo(
    this.id,
    this.label, {
    this.description,
    this.dueDate,
    this.done = false,
  });

  @override
  final String id;

  String label;
  String? description;
  DateTime? dueDate;
  bool done;

  @override
  Map<String, dynamic> toJson() => {
        'id': id,
        'label': label,
        'description': description,
        'due-date': dueDate?.toUtc().toIso8601String(),
        'done': done,
      };

  static ToDo fromJson(Map json) {
    var dueDate = json['due-date'];
    if (dueDate != null) {
      dueDate = DateTime.parse(dueDate).toLocal();
    }
    final todo = ToDo(
      json['id'],
      json['label'],
      description: json['description'],
      dueDate: dueDate,
      done: json['done'],
    );
    todo.setEtag(json);
    return todo;
  }
}

To manage your documents in Azure Cosmos DB:

  • establish a connection to get hold of the Azure Cosmos DB collection
  • register the static fromJson() methods with the collection to enable deserialization of your documents
  • then add or query your documents!

For instance:

void main() async {
  // connect to the collection
  final cosmosDB = CosmosDbServer('https://localhost:8081/', masterKey: '/* your master key*/');

  final database = await cosmosDB.databases.openOrCreate(
    'sample',
    throughput: CosmosDbThroughput.minimum,
  );

  final indexingPolicy =
      IndexingPolicy(indexingMode: IndexingMode.consistent, automatic: false);
  indexingPolicy.excludedPaths.add(IndexPath('/*'));
  indexingPolicy.includedPaths.add(IndexPath('/"due-date"/?'));
  indexingPolicy.compositeIndexes.add([
    IndexPath('/label', order: IndexOrder.ascending),
    IndexPath('/"due-date"', order: IndexOrder.descending)
  ]);

  final todoCollection = await database.collections.openOrCreate('todo',
      partitionKeys: ['/id'], indexingPolicy: indexingPolicy);

  // register the builder for ToDo items
  todoCollection.registerBuilder<ToDo>(ToDo.fromJson);

  // create a new item
  final task = ToDo(
    DateTime.now().millisecondsSinceEpoch.toString(),
    'Improve tests',
    dueDate: DateTime.now().add(Duration(days: 3)),
  );

  // save it to the collection
  await todoCollection.add(task);

  print('Added new task ${task.id} - ${task.label}');

  // query the collection
  final tasks = await todoCollection.query<ToDo>(cosmosdb.Query(
    'SELECT * FROM c WHERE c.label = @improvetests',
    params: {'@improvetests': task.label}));

  print('Other tasks:');
  for (var t in tasks.where((_) => _.id != task.id)) {
    String status = 'still pending';
    final dueDate = t.dueDate;
    if (t.done) {
      status = 'done';
    } else if (dueDate != null) {
      if (dueDate.isBefore(DateTime.now())) {
        status = 'overdue since $dueDate';
      } else {
        status = 'expected for $dueDate';
      }
    }
    print('* ${t.id} - ${t.label} - $status');
  }
}

Users and Permissions #

Most APIs implemented in azure_cosmosdb support an optional CosmosDbPermission parameter when calling Azure Cosmos DB.

This makes it possible open a connection to Azure Cosmos DB without providing the master key. The master key should be kept secret and should not be provided in Web apps or even mobile apps.

Azure Cosmos DB manages a list of users and permissions at the database level. If you need to implement direct access from a Web or mobile app to Azure Cosmos DB, you should create a user for your app and grant permissions as necessary.

To retrieve the permission in your app, you should implement a REST API, e.g. an Azure Function, that your app will call to get the required set of permissions. Only the REST API will need to know the master key to retrieve the permissions.

13
likes
0
pub points
70%
popularity

Publisher

unverified uploader

Connector for Azure Cosmos DB on Dart and Flutter platforms. Supports Cosmos DB SQL API, indexing policies, users, permissions, and spatial types.

Homepage
Repository

License

unknown (license)

Dependencies

crypto, http, retry

More

Packages that depend on azure_cosmosdb