ottoman
Version:
Ottoman Couchbase ODM
271 lines (270 loc) • 10.5 kB
TypeScript
import * as couchbase from 'couchbase';
import { Schema } from '../schema';
import { ModelTypes, SearchConsistency } from '..';
import { ModelOptions } from '../model/interfaces/create-model.interface';
import { ModelMetadata } from '../model/interfaces/model-metadata.interface';
import { Bucket, BucketManager, Cluster, CollectionManager, DropBucketOptions, DropCollectionOptions, DropScopeOptions, QueryOptions, ConnectOptions as CouchbaseConnectOptions, QueryIndexManager, ViewIndexManager, Collection, NodeCallback, TransactionAttemptContext, TransactionOptions } from 'couchbase';
import { SearchQuery } from 'couchbase/dist/searchquery';
import { SearchMetaData, SearchQueryOptions, SearchResult, SearchRow } from 'couchbase/dist/searchtypes';
import { StreamableRowPromise } from 'couchbase/dist/streamablepromises';
export interface ConnectOptions extends CouchbaseConnectOptions {
connectionString: string;
bucketName: string;
}
interface OttomanConfig {
collectionName?: string;
retryCount?: number;
scopeName?: string;
idKey?: string;
modelKey?: string;
populateMaxDeep?: number;
consistency?: SearchConsistency;
maxExpiry?: number;
keyGenerator?: (params: {
metadata: ModelMetadata;
}) => string;
keyGeneratorDelimiter?: string;
}
interface EnsureIndexesOptions {
ignoreWatchIndexes?: boolean;
}
interface StartOptions {
ignoreWatchIndexes?: boolean;
}
export type OttomanEvents = 'IndexOnline';
/**
* Store default connection.
*/
export declare let __ottoman: Ottoman;
export declare let __ottomanInstances: Ottoman[];
export declare class Ottoman {
private n1qlIndexes;
private viewIndexes;
private refdocIndexes;
private readonly id;
private events;
indexOnline: Error | boolean;
indexOnlinePromise: Promise<any> | undefined;
/**
* Retrieve all register callbacks to "IndexOnline" event
*/
get indexReadyHooks(): couchbase.NodeCallback<Ottoman>[];
/**
* Register Ottoman events
* @param event the name of the event you want to listen to.
* @param fn callback function to be executed when the event trigger up.
*/
on(event: OttomanEvents, fn: NodeCallback<Ottoman>): void;
/**
* @ignore
*/
getRefdocIndexByKey: (key: any) => {
fields: string[];
}[];
/**
* @ignore
*/
registerIndex: (indexName: string, fields: any, modelName: any) => void;
/**
* @ignore
*/
registerViewIndex: (designDocName: string, indexName: string, fields: any, metadata: any) => void;
/**
* @ignore
*/
registerRefdocIndex: (fields: string[], prefix: string) => void;
config: OttomanConfig;
/**
* Bucket represents a storage grouping of data within a Couchbase Server cluster.
*/
bucket?: Bucket;
/**
* CollectionManager allows the management of collections within a Bucket.
*
* Check the
* [Collection Manager Couchbase SDK API](https://docs.couchbase.com/sdk-api/couchbase-node-client/classes/CollectionManager.html)
* documentation for more details.
*/
get collectionManager(): CollectionManager;
/**
* Gets a bucket manager for this cluster.
*
* Check the
* [Bucket Manager Couchbase SDK API](https://docs.couchbase.com/sdk-api/couchbase-node-client/classes/BucketManager.html)
* documentation for more details.
*/
get bucketManager(): BucketManager;
/**
* QueryIndexManager provides an interface for managing the query indexes on the cluster.
*
* Check the
* [Query Index Manager Couchbase SDK API](https://docs.couchbase.com/sdk-api/couchbase-node-client/classes/QueryIndexManager.html)
* documentation for more details.
*/
get queryIndexManager(): QueryIndexManager;
/**
* ViewIndexManager is an interface which enables the management of view indexes on the cluster.
*
* @deprecated
* Check the
* [View Index Manager Couchbase SDK API](https://docs.couchbase.com/sdk-api/couchbase-node-client/classes/ViewIndexManager.html)
* documentation for more details.
*/
get viewIndexManager(): ViewIndexManager;
/**
* Dictionary for all models registered on this connection.
*/
models: {};
private _cluster?;
/**
* Cluster represents an entire Couchbase Server cluster.
*/
get cluster(): Cluster;
/**
* Contains the name of the current bucket.
*/
bucketName: string;
/**
* Stores a reference to couchbase instance.
*/
couchbase: any;
constructor(config?: OttomanConfig);
/**
* Connect to Couchbase server.
* @example
* ```javascript
* import { connect } from "ottoman";
* const connection = connect("couchbase://localhost/travel-sample@admin:password");
* ```
*/
connect: (connectOptions: ConnectOptions | string) => Promise<Ottoman>;
/**
* Creates a Model on this connection.
* @example
* ```javascript
* const User = connection.model('User', { name: String }, { collectionName: 'users' });
* ```
*/
model<T = any, R = T>(name: string, schema: Schema | Record<string, unknown>, options?: ModelOptions): ModelTypes<T, R>;
/**
* dropCollection drops a collection from a scope in a bucket.
* @param collectionName
* @param scopeName
* @param options
*/
dropCollection(collectionName: string, scopeName: string, options?: DropCollectionOptions): Promise<boolean | undefined | void>;
/**
* dropScope drops a scope from a bucket.
* @param scopeName
* @param options
*/
dropScope(scopeName: string, options?: DropScopeOptions): Promise<boolean | undefined | void>;
/**
* dropBucket drops a bucket from the cluster.
* @param bucketName
* @param options
*/
dropBucket(bucketName: string, options?: DropBucketOptions): Promise<boolean | undefined | void>;
/**
* Returns a Model constructor from the given model name.
*
* @example
* ```javascript
* const User = connection.getModel('User');
* ```
*/
getModel<T = any>(name: string): ModelTypes<T>;
/**
* Return a collection from the given collectionName in this bucket
* or default collection if collectionName is missing.
*/
getCollection(collectionName?: string, scopeName?: string): Collection;
getIndexes(): Promise<couchbase.SearchIndex[]>;
searchQuery(indexName: string, query: SearchQuery, options?: SearchQueryOptions): StreamableRowPromise<SearchResult, SearchRow, SearchMetaData>;
/**
* Closes the current connection.
*
* @example
* ```javascript
* connection.close().then(() => console.log('connection closed'));
* ```
*/
close(): Promise<void>;
/**
* Executes N1QL Queries.
*
* Ottoman provides a powerful [Query Builder](docs/basic/query-builder) system to create valid N1QL queries using method chaining.
* See the example below:
*
* @example
* ```js
* const expr_where = {
* $or: [
* { address: { $like: '%57-59%' } },
* { free_breakfast: true }
* ]
* };
* const query = new Query({}, 'travel-sample');
* const n1qlQuery = query.select([{ $field: 'address' }])
* .where(expr_where)
* .build()
*
* connection.query(n1qlQuery).then(result => console.log( result ))
* ```
* The above example will run this query:
* ```sql
* SELECT address
* FROM `travel-sample`
* WHERE (address LIKE '%57-59%' OR free_breakfast = true)
* ```
*/
query(query: string, options?: QueryOptions & {
transactionContext?: TransactionAttemptContext;
}): Promise<couchbase.TransactionQueryResult<any> | couchbase.QueryResult<any>>;
/**
* `ensureCollections` will attempt to create scopes and collections to map your models to in Couchbase Server.
*/
ensureCollections(): Promise<void>;
/**
* `ensureIndexes` will attempt to create indexes defined in your schema if they do not exist.
* * @param options
* - `ignoreWatchIndexes`: by default `ensureIndexes` function will wait for indexes, but you can disabled it setting ignoreWatchIndexes to true.
*/
ensureIndexes(options?: EnsureIndexesOptions): Promise<any>;
/**
* `start` method is just a shortcut to run `ensureCollections` and `ensureIndexes`.
* @param options
* - `ignoreWatchIndexes`: by default `start` function will wait for indexes, but you can disabled it setting ignoreWatchIndexes to true.
*
* Notice: It's not required to execute the `start` method in order for Ottoman work.
*/
start(options?: StartOptions): Promise<void>;
/**
* The `$transactions` function passes a `TransactionAttemptContext` object to the transaction function.
* @param transactionFn The function to be executed as a transaction.
*
* @param config
* - `durabilityLevel`: Specifies the level of synchronous durability level.
* - `timeout`: Specifies the timeout for the transaction.
*
* @example
* ```javascript
* await otttoman.$transactions(async (ctx: TransactionAttemptContext) => {
* const user = await User.create({ name: "John Doe" }, { transactionContext: ctx });
* });
* ```
*
* Notice: You **MUST pass the `transactionContext` option in the model methods** to execute the operation(s) as a transaction.
*/
$transactions(transactionFn: (attempt: TransactionAttemptContext) => Promise<void>, config?: TransactionOptions): Promise<void>;
}
export declare const getDefaultInstance: () => Ottoman;
export declare const getOttomanInstances: () => Ottoman[];
export declare const connect: (connectOptions: ConnectOptions | string) => Promise<void>;
export declare const close: () => Promise<void>;
export declare const start: () => Promise<void>;
export declare const getModel: (name: string) => ModelTypes<any, any>;
export declare const getCollection: (collectionName?: string, scopeName?: string) => couchbase.Collection;
export declare const model: <T = any, R = T>(name: string, schema: Schema | Record<string, unknown>, options?: ModelOptions) => ModelTypes<T, R>;
export declare const searchQuery: (indexName: string, query: SearchQuery, options?: SearchQueryOptions) => StreamableRowPromise<SearchResult, SearchRow, SearchMetaData>;
export {};