Added some missing api from 6.0.9 version:

PouchDB.replicate()
PouchDB.sync()
PouchDB.defaults()
PouchDB.on() Events
db.info()
db.sync()
db.replicate.to()|from()
db.changes()
db.close()
db.putAttachment()
db.getAttachment()
db.removeAttachment()

Also updated many existing api options and responses

Added replication plugin definitions
Added find plugin definitions v0.10.0
This commit is contained in:
Jakub Navrátil 2016-11-21 23:13:40 +01:00 committed by geppy
parent 66faea1770
commit 126e55128b
9 changed files with 931 additions and 53 deletions

View File

@ -1,8 +1,10 @@
// Type definitions for pouchdb-core v5.4.4
// Type definitions for pouchdb-core v6.0.7
// Project: https://pouchdb.com/
// Definitions by: Andy Brown <https://github.com/AGBrown>, Brian Geppert <https://github.com/geppy>, Frederico Galvão <https://github.com/fredgalvao>
// Definitions by: Jakub Navratil <https://github.com/trubit>, Andy Brown <https://github.com/AGBrown>, Brian Geppert <https://github.com/geppy>, Frederico Galvão <https://github.com/fredgalvao>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
declare namespace PouchDB {
namespace Core {
interface Error {
@ -13,10 +15,11 @@ declare namespace PouchDB {
type AnyCallback = Callback<any, any>;
type DocumentId = string;
type DocumentKey = string;
type AttachmentId = string;
type RevisionId = string;
type Availability = 'available' | 'compacted' | 'not compacted' | 'missing';
type Attachment = string | ArrayBuffer;
type Encodable = { [propertyName: string]: any };
type Attachment = string | Blob | Buffer;
interface Options {
ajax?: Configuration.RemoteRequesterConfiguration;
@ -34,6 +37,14 @@ declare namespace PouchDB {
}
interface DatabaseInfo {
/** Name of the database you gave when you called new PouchDB(), and also the unique identifier for the database. */
db_name: string;
/** Total number of non-deleted documents in the database. */
doc_count: number;
/** Sequence number of the database. It starts at 0 and gets incremented every time a document is added or modified */
update_seq: number;
}
interface Revision<Content> {
@ -64,12 +75,62 @@ declare namespace PouchDB {
ids: RevisionId[];
start: number;
}
/** Attachments where index is attachmentId */
_attachments?: Attachments;
}
interface AttachmentResponse {
content_type: string;
/** MD5 hash, starts with "md5-" prefix */
digest: string;
/** Only present if `attachments` was `false`. */
stub?: boolean;
/** Only present if `attachments` was `false`. */
length?: number;
/**
* Only present if `attachments` was `true`.
* {string} if `binary` was `false`
* {Blob|Buffer} if `binary` was `true`
*/
data?: Attachment;
}
interface Attachments {
[attachmentId: string]: AttachmentResponse;
}
type NewDocument<Content extends Encodable> = Content;
type Document<Content extends Encodable> = Content & IdMeta;
type ExistingDocument<Content extends Encodable> =
Document<Content> & RevisionIdMeta;
/** Existing doc or just object with `_id` and `_rev` */
type RemoveDocument = Encodable & IdMeta & RevisionIdMeta;
type PostDocument<Content extends Encodable> = NewDocument<Content> & {
filters?: {[filterName: string]: string};
views?: {[viewName: string]: string};
/** You can update an existing doc using _rev */
_rev?: RevisionId;
_attachments?: {[attachmentId: string]: PutAttachment};
};
type PutDocument<Content extends Encodable> = PostDocument<Content> & ChangesMeta & {
_id?: DocumentId;
};
interface PutAttachment {
content_type: string;
data: Attachment;
}
interface AllDocsOptions extends Options {
/** Include attachment data for each document.
*
@ -118,9 +179,11 @@ declare namespace PouchDB {
inclusive_end?: boolean;
}
interface AllDocsMeta {
_attachments?: {
[attachmentId: string]: Attachment;
};
/** Only present if `conflicts` is `true` */
_conflicts?: RevisionId[];
_attachments?: Attachments;
}
interface AllDocsResponse<Content extends Core.Encodable> {
/** The `skip` if provided, or in CouchDB the actual offset */
@ -133,10 +196,104 @@ declare namespace PouchDB {
key: DocumentKey;
value: {
rev: RevisionId;
deleted?: boolean;
}
}[];
}
interface ChangesMeta {
_deleted?: boolean;
_attachments?: Attachments;
}
interface ChangesOptions {
/**
* Does "live" changes.
*/
live?: boolean;
/**
* Start the results from the change immediately after the given sequence number.
* You can also pass `'now'` if you want only new changes (when `live` is `true`).
*/
since?: 'now' | number;
/**
* Request timeout (in milliseconds).
*/
timeout?: number | false;
/** Include contents for each document. */
include_docs?: boolean;
/** Maximum number of documents to return. */
limit?: number | false;
/** Include conflicts. */
conflicts?: boolean;
/** Include attachments. */
attachments?: boolean;
/** Return attachment data as Blobs/Buffers, instead of as base64-encoded strings. */
binary?: boolean;
/** Reverse the order of the output documents. */
descending?: boolean;
/**
* For http adapter only, time in milliseconds for server to give a heartbeat to keep long connections open.
* Defaults to 10000 (10 seconds), use false to disable the default.
*/
heartbeat?: number | false;
/**
* Reference a filter function from a design document to selectively get updates.
* To use a view function, pass '_view' here and provide a reference to the view function in options.view.
* See filtered changes for details.
*/
filter?: string | {(doc: any, params: any): any};
/** Only show changes for docs with these ids (array of strings). */
doc_ids?: string[];
/**
* Object containing properties that are passed to the filter function, e.g. {"foo:"bar"},
* where "bar" will be available in the filter function as params.query.foo.
* To access the params, define your filter function like function (doc, params).
*/
query_params?: {[paramName: string]: any};
/**
* Specify a view function (e.g. 'design_doc_name/view_name' or 'view_name' as shorthand for 'view_name/view_name') to act as a filter.
* Documents counted as passed for a view filter if a map function emits at least one record for them.
* Note: options.filter must be set to '_view' for this option to work.
*/
view?: string;
}
interface ChangesResponseChange<Content extends Core.Encodable> {
id: string;
seq: number;
changes: { rev: string }[];
deleted?: boolean;
doc?: ExistingDocument<Content & ChangesMeta>;
}
interface ChangesResponse<Content extends Core.Encodable> {
status: string;
last_seq: number;
results: ChangesResponseChange<Content>[];
}
interface Changes<Content extends Core.Encodable> extends EventEmitter {
on(event: 'change', listener: (value: ChangesResponseChange<Content>) => any): this;
on(event: 'complete', listener: (value: ChangesResponse<Content>) => any): this;
on(event: 'error', listener: (value: any) => any): this;
cancel(): void;
}
interface DestroyOptions extends Options {
}
@ -150,7 +307,14 @@ declare namespace PouchDB {
/** Include a list of revisions of the document, and their
* availability. */
revs_info?: boolean;
/** Include attachment data. */
attachments?: boolean;
/** Return attachment data as Blobs/Buffers, instead of as base64-encoded strings. */
binary?: boolean;
}
interface GetOpenRevisions extends Options {
/** Fetch all leaf revisions if open_revs="all" or fetch all leaf
* revisions specified in open_revs array. Leaves will be returned
@ -170,6 +334,10 @@ declare namespace PouchDB {
interface InfoOptions extends Options {
}
interface RemoveAttachmentResponse extends BasicResponse {
rev: Core.RevisionId;
}
}
/**
@ -245,63 +413,107 @@ declare namespace PouchDB {
RemoteDatabaseConfiguration;
}
/** @todo: remove nodejs dep. */
interface EventEmitter extends NodeJS.EventEmitter {
}
interface Static {
interface Static extends EventEmitter {
plugin(plugin: Plugin): Static;
version: string;
on(event: 'created', listener: (dbName: string) => any): this;
on(event: 'destroyed', listener: (dbName: string) => any): this;
new<Content extends Core.Encodable>(name?: string,
options?: Configuration.DatabaseConfiguration): Database<Content>;
/**
* The returned object is a constructor function that works the same as PouchDB,
* except that whenever you invoke it (e.g. with new), the given options will be passed in by default.
*/
defaults(options: Configuration.DatabaseConfiguration): {
new<Content extends Core.Encodable>(name?: string,
options?: Configuration.DatabaseConfiguration): Database<Content>;
}
}
interface Database<Content extends Core.Encodable> {
/** Fetch all documents matching the given key. */
allDocs(options: Core.AllDocsWithKeyOptions):
Promise<Core.AllDocsResponse<Content>>;
/** Fetch all documents matching any of the given keys. */
allDocs(options: Core.AllDocsWithKeysOptions):
Promise<Core.AllDocsResponse<Content>>;
/** Fetch all documents matching the given key range. */
allDocs(options: Core.AllDocsWithinRangeOptions):
Promise<Core.AllDocsResponse<Content>>;
/** Fetch all documents. */
allDocs(options?: Core.AllDocsOptions):
Promise<Core.AllDocsResponse<Content>>;
bulkDocs(docs: Core.Document<Content>[],
options: Core.PutOptions | void,
/**
* Create, update or delete multiple documents. The docs argument is an array of documents.
* If you omit an _id parameter on a given document, the database will create a new document and assign the ID for you.
* To update a document, you must include both an _id parameter and a _rev parameter,
* which should match the ID and revision of the document on which to base your updates.
* Finally, to delete a document, include a _deleted parameter with the value true.
*/
bulkDocs(docs: Core.PutDocument<Content>[],
options: Core.PutOptions | null,
callback: Core.Callback<Core.Error, Core.Response[]>): void;
bulkDocs(docs: Core.Document<Content>[],
/**
* Create, update or delete multiple documents. The docs argument is an array of documents.
* If you omit an _id parameter on a given document, the database will create a new document and assign the ID for you.
* To update a document, you must include both an _id parameter and a _rev parameter,
* which should match the ID and revision of the document on which to base your updates.
* Finally, to delete a document, include a _deleted parameter with the value true.
*/
bulkDocs(docs: Core.PutDocument<Content>[],
options?: Core.PutOptions): Promise<Core.Response[]>;
/** Compact the database */
compact(options?: Core.CompactOptions): Promise<Core.Response>;
/** Compact the database */
compact(options: Core.CompactOptions,
callback: Core.Callback<Core.Error, Core.Response>): void;
/** Destroy the database */
destroy(options: Core.DestroyOptions | void,
callback: Core.AnyCallback): void;
/** Destroy the database */
destroy(options?: Core.DestroyOptions | void): Promise<void>;
/** Fetch a document */
get(docId: Core.DocumentId,
options: Core.GetOpenRevisions): Promise<Core.Revision<Content>[]>;
get(docId: Core.DocumentId,
options: Core.GetOpenRevisions,
callback: Core.Callback<any,
Core.Revision<Content>[]>): void;
options: Core.GetOptions | null,
callback: Core.Callback<any, Core.Document<Content> & Core.GetMeta>
): void;
/** Fetch a document */
get(docId: Core.DocumentId,
options: Core.GetOptions
): Promise<Core.Document<Content> & Core.GetMeta>;
/** Fetch a document */
get(docId: Core.DocumentId): Promise<Core.Document<Content> & Core.GetMeta>;
/** Fetch document open revs */
get(docId: Core.DocumentId,
options: Core.GetOptions,
callback: Core.Callback<any, Core.Document<Content> & Core.GetMeta>
): void;
options: Core.GetOpenRevisions,
callback: Core.Callback<any, Core.Revision<Content>[]>): void;
/** Fetch document open revs */
get(docId: Core.DocumentId,
options: void,
callback: Core.Callback<any, Core.Document<Content>>): void;
get(docId: Core.DocumentId): Promise<Core.Document<Content>>;
options: Core.GetOpenRevisions): Promise<Core.Revision<Content>[]>;
/** Create a new document without providing an id.
*
@ -310,11 +522,20 @@ declare namespace PouchDB {
* (because your _ids are random).
*
* @see {@link https://pouchdb.com/2014/06/17/12-pro-tips-for-better-code-with-pouchdb.html|PouchDB Pro Tips}
* */
post(doc: Core.NewDocument<Content>,
options: Core.PostOptions | void,
*/
post(doc: Core.PostDocument<Content>,
options: Core.PostOptions | null,
callback: Core.Callback<Core.Error, Core.Response>): void;
post(doc: Core.NewDocument<Content>,
/** Create a new document without providing an id.
*
* You should prefer put() to post(), because when you post(), you are
* missing an opportunity to use allDocs() to sort documents by _id
* (because your _ids are random).
*
* @see {@link https://pouchdb.com/2014/06/17/12-pro-tips-for-better-code-with-pouchdb.html|PouchDB Pro Tips}
*/
post(doc: Core.PostDocument<Content>,
options?: Core.PostOptions): Promise<Core.Response>;
/** Create a new document or update an existing document.
@ -323,35 +544,162 @@ declare namespace PouchDB {
* otherwise a conflict will occur.
* There are some restrictions on valid property names of the documents.
* If you try to store non-JSON data (for instance Date objects) you may
* see inconsistent results. */
put(doc: Core.Document<Content>,
id: Core.DocumentId | void,
revision: Core.RevisionId | void,
options: Core.PutOptions | void,
* see inconsistent results.
*/
put(doc: Core.PutDocument<Content>,
id: Core.DocumentId | null,
revision: Core.RevisionId | null,
options: Core.PutOptions | null,
callback: Core.Callback<Core.Error, Core.Response>): void;
put(doc: Core.Document<Content>,
/** Create a new document or update an existing document.
*
* If the document already exists, you must specify its revision _rev,
* otherwise a conflict will occur.
* There are some restrictions on valid property names of the documents.
* If you try to store non-JSON data (for instance Date objects) you may
* see inconsistent results.
*/
put(doc: Core.PutDocument<Content>,
id?: Core.DocumentId,
revision?: Core.RevisionId,
options?: Core.PutOptions): Promise<Core.Response>;
/** Remove a doc from the database */
remove(doc: Core.Document<Content>,
remove(doc: Core.RemoveDocument,
options: Core.Options,
callback: Core.Callback<Core.Error, Core.Response>): void;
/** Remove a doc from the database */
remove(docId: Core.DocumentId,
revision: Core.RevisionId,
options: Core.Options,
callback: Core.Callback<Core.Error, Core.Response>): void;
remove(doc: Core.Document<Content>,
/** Remove a doc from the database */
remove(doc: Core.RemoveDocument,
options?: Core.Options): Promise<Core.Response>;
/** Remove a doc from the database */
remove(docId: Core.DocumentId,
revision: Core.RevisionId,
options?: Core.Options): Promise<Core.Response>;
/** Get database information */
info(options: Core.InfoOptions | void,
info(options: Core.InfoOptions | null,
callback: Core.Callback<any, Core.DatabaseInfo>): void;
/** Get database information */
info(options?: Core.InfoOptions): Promise<Core.DatabaseInfo>;
/**
* A list of changes made to documents in the database, in the order they were made.
* It returns an object with the method cancel(), which you call if you dont want to listen to new changes anymore.
*
* It is an event emitter and will emit a 'change' event on each document change,
* a 'complete' event when all the changes have been processed, and an 'error' event when an error occurs.
* Calling cancel() will unsubscribe all event listeners automatically.
*/
changes(options: Core.ChangesOptions | null,
callback: Core.Callback<any, Core.Changes<Content>>): void;
/**
* A list of changes made to documents in the database, in the order they were made.
* It returns an object with the method cancel(), which you call if you dont want to listen to new changes anymore.
*
* It is an event emitter and will emit a 'change' event on each document change,
* a 'complete' event when all the changes have been processed, and an 'error' event when an error occurs.
* Calling cancel() will unsubscribe all event listeners automatically.
*/
changes(options?: Core.ChangesOptions): Core.Changes<Content>;
/** Close the database */
close(callback: Core.AnyCallback): void;
/** Close the database */
close(): Promise<void>;
/**
* Attaches a binary object to a document.
* This method will update an existing document to add the attachment, so it requires a rev if the document already exists.
* If the document doesnt already exist, then this method will create an empty document containing the attachment.
*/
putAttachment(docId: Core.DocumentId,
attachmentId: Core.AttachmentId,
rev: Core.RevisionId,
attachment: Core.Attachment,
type: string,
callback: Core.Callback<Core.Error, Core.Response>): void;
/**
* Attaches a binary object to a document.
* This method will update an existing document to add the attachment, so it requires a rev if the document already exists.
* If the document doesnt already exist, then this method will create an empty document containing the attachment.
*/
putAttachment(docId: Core.DocumentId,
attachmentId: Core.AttachmentId,
rev: Core.RevisionId,
attachment: Core.Attachment,
type: string): Promise<Core.Response>;
/**
* Attaches a binary object to a document.
* This method will update an existing document to add the attachment, so it requires a rev if the document already exists.
* If the document doesnt already exist, then this method will create an empty document containing the attachment.
*/
putAttachment(docId: Core.DocumentId,
attachmentId: Core.AttachmentId,
attachment: Core.Attachment,
type: string,
callback: Core.Callback<Core.Error, Core.Response>): void;
/**
* Attaches a binary object to a document.
* This method will update an existing document to add the attachment, so it requires a rev if the document already exists.
* If the document doesnt already exist, then this method will create an empty document containing the attachment.
*/
putAttachment(docId: Core.DocumentId,
attachmentId: Core.AttachmentId,
attachment: Core.Attachment,
type: string): Promise<Core.Response>;
/** Get attachment data */
getAttachment(docId: Core.DocumentId,
attachmentId: Core.AttachmentId,
options: { rev?: Core.RevisionId},
callback: Core.Callback<Core.Error, Blob | Buffer>): void;
/** Get attachment data */
getAttachment(docId: Core.DocumentId,
attachmentId: Core.AttachmentId,
options: { rev?: Core.RevisionId}): Promise<Blob | Buffer>;
/** Get attachment data */
getAttachment(docId: Core.DocumentId,
attachmentId: Core.AttachmentId,
callback: Core.Callback<Core.Error, Blob | Buffer>): void;
/** Get attachment data */
getAttachment(docId: Core.DocumentId,
attachmentId: Core.AttachmentId): Promise<Blob | Buffer>;
/** Delete an attachment from a doc. You must supply the rev of the existing doc. */
removeAttachment(docId: Core.DocumentId,
attachmentId: Core.AttachmentId,
rev: Core.RevisionId,
callback: Core.Callback<Core.Error, Core.RemoveAttachmentResponse>): void;
/** Delete an attachment from a doc. You must supply the rev of the existing doc. */
removeAttachment(docId: Core.DocumentId,
attachmentId: Core.AttachmentId,
rev: Core.RevisionId): Promise<Core.RemoveAttachmentResponse>;
/** Given a set of document/revision IDs, returns the document bodies (and, optionally, attachment data) for each ID/revision pair specified. */
bulkGet(options: any,
callback: Core.Callback<any, any>): void;
/** Given a set of document/revision IDs, returns the document bodies (and, optionally, attachment data) for each ID/revision pair specified. */
bulkGet(options: any): Promise<any>;
}
}

View File

@ -17,7 +17,7 @@ namespace PouchDBCoreTests {
isString(value.rev);
// check document property
isNumber(doc.foo);
isNumber(doc!.foo);
})
});
@ -38,9 +38,9 @@ namespace PouchDBCoreTests {
function testBulkDocs() {
const db = new PouchDB<MyModel>();
type MyModel = { property: 'someProperty '};
let model: PouchDB.Core.Document<MyModel>;
let model2: PouchDB.Core.Document<MyModel>;
type MyModel = { property: string };
let model = { property: 'test' };
let model2 = { property: 'test' };
db.bulkDocs([model, model2]).then((result) => {
result.forEach(({ ok, id, rev }) => {
@ -74,8 +74,8 @@ namespace PouchDBCoreTests {
}
function testBasics() {
type MyModel = { property: 'someProperty '};
let model: PouchDB.Core.Document<MyModel>;
type MyModel = { property: string };
let model = { property: 'test' };
const id = 'model';
const db = new PouchDB<MyModel>();
@ -102,10 +102,10 @@ namespace PouchDBCoreTests {
}
function testRemove() {
type MyModel = { rev: 'rev', property: 'someProperty '};
let model: PouchDB.Core.Document<MyModel>;
type MyModel = { property: string };
const id = 'model';
const rev = 'rev';
let model = { _id: id, _rev: rev, existingDocProperty: 'any' };
const db = new PouchDB<MyModel>();
@ -127,4 +127,53 @@ namespace PouchDBCoreTests {
// Callback version with docId and rev
db.remove(id, rev, {}, (res: PouchDB.Core.Response) => {});
}
function testChanges() {
type MyModel = { foo: string };
const db = new PouchDB<MyModel>();
db.changes({
live: true,
since: 'now',
timeout: 1,
include_docs: true,
limit: 1,
conflicts: true,
attachments: true,
binary: true,
descending: true,
heartbeat: 1,
filter: '',
doc_ids: [''],
query_params: {paramName: 'any'},
view: ''
})
.on('change', (change) => {
let _id: string = change.id;
let _seq: number = change.seq;
let _changes: { rev: string }[] = change.changes;
let _foo: string = change.doc!.foo;
let _deleted: boolean | undefined = change.doc!._deleted;
let _attachments: PouchDB.Core.Attachments | undefined = change.doc!._attachments;
})
.on('complete', (info) => {
let _status: string = info.status;
let _last_req: number = info.last_seq;
let change = info.results[0];
let _id: string = change.id;
let _seq: number = change.seq;
let _changes: { rev: string }[] = change.changes;
let _deleted: boolean | undefined = change.doc!._deleted;
let _attachments: PouchDB.Core.Attachments | undefined = change.doc!._attachments;
});
db.changes({
since: 1,
timeout: false,
limit: false,
heartbeat: false,
filter: (doc: any, params: any) => {}
});
}
}

View File

@ -3,7 +3,7 @@
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"strictNullChecks": false,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
@ -16,4 +16,4 @@
"index.d.ts",
"pouchdb-core-tests.ts"
]
}
}

View File

@ -0,0 +1,72 @@
/// <reference path="./pouchdb-find.d.ts" />
namespace PouchDBFindTests {
function testFind() {
const db = new PouchDB<{ foo: number }>();
db.find({
selector: {},
fields: ['fieldName'],
sort: ['fieldName'],
limit: 1,
skip: 1
})
db.find({
selector: {},
sort: [{'fieldName': 'asc'}]
});
// test combinations of selectors
db.find({
selector: {
// test id
_id: {
gt: null
},
// conditions
foo: {
$lt: null,
$gt: null,
$lte: null,
$gte: null,
$eq: null,
$ne: null,
$elemMatch: null,
$exists: true,
$type: "null",
$in: ["string", null, 1, true, {}, []],
$nin: ["string", null, 1, true, {}, []],
$size: 5,
$mod: [1, 2],
$regex: "pattern",
$all: ["string", null, 1, true, {}, []]
},
// value
bar: 'any value',
// combinatons
$and: [],
$or: [],
$nor: [],
$not: [],
// sub combinations
sub: {
$and: [
{
foo: 'bar',
bar: {
$gt: null
}
}
]
}
}
});
}
}

188
pouchdb-find/pouchdb-find.d.ts vendored Normal file
View File

@ -0,0 +1,188 @@
// Type definitions for pouchdb-find v0.10.0
// Project: https://pouchdb.com/
// Definitions by: Jakub Navratil <https://github.com/trubit>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../pouchdb-core/pouchdb-core.d.ts" />
declare namespace PouchDB {
namespace Find {
interface ConditionOperators {
/** Match fields "less than" this one. */
$lt?: any;
/** Match fields "greater than" this one. */
$gt?: any;
/** Match fields "less than or equal to" this one. */
$lte?: any;
/** Match fields "greater than or equal to" this one. */
$gte?: any;
/** Match fields equal to this one. */
$eq?: any;
/** Match fields not equal to this one. */
$ne?: any;
/** True if the field should exist, false otherwise. */
$exists?: boolean;
/** One of: "null", "boolean", "number", "string", "array", or "object". */
$type?: "null" | "boolean" | "number" | "string" | "array" | "object";
/** The document field must exist in the list provided. */
$in?: any[];
/** The document field must not exist in the list provided. */
$nin?: any[];
/** Special condition to match the length of an array field in a document. Non-array fields cannot match this condition. */
$size?: number;
/** Divisor and Remainder are both positive or negative integers.
* Non-integer values result in a 404 status.
* Matches documents where (field % Divisor == Remainder) is true, and only when the document field is an integer.
* [divisor, remainder]
* */
$mod?: [number, number];
/** A regular expression pattern to match against the document field. Only matches when the field is a string value and matches the supplied regular expression. */
$regex?: string;
/** Matches an array value if it contains all the elements of the argument array. */
$all?: any[];
$elemMatch?: ConditionOperators;
}
interface CombinationOperators {
/** Matches if all the selectors in the array match. */
$and?: Selector[];
/** Matches if any of the selectors in the array match. All selectors must use the same index. */
$or?: Selector[];
/** Matches if the given selector does not match. */
$not?: Selector;
/** Matches if none of the selectors in the array match. */
$nor?: Selector[];
}
interface Selector extends CombinationOperators {
[field: string]: Selector | Selector[] | ConditionOperators | any;
_id?: ConditionOperators;
}
interface FindRequest<Content extends Core.Encodable> {
/** Defines a selector to filter the results. Required */
selector: Selector;
/** Defines a list of fields that you want to receive. If omitted, you get the full documents. */
fields?: string[];
/** Defines a list of fields defining how you want to sort. Note that sorted fields also have to be selected in the selector. */
sort?: Array<string|{[propName: string]: 'asc' | 'desc'}>;
/** Maximum number of documents to return. */
limit?: number;
/** Number of docs to skip before returning. */
skip?: number;
}
interface FindResponse<Content extends Core.Encodable> {
docs: Core.Document<Content>[];
}
interface CreateIndexOptions {
index: {
/** List of fields to index */
fields: string[];
/** Name of the index, auto-generated if you don't include it */
name?: string;
/** Design document name (i.e. the part after '_design/', auto-generated if you don't include it */
ddoc?: string;
/** Only supports 'json', and it's also the default */
type?: string;
}
}
interface CreateIndexResponse<Content extends Core.Encodable> {
result: string;
}
interface Index {
/** Name of the index, auto-generated if you don't include it */
name: string;
/** Design document name (i.e. the part after '_design/', auto-generated if you don't include it */
ddoc: string | null;
/** Only supports 'json' */
type: string;
def: {
fields: {
[fieldName: string]: string
}[]
}
}
interface GetIndexesResponse<Content extends Core.Encodable> {
indexes: Index[]
}
interface DeleteIndexOptions {
/** Name of the index */
name: string;
/** Design document name */
ddoc: string;
/** Default 'json' */
type?: string;
}
interface DeleteIndexResponse<Content extends Core.Encodable> {
[propertyName: string]: any;
}
}
interface Database<Content extends Core.Encodable> {
/** Query the API to find some documents. */
find(request: Find.FindRequest<Content>,
callback: Core.Callback<any, Find.FindResponse<Content>>): void;
find(request?: Find.FindRequest<Content>): Promise<Find.FindResponse<Content>>;
/** Create an index if it doesn't exist, or do nothing if it already exists. */
createIndex(index: Find.CreateIndexOptions,
callback: Core.Callback<any, Find.CreateIndexResponse<Content>>): void;
createIndex(index?: Find.CreateIndexOptions): Promise<Find.CreateIndexResponse<Content>>;
/** Get a list of all the indexes you've created. Also tells you about the special _all_docs index, i.e. the default index on the _id field. */
getIndexes(callback: Core.Callback<any, Find.GetIndexesResponse<Content>>): void;
getIndexes(): Promise<Find.GetIndexesResponse<Content>>;
/** Delete an index and clean up any leftover data on the disk. */
deleteIndex(index: Find.DeleteIndexOptions,
callback: Core.Callback<any, Find.DeleteIndexResponse<Content>>): void;
deleteIndex(index?: Find.DeleteIndexOptions): Promise<Find.DeleteIndexResponse<Content>>;
}
}
declare module 'pouchdb-find' {
const plugin: PouchDB.Plugin;
export = plugin;
}

View File

@ -0,0 +1,6 @@
{
"compilerOptions": {
"noImplicitAny": true,
"strictNullChecks": true
}
}

View File

@ -1,19 +1,216 @@
// Type definitions for pouchdb-replication v5.4.4
// Type definitions for pouchdb-replication v6.0.7
// Project: https://pouchdb.com/
// Definitions by: Andy Brown <https://github.com/AGBrown>, Brian Geppert <https://github.com/geppy>, Frederico Galvão <https://github.com/fredgalvao>
// Definitions by: Jakub Navratil <https://github.com/trubit>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="pouchdb-core" />
declare namespace PouchDB {
namespace Replication {
/** @todo When is this present? */
interface ReplicationMeta {
_replication_id: string;
_replication_state: string;
_replication_state_time: number;
_replication_stats: {};
interface ReplicateOptions {
/** If true, starts subscribing to future changes in the source database and continue replicating them. */
live?: boolean;
/**
* If true will attempt to retry replications in the case of failure (due to being offline),
* using a backoff algorithm that retries at longer and longer intervals until a connection is re-established,
* with a maximum delay of 10 minutes. Only applicable if options.live is also true.
*/
retry?: boolean;
/**
* Reference a filter function from a design document to selectively get updates.
* To use a view function, pass '_view' here and provide a reference to the view function in options.view.
* See filtered changes for details.
*/
filter?: string | {(doc: any, params: any): any};
/** Only show changes for docs with these ids (array of strings). */
doc_ids?: string[];
/**
* Object containing properties that are passed to the filter function, e.g. {"foo:"bar"},
* where "bar" will be available in the filter function as params.query.foo.
* To access the params, define your filter function like function (doc, params).
*/
query_params?: {[paramName: string]: any};
/**
* Specify a view function (e.g. 'design_doc_name/view_name' or 'view_name' as shorthand for 'view_name/view_name') to act as a filter.
* Documents counted as passed for a view filter if a map function emits at least one record for them.
* Note: options.filter must be set to '_view' for this option to work.
*/
view?: string;
/** Replicate changes after the given sequence number. */
since?: any;
/** Configure the heartbeat supported by CouchDB which keeps the change connection alive. */
heartbeat?: any;
/** Request timeout (in milliseconds). */
timeout?: number | false;
/**
* Number of change feed items to process at a time. Defaults to 100.
* This affects the number of docs and attachments held in memory and the number sent at a time to the target server.
* You may need to adjust downward if targeting devices with low amounts of memory
* e.g. or if the documents and/or attachments are large in size or if there are many conflicted revisions.
* If your documents are small in size, then increasing this number will probably speed replication up.
*/
batch_size?: number;
/**
* Number of batches to process at a time. Defaults to 10.
* This (along wtih batch_size) controls how many docs are kept in memory at a time,
* so the maximum docs in memory at once would equal batch_size × batches_limit.
*/
batches_limit?: number;
/**
* Backoff function to be used in retry replication. This is a function that takes the current
* backoff as input (or 0 the first time) and returns a new backoff in milliseconds.
* You can use this to tweak when and how replication will try to reconnect to a remote database when the user goes offline.
* Defaults to a function that chooses a random backoff between 0 and 2 seconds and doubles every time it fails to connect.
* The default delay will never exceed 10 minutes.
*/
back_off_function?: (delay: number) => number;
}
interface ReplicationEventEmitter<Content extends Core.Encodable, C, F> extends EventEmitter {
on(event: 'change', listener: (info: C) => any): this;
on(event: 'paused', listener: (err: {}) => any): this;
on(event: 'active', listener: () => any): this;
on(event: 'denied', listener: (err: {}) => any): this;
on(event: 'complete', listener: (info: F) => any): this;
on(event: 'error', listener: (err: {}) => any): this;
cancel(): void;
}
interface Replication<Content extends Core.Encodable>
extends ReplicationEventEmitter<Content, ReplicationResult<Content>, ReplicationResultComplete<Content>>,
Promise<ReplicationResultComplete<Content>> {
}
interface ReplicationResult<Content extends Core.Encodable> {
doc_write_failures: number;
docs_read: number;
docs_written: number;
last_seq: number,
start_time: Date,
ok: boolean,
errors: any[];
docs: Core.ExistingDocument<Content>[];
}
interface ReplicationResultComplete<Content extends Core.Encodable> extends ReplicationResult<Content> {
end_time: Date;
status: string;
}
interface SyncOptions extends ReplicateOptions {
push?: boolean;
pull?: boolean;
}
interface Sync<Content extends Core.Encodable>
extends ReplicationEventEmitter<Content, SyncResult<Content>, SyncResultComplete<Content>>,
Promise<SyncResultComplete<Content>> {
}
interface SyncResult<Content extends Core.Encodable> {
direction: 'push' | 'pull';
change: ReplicationResult<Content>;
}
interface SyncResultComplete<Content extends Core.Encodable> {
push?: ReplicationResultComplete<Content>;
pull?: ReplicationResultComplete<Content>;
}
}
interface Static {
/**
* Replicate data from source to target. Both the source and target can be a PouchDB instance or a string
* representing a CouchDB database URL or the name of a local PouchDB database. If options.live is true,
* then this will track future changes and also replicate them automatically.
* This method returns an object with the method cancel(), which you call if you want to cancel live replication.
*/
replicate<Content>(
source: string | Database<Content>,
target: string | Database<Content>,
options?: Replication.ReplicateOptions,
callback?: Core.Callback<any, Replication.ReplicationResultComplete<Content>>
): Replication.Replication<Content>;
/**
* Sync data from src to target and target to src. This is a convenience method for bidirectional data replication.
*
* In other words, this code:
* `PouchDB.replicate('mydb', 'http://localhost:5984/mydb')`;
* `PouchDB.replicate('http://localhost:5984/mydb', 'mydb')`;
* is equivalent to this code:
* `PouchDB.sync('mydb', 'http://localhost:5984/mydb')`;
*/
sync<Content>(
source: string | Database<Content>,
target: string | Database<Content>,
options?: Replication.SyncOptions,
callback?: Core.Callback<any, Replication.SyncResultComplete<Content>>
): Replication.Sync<Content>;
}
interface Database<Content extends Core.Encodable> {
replicate: {
/**
* Replicate data to `target`. Both the source and target can be a PouchDB instance
* or a string representing a CouchDB database URL or the name of a local PouchDB database.
* If options.live is true, then this will track future changes and also replicate them automatically.
* This method returns an object with the method cancel(), which you call if you want to cancel live replication.
*/
to<Content>(
target: string | Database<Content>,
options?: Replication.ReplicateOptions,
callback?: Core.Callback<any, Replication.ReplicationResultComplete<Content>>
): Replication.Replication<Content>;
/**
* Replicate data from `source`. Both the source and target can be a PouchDB instance
* or a string representing a CouchDB database URL or the name of a local PouchDB database.
* If options.live is true, then this will track future changes and also replicate them automatically.
* This method returns an object with the method cancel(), which you call if you want to cancel live replication.
*/
from<Content>(
source: string | Database<Content>,
options?: Replication.ReplicateOptions,
callback?: Core.Callback<any, Replication.ReplicationResultComplete<Content>>
): Replication.Replication<Content>;
};
/**
* Sync data from src to target and target to src. This is a convenience method for bidirectional data replication.
*
* In other words, this code:
* `PouchDB.replicate('mydb', 'http://localhost:5984/mydb')`;
* `PouchDB.replicate('http://localhost:5984/mydb', 'mydb')`;
* is equivalent to this code:
* `PouchDB.sync('mydb', 'http://localhost:5984/mydb')`;
*/
sync<Content>(
remote: string | Database<Content>,
options?: Replication.SyncOptions,
callback?: Core.Callback<any, Replication.SyncResultComplete<Content>>
): Replication.Sync<Content>;
}
}

View File

@ -0,0 +1,18 @@
/// <reference path="./index.d.ts" />
namespace PouchDBReplicationTests {
/** @todo make some real tests */
function testReplication() {
type Model = { foo: number };
const db = new PouchDB<Model>();
db.replicate.to('').then((res: PouchDB.Replication.ReplicationResultComplete<Model>) => {
});
db.replicate.from('').then((res: PouchDB.Replication.ReplicationResultComplete<Model>) => {
});
}
}

View File

@ -16,4 +16,4 @@
"index.d.ts",
"pouchdb-replication-tests.ts"
]
}
}