couchdb 0.5.5

A library for Dart developers for work with CouchDB #

Created under a MIT-style license.

Overview #

CouchDB is a database that completely embraces the web. Store your data with JSON documents. Access your documents with your web browser, via HTTP.

A basic understanding of CouchDB is required to using this library. Detailed information can be found at the official documentation site.

API #

The connection to the database, along with authentication, is handled via CouchDbClient for both web and server environments.

Available three types of authentication:

- Basic
- Cookie
- Proxy

For Basic authentication simply pass username and password to constructor:

final c = CouchDbClient(username: 'name', password: 'pass');

For Cookie authentication you also must provide auth parameter and then call authenticate() method (note that cookies are valid for 10 minutes by default, other expiration you may specify in Expiration header):

final c = CouchDbClient(username: 'name', password: 'pass', auth: 'cookie');
final res = await c.authenticate();

authenticate(), logout() are suitable only for cookie authentication. userInfo() are suitable for all auth types.

For Proxy authentication pass username to constructor and provide

  • X-Auth-CouchDB-UserName: username (by default is used username that is passed to constructor, so it can be skipped);
  • X-Auth-CouchDB-Roles: comma-separated (,) list of user roles;
  • X-Auth-CouchDB-Token: authentication token. When proxy_use_secret is set (which is strongly recommended!), this header provides an HMAC of the username to authenticate and the secret token to prevent requests from untrusted sources (by default are used username and secret that are passed to constructor, so it can be skipped).

headers:

final c = CouchDbClient(username: 'name', auth: 'proxy', secret: '92de07df7e7a3fe14808cef90a7cc0d91');
c.modifyRequestHeaders(<String, String>{
  'X-Auth-CouchDB-Roles': 'users,blogger'
});

Note that X-Auth-CouchDB-Token isn't required if proxy_use_secret sets to false.

[couch_httpd_auth]
proxy_use_secret = false

Otherwise you may provide secret option which is used to generate token. The secret key should be the same on the client and the CouchDB node:

[couch_httpd_auth]
secret = 92de07df7e7a3fe14808cef90a7cc0d91

To use this authentication method make sure that the {chttpd_auth, proxy_authentication_handler} value in added to the list of the active chttpd/authentication_handlers:

[chttpd]
authentication_handlers = {chttpd_auth, cookie_authentication_handler}, {chttpd_auth, proxy_authentication_handler}, {chttpd_auth, default_authentication_handler}

Anonymous user #

You can configure access to your db to anonymous users. To achieve this you must provide the following option (and don't set username and password to CouchDbClient constructor):

[chttpd]
require_valid_user = false

Otherwise, no requests will be allowed from anonymous users.

Client #

You can communicate with the server directly if you wish via the http client methods such as get() and post(), however, other classes provide functions which can abstract away the particulars of HTTP, therefore using these client methods directly is not the way you will typically use this library.

Every supported method: HEAD, GET, POST, PUT and COPY - has an Accept header with default value as application/json, and POST and PUT both have a Content-Type header with default value as application/json. You can override this if you need.

All requests, both those by the basic http methods, as well as those by the other classes we will go over in a moment, return a specific ...Response object (see below). It contains various fields, about which you can find in package API.

Some method returns DbResponse object (primary for all responses). It is contain an DbResponse.json property (Map type) that contain JSON that was sent by CouchDB, DbResponse.raw property (String type) for responses that aren't valid JSON (numbers, lists, files) and DbResponse.headers property that contains headers of the response. In order to gets concrete object representation of the response you may call methods of the DbResponse class that can return:

- ServerModelResponse
- DatabaseModelResponse
- DocumentModelResponse
- DesignDocumentModelResponse
- LocalDocumentModelResponse
- ErrorResponse

Each of these class have specific properties that can be provided by CouchDB according to categories of API described below.

Categories #

All of the API is divided into five areas or categories, each representing a different aspect of the database overall. These five categories are:

1. Server
2. Database
3. Documents
4. Design documents
5. Local documents
1: Server #

Represented by the ServerModel class. This class provides server-level interaction with CouchDB, such as managing replication or obtaining basic information about the server. Also it includes info about authentication and current user (methods in CouchDbClient class).

2: Database #

A Database in CouchDB is a single document store located on the given database server. This part of the API is represented by the DatabaseModel class. You will use this class for interacting with your data on a database level; for example creating a new database or preforming a query to search for certain documents.

3: Documents #

You will use the DocumentModel class to interact with the data on a document level. This would include functions such as fetching a specific document, adding a new document, or attaching a file to a document. Note that this class does not model the documents themselves, but rather your interactions with them. The documents themselves are represented as Maps.

4: Design Documents #

Represented by the DesignDocumentModel, design documents provide views of data in the database.

5: Local Documents #

Local documents are no different than normal documents, with the exception that they are not copied to other instances of CouchDB during replication. You will interact with them via the LocalDocumentModel class.

CORS #

CORS is a method of enabling a web app to talk to a server other than the server hosting it. It is only necessary if the application is running in the browser.

CouchDB Server Configuration for CORS #

If the application isn't on the same origin with CouchDB instance (or you using different ports on server), then the remote CouchDB must be configured with the following options:

[httpd]
enable_cors = true
[cors]
origins = *
credentials = true
methods = GET, PUT, POST, HEAD, DELETE, COPY
headers = accept, authorization, content-type, origin, referer, x-csrf-token

Change these settings either in Fauxton configuration utility or in the CouchDb local.ini file. For better security, specify specific domains instead of * in the origins section.

Browser Client Configuration for CORS #

Depending on the browser, you might also need to pass cors=true to the CouchBdClient constructor. However, most of the time the browser will handle this for you and this shouldn't be necessary. In fact, it might cause an "Unsafe Header" message in the browser console.

Usage #

A simple usage example:

import 'package:couchdb/couchdb.dart';

Future<void> main() async {
  final client = CouchDbClient(username: 'name', password: 'password');
  final dbModel = DatabaseModel(client);
  final docModel = DocumentModel(client);

  try {
    final DatabaseModelResponse response1 = await dbModel.allDocs('some_db');

    for (var i in response1.rows) {
      // Some code here
    }

    final DocumentModelResponse response2 = await docModel.doc('another_db', 'some_id');

    var thing = response2.json['some_attribute'];

  } on CouchDbException catch (e) {
    print('$e - error');
  }
}

Features and bugs #

Please file feature requests and bugs at the issue tracker.

With ❤️ to CouchDB

0.5.5 #

  • Change own rules of analysis_options.yaml to pedantic package.

0.5.4 #

  • Convert DbResponse result object directly to DatabaseModelResponse in changesIn() and postChangesIn() methods of DatabaseModel class.
  • Update supported Dart SDK to >=2.2.0 <3.0.0.

0.5.3 #

  • Add missing parameters to DatabaseModel.allDocs(). Thanks to dominickj-tdi.
  • Fix pana warnings.

0.5.2 #

  • Added a path parameter to the CouchDbClient constructor. Thanks to dominickj-tdi.
  • Fixed bugs in CouchDBClient.copy() and DocumentModel.copyDoc(). Thanks to dominickj-tdi.
  • Update README.

0.5.1 #

  • Add possibility to connect to CouchDb as anonymous user.
  • Rewrite methods of model classes to return more concrete response. Thanks to dominickj-tdi.
  • Update README.

0.5.0 #

  • Make username and password parameters of CouchDbClient @required and add scheme parameter.
  • Add CouchDbClient.fromString and CouchDbClient.fromUri constructors.
  • Fix passing to CouchDbClient(...) constructor value of host parameter with protocol like http://0.0.0.0 according to this issue.
  • Remove origin parameter from CouchDbClient constructors.
  • Add CONTRIBUTING.

0.4.3+1 #

  • Downgrade meta dependency to ^1.1.6 according to this issue.

0.4.3 #

  • Change signature of CouchDbClient to provide origin parameter.
  • Small fix of docs.

0.4.2 #

  • Fix secret encoding for non-proxy authentication.
  • Make most fields in CouchDbClient final.
  • Add shards(), shard() and synchronizeShards() methods to DatabaseModel class.
  • Fix Origin construction.

0.4.1 #

  • Add secret field to CouchDbClient class for proxy authentication.
  • Edit README.

0.4.0 #

  • Add cookie authentication.
  • Add proxy authentication.
  • Add authenticate(), logout() and userInfo() methods to CouchDbClient class.
  • Add related to authentication fields to ServerModelResponse class.

0.3.0 #

  • Unit CouchDbWebClient and CouchDbServerClient to CouchDbClient class.
  • Add streamed() method to CouchDbClient class.
  • Change DatabaseModel.changesIn() and DatabaseModel.postChangesIn() methods to return stream of event responses (fix for alive connection).
  • Makes all fields of ...Response classes final.

0.2.1 #

  • Fix cast revsDiff property in DbResponse class.

0.2.0 #

  • Split DbResponse to five classes corresponds to categories of CouchDB:

      1. Server
      2. Database
      3. Documents
      4. Design documents
      5. Local documents
    
  • Change signatures of some methods (check your code for error and reference to Docs).

  • Add purgedInfosLimit() and setPurgedInfosLimit() to DatabaseModel class.

  • Improve docs in API docs (add return's JSON example).

  • Move headers to separate field in DbResponse from json.

  • Improved README.

0.1.4+1 #

  • Downgrade required Dart SDK to 2.1.0-dev.9.4.

0.1.4 #

  • Move cors field to CouchDbWebClient class.
  • Remove cors parameter from constructor of CouchDbServerClient and CouchDbBaseClient classes.

0.1.3 #

  • Add _headers field, headers getter and improve modifyRequestHeaders() method of CouchDbBaseClient class.
  • Move fields and getters from CouchDb(Server/Web)Client to CouchDbBaseClient.
  • Remove _client from CouchDb(Server/Web)Client and change constructors from being factory to usual.
  • Add cors field to CouchDbBaseClient class and its constructor.

0.1.2 #

  • Improve README.
  • Rename getAllDocs() to allDocs(), getAllDesignDocs() to allDesignDocs(), getBulkDocs() to bulkDocs(), getDocsByKeys() to docsByKeys() methods of DatabaseModel class.
  • Rename getDesignDoc() to designDoc(), getAttachment() to attachment() methods of DesignDocumentModel class.
  • Rename getDoc() to doc(), getAttachment() to attachment() methods of DocumentModel class.
  • Rename getLocalDocs() to localDocs(), getLocalDocsWithKeys() to localDocsWithKeys(), getLocalDoc() to localDoc() methods of LocalDocumentModel class.
  • Rename getClusterSetup() to clusterSetupStatus() method of ServerModel class.
  • Add includeDocs parameter to allDocs() method of DatabaseModel class.

0.1.1 #

  • Small changes that don't touch main classes.

0.1.0 #

  • Introducing beta-version of library.
  • Implement all methods of ServerModel class.
  • Implement all methods of DesignDocumentModel class.
  • Add library description to CouchDb(Server/Web)Client classes.
  • Add raw field to DbResponse class (prior rawBody).
  • Change body parameter of post() method in CouchDb(Server/Web)Client to Object type.

0.0.8 #

  • Implements schedulerJobs(), schedulerDocs(), schedulerDocsWithReplicatorDbName(), schedulerDocsWithDocId(), nodeStats(), systemStatsForNode(), up() and uuids() methods of ServerModel class.
  • Add some fields to DbResponse class.

0.0.7 #

  • Change toString() method of CouchDbException class - it shows error code, name error and reason.
  • Add allNodes, clusterNodes, history, replicationIdVersion, sessionId and sourceLastSeq fields to DbResponse class.
  • Implements configureCouchDb(), dbUpdates(), membership() and replicate() methods of ServerModel class.

0.0.6 #

  • Moving CouchDbWebClient and CouchDbServerClient to the separate export.
  • Delete rawBody field from DbResponse class.
  • Add state field to DbResponse class.
  • Implements couchDbInfo(), activeTasks(), allDbs(), dbsInfo() and getClusterSetup() methods of ServerModel class.
  • Small changes in CouchDb(Server/Web)Client classes.

0.0.5 #

  • Implement CouchDbWebClient class for interacting with CouchDB.
  • Moving all examples to example/README.md.

0.0.4 #

  • Implements attachmentInfo(), getAttachment(), insertAttachment() and deleteAttachment() methods of DocumentModel class.
  • Implement setRevsLimit() method of DatabaseModel class.
  • Method put() now accept any body type.
  • Non-json response body now available in rawBody field of DbResponse class.

0.0.3 #

  • Implements insertDoc(), deleteDoc() and copyDoc() methods of DocumentModel class.
  • All methods of CouchDb(Server/Web)Client can set custom headers.

0.0.2 #

  • Implements docInfo() and getDoc() methods of DocumentModel class.
  • Add documentation to DatabaseModel methods.
  • Add opportunity to add headers to head() method of CouchDb(Server/Web)Client classes.

0.0.1 #

  • Initial version.
  • Implement CouchDbServerClient for interacting with CouchDB.
  • Implements DatabaseBaseModel methods.

example/README.md

Server #

import 'package:couchdb/couchdb.dart';

Future<void> main() async {
  final client = CouchDbClient(username: 'name', password: 'password');
  final dbModel = DatabaseModel(client);
  final docModel = DocumentModel(client)

  try {
    final DatabaseModelResponse response1 = await dbModel.allDocs('some_db');

    for (var i in response1.rows) {
      // Some code here
    }

    final DocumentModelResponse response2 = await docModel.doc('another_db', 'some_id');

    var thing = response2.doc['some_attribute'];

  } on CouchDbException catch (e) {
    print('$e - error');
  }
}

Browser #

import 'dart:html';

import 'package:couchdb/couchdb.dart';

Future<void> main(List<String> args) async {
  final ButtonElement btn = querySelector('#data');
  final DivElement output = querySelector('#output');

  final c = CouchDbClient(username: 'name', password: 'pass', cors: true);
  final dm = DocumentModel(c);

  btn.onClick.listen((event) async {
  try {
    final DocumentModelResponse response1 = await dbModel.doc('some_db', 'some_doc_id');

    final Map<String, Object> doc = response1.doc;

    // Some code here

    // There properties are extracted from [doc] in order to gets direct access
    final String id = response1.id;
    final String rev = response1.rev;
    final Object attachment = response1.attachment;

    // Another code here

  } on CouchDbException catch (e) {
      window.console.log('${e.code} - error');
    }
  });
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  couchdb: ^0.5.5

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter pub get

Alternatively, your editor might support pub get or flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:couchdb/couchdb.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
67
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
83
Learn more about scoring.

We analyzed this package on Aug 21, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.4.0
  • pana: 0.12.19

Platforms

Detected platforms: Flutter, web, other

No platform restriction found in primary library package:couchdb/couchdb.dart.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.2.0 <3.0.0
crypto ^2.0.6 2.1.2
http ^0.12.0 0.12.0+2
meta ^1.1.6 1.1.7
Transitive dependencies
async 2.3.0
charcode 1.1.2
collection 1.14.12
convert 2.1.1
http_parser 3.1.3
path 1.6.4
source_span 1.5.5
string_scanner 1.0.5
term_glyph 1.1.0
typed_data 1.1.6
Dev dependencies
pedantic ^1.7.0 1.8.0+1
test ^1.5.3