mirror of
https://github.com/gosticks/DefinitelyTyped.git
synced 2026-12-03 19:51:53 +00:00
Merge remote-tracking branch 'upstream/master'
This commit is contained in:
Vendored
+172
-48
@@ -14,6 +14,7 @@
|
||||
// Wan Bachtiar <https://github.com/sindbach>
|
||||
// Geraldine Lemeur <https://github.com/geraldinelemeur>
|
||||
// Jimmy Shimizu <https://github.com/jishi>
|
||||
// Dominik Heigl <https://github.com/various89>
|
||||
// Angela-1 <https://github.com/angela-1>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
// TypeScript Version: 2.3
|
||||
@@ -23,7 +24,7 @@
|
||||
/// <reference types="node" />
|
||||
/// <reference types="bson" />
|
||||
|
||||
import { ObjectID } from 'bson';
|
||||
import { ObjectID, Timestamp } from 'bson';
|
||||
import { EventEmitter } from 'events';
|
||||
import { Readable, Writable } from "stream";
|
||||
|
||||
@@ -59,13 +60,136 @@ export class MongoClient extends EventEmitter {
|
||||
logout(options?: { dbName?: string }): Promise<any>;
|
||||
logout(options: { dbName?: string }, callback: MongoCallback<any>): void;
|
||||
/** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#startSession */
|
||||
startSession(options?: any): ClientSession;
|
||||
startSession(options?: SessionOptions): ClientSession;
|
||||
/** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#watch */
|
||||
watch(pipeline?: Object[], options?: ChangeStreamOptions & { startAtClusterTime?: Timestamp, session?: ClientSession }): ChangeStream;
|
||||
/** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#withSession */
|
||||
withSession(operation: (session: ClientSession) => Promise<any>): Promise<void>;
|
||||
/** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#withSession */
|
||||
withSession(options: SessionOptions, operation: (session: ClientSession) => Promise<any>): Promise<void>;
|
||||
}
|
||||
|
||||
declare class ClientSession extends EventEmitter {
|
||||
endSession(callback?: MongoCallback<void>): void;
|
||||
endSession(options: any, callback?: MongoCallback<void>): void;
|
||||
/**
|
||||
* http://mongodb.github.io/node-mongodb-native/3.1/api/ClientSession.html
|
||||
*/
|
||||
export interface ClientSession extends EventEmitter {
|
||||
/** The server id associated with this session */
|
||||
id: any;
|
||||
/**
|
||||
* Aborts the currently active transaction in this session.
|
||||
* @param {MongoCallback<void>} [cb] Optional callback for completion of this operation
|
||||
*/
|
||||
abortTransaction(cb?: MongoCallback<void>): Promise<void>;
|
||||
/**
|
||||
* Advances the operationTime for a ClientSession.
|
||||
* @param {mongodb.Timestamp} operationTime
|
||||
*/
|
||||
advanceOperationTime(operamtionTime: Timestamp): void;
|
||||
/**
|
||||
* Commits the currently active transaction in this session.
|
||||
* @param {MongoCallback<void>} [cb] Optional callback for completion of this operation
|
||||
*/
|
||||
commitTransaction(cb?: MongoCallback<void>): Promise<void>;
|
||||
|
||||
/**
|
||||
* Ends this session on the server
|
||||
* @param {MongoCallback<void>} [cb] Optional callback for completion of this operation
|
||||
*/
|
||||
endSession(cb?: MongoCallback<void>): void;
|
||||
/**
|
||||
* Ends this session on the server
|
||||
* @param {*} [options] Optional settings. Currently reserved for future use
|
||||
* @param {MongoCallback<void>} [cb] Optional callback for completion of this operation
|
||||
*/
|
||||
endSession(options: any, cb?: MongoCallback<void>): void
|
||||
|
||||
/**
|
||||
* Used to determine if this session equals another
|
||||
*
|
||||
* @param {ClientSession} session A class representing a client session on the server
|
||||
* @returns {boolean} if the sessions are equal
|
||||
*/
|
||||
equals(session: ClientSession): boolean;
|
||||
|
||||
/** Increment the transaction number on the internal ServerSession */
|
||||
incrementTransactionNumber(): void;
|
||||
|
||||
/**
|
||||
* @returns {boolean} this session is currently in a transaction or not
|
||||
*/
|
||||
inTransaction(): boolean;
|
||||
|
||||
/**
|
||||
* Starts a new transaction with the given options.
|
||||
* @param {TransactionOptions} options
|
||||
* @memberof ClientSession
|
||||
*/
|
||||
startTransaction(options?: TransactionOptions): void;
|
||||
|
||||
}
|
||||
|
||||
// http://mongodb.github.io/node-mongodb-native/3.1/api/global.html#ReadConcern
|
||||
type ReadConcernLevel = 'local' | 'available' | 'majority' | 'linearizable' | 'snapshot';
|
||||
|
||||
/**
|
||||
* The MongoDB ReadConcern, which allows for control of the consistency and isolation properties
|
||||
* of the data read from replica sets and replica set shards.
|
||||
* http://mongodb.github.io/node-mongodb-native/3.1/api/global.html#ReadConcern
|
||||
*/
|
||||
export interface ReadConcern {
|
||||
level: ReadConcernLevel;
|
||||
}
|
||||
|
||||
/**
|
||||
* A MongoDB WriteConcern, which describes the level of acknowledgement
|
||||
* requested from MongoDB for write operations.
|
||||
* http://mongodb.github.io/node-mongodb-native/3.1/api/global.html#WriteConcern
|
||||
*/
|
||||
interface WriteConcern {
|
||||
/**
|
||||
* requests acknowledgement that the write operation has
|
||||
* propagated to a specified number of mongod hosts
|
||||
* @type {(number | 'majority' | string)} default 1
|
||||
*/
|
||||
w?: number | 'majority' | string;
|
||||
/**
|
||||
* requests acknowledgement from MongoDB that the write operation has
|
||||
* been written to the journal
|
||||
* @type {boolean} default false
|
||||
*/
|
||||
j?: boolean;
|
||||
/**
|
||||
* a time limit, in milliseconds, for the write concern
|
||||
* @type {number}
|
||||
* @memberof WriteConcern
|
||||
*/
|
||||
wtimeout?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Options to pass when creating a Client Session
|
||||
* http://mongodb.github.io/node-mongodb-native/3.1/api/global.html#SessionOptions
|
||||
*/
|
||||
export interface SessionOptions {
|
||||
/**
|
||||
* Whether causal consistency should be enabled on this session
|
||||
* @type {boolean} default true
|
||||
*/
|
||||
causalConsistency?: boolean;
|
||||
/**
|
||||
* The default TransactionOptions to use for transactions started on this session.
|
||||
*/
|
||||
defaultTransactionOptions?: TransactionOptions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configuration options for a transaction.
|
||||
* http://mongodb.github.io/node-mongodb-native/3.1/api/global.html#TransactionOptions
|
||||
*/
|
||||
export interface TransactionOptions {
|
||||
readConcern?: ReadConcern;
|
||||
writeConcern?: WriteConcern;
|
||||
readPreference?: any;
|
||||
}
|
||||
|
||||
export interface MongoClientCommonOption {
|
||||
@@ -191,7 +315,7 @@ export interface DbCreateOptions extends CommonOptions {
|
||||
// ES6 compatible promise constructor
|
||||
promiseLibrary?: Object;
|
||||
/** https://docs.mongodb.com/manual/reference/read-concern/#read-concern */
|
||||
readConcern?: { level?: Object };
|
||||
readConcern?: ReadConcern;
|
||||
// Sets a cap on how many operations the driver will buffer up before giving up on getting a
|
||||
// working connection, default is -1 which is unlimited.
|
||||
bufferMaxEntries?: number;
|
||||
@@ -333,14 +457,7 @@ export class Db extends EventEmitter {
|
||||
stats(options: { scale?: number }, callback: MongoCallback<any>): void;
|
||||
}
|
||||
|
||||
export interface CommonOptions {
|
||||
/** The write concern. */
|
||||
w?: string | number;
|
||||
/** The write concern timeout. */
|
||||
wtimeout?: number;
|
||||
/** Specify a journal write concern. */
|
||||
j?: boolean;
|
||||
/** Session to use for this operation */
|
||||
export interface CommonOptions extends WriteConcern {
|
||||
session?: ClientSession;
|
||||
}
|
||||
|
||||
@@ -400,7 +517,7 @@ export interface DbCollectionOptions extends CommonOptions {
|
||||
readPreference?: ReadPreference | string;
|
||||
serializeFunctions?: boolean;
|
||||
strict?: boolean;
|
||||
readConcern?: { level: Object };
|
||||
readConcern?: ReadConcern;
|
||||
}
|
||||
|
||||
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#createIndex */
|
||||
@@ -490,7 +607,7 @@ export interface Collection<TSchema = Default> {
|
||||
// The current write concern values.
|
||||
writeConcern: any;
|
||||
// The current read concern values.
|
||||
readConcern: any;
|
||||
readConcern: ReadConcern;
|
||||
// Get current index hint for collection.
|
||||
hint: any;
|
||||
/** http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#aggregate */
|
||||
@@ -520,8 +637,8 @@ export interface Collection<TSchema = Default> {
|
||||
createIndex(fieldOrSpec: string | any, options: IndexOptions, callback: MongoCallback<string>): void;
|
||||
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#createIndexes and http://docs.mongodb.org/manual/reference/command/createIndexes/ */
|
||||
createIndexes(indexSpecs: Object[], callback: MongoCallback<any>): void;
|
||||
createIndexes(indexSpecs: Object[], options?: {session?: ClientSession}): Promise<any>;
|
||||
createIndexes(indexSpecs: Object[], options: {session?: ClientSession}, callback: MongoCallback<any>): void;
|
||||
createIndexes(indexSpecs: Object[], options?: { session?: ClientSession }): Promise<any>;
|
||||
createIndexes(indexSpecs: Object[], options: { session?: ClientSession }, callback: MongoCallback<any>): void;
|
||||
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteMany */
|
||||
deleteMany(filter: FilterQuery<TSchema>, callback: MongoCallback<DeleteWriteOpResultObject>): void;
|
||||
deleteMany(filter: FilterQuery<TSchema>, options?: CommonOptions): Promise<DeleteWriteOpResultObject>;
|
||||
@@ -535,17 +652,17 @@ export interface Collection<TSchema = Default> {
|
||||
distinct(key: string, query: Object, options?: { readPreference?: ReadPreference | string, maxTimeMS?: number, session?: ClientSession }): Promise<any>;
|
||||
distinct(key: string, query: Object, options: { readPreference?: ReadPreference | string, maxTimeMS?: number, session?: ClientSession }, callback: MongoCallback<any>): void;
|
||||
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#drop */
|
||||
drop(options?: {session: ClientSession}): Promise<any>;
|
||||
drop(options?: { session: ClientSession }): Promise<any>;
|
||||
drop(callback: MongoCallback<any>): void;
|
||||
drop(options: {session: ClientSession}, callback: MongoCallback<any>): void;
|
||||
drop(options: { session: ClientSession }, callback: MongoCallback<any>): void;
|
||||
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#dropIndex */
|
||||
dropIndex(indexName: string, callback: MongoCallback<any>): void;
|
||||
dropIndex(indexName: string, options?: CommonOptions & { maxTimeMS?: number }): Promise<any>;
|
||||
dropIndex(indexName: string, options: CommonOptions & { maxTimeMS?: number }, callback: MongoCallback<any>): void;
|
||||
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#dropIndexes */
|
||||
dropIndexes(options?: {session?: ClientSession, maxTimeMS?: number}): Promise<any>;
|
||||
dropIndexes(options?: { session?: ClientSession, maxTimeMS?: number }): Promise<any>;
|
||||
dropIndexes(callback?: MongoCallback<any>): void;
|
||||
dropIndexes(options: {session?: ClientSession, maxTimeMS?: number}, callback: MongoCallback<any>): void;
|
||||
dropIndexes(options: { session?: ClientSession, maxTimeMS?: number }, callback: MongoCallback<any>): void;
|
||||
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#estimatedDocumentCount */
|
||||
estimatedDocumentCount(callback: MongoCallback<number>): void;
|
||||
estimatedDocumentCount(query: Object, callback: MongoCallback<number>): void;
|
||||
@@ -584,13 +701,13 @@ export interface Collection<TSchema = Default> {
|
||||
group(keys: Object | Array<any> | Function | Code, condition: Object, initial: Object, reduce: Function | Code, finalize: Function | Code, command: boolean, options?: { readPreference?: ReadPreference | string }): Promise<any>;
|
||||
group(keys: Object | Array<any> | Function | Code, condition: Object, initial: Object, reduce: Function | Code, finalize: Function | Code, command: boolean, options: { readPreference?: ReadPreference | string }, callback: MongoCallback<any>): void;
|
||||
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#indexes */
|
||||
indexes(options?: {session: ClientSession}): Promise<any>;
|
||||
indexes(options?: { session: ClientSession }): Promise<any>;
|
||||
indexes(callback: MongoCallback<any>): void;
|
||||
indexes(options: {session?: ClientSession}, callback: MongoCallback<any>): void;
|
||||
indexes(options: { session?: ClientSession }, callback: MongoCallback<any>): void;
|
||||
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#indexExists */
|
||||
indexExists(indexes: string | string[], callback: MongoCallback<boolean>): void;
|
||||
indexExists(indexes: string | string[], options?: {session: ClientSession}): Promise<boolean>;
|
||||
indexExists(indexes: string | string[], options: {session: ClientSession}, callback: MongoCallback<boolean>): void;
|
||||
indexExists(indexes: string | string[], options?: { session: ClientSession }): Promise<boolean>;
|
||||
indexExists(indexes: string | string[], options: { session: ClientSession }, callback: MongoCallback<boolean>): void;
|
||||
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#indexInformation */
|
||||
indexInformation(callback: MongoCallback<any>): void;
|
||||
indexInformation(options?: { full: boolean, session: ClientSession }): Promise<any>;
|
||||
@@ -615,9 +732,9 @@ export interface Collection<TSchema = Default> {
|
||||
insertOne(docs: Object, options?: CollectionInsertOneOptions): Promise<InsertOneWriteOpResult>;
|
||||
insertOne(docs: Object, options: CollectionInsertOneOptions, callback: MongoCallback<InsertOneWriteOpResult>): void;
|
||||
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#isCapped */
|
||||
isCapped(options?: {session: ClientSession}): Promise<any>;
|
||||
isCapped(options?: { session: ClientSession }): Promise<any>;
|
||||
isCapped(callback: MongoCallback<any>): void;
|
||||
isCapped(options: {session: ClientSession}, callback: MongoCallback<any>): void;
|
||||
isCapped(options: { session: ClientSession }, callback: MongoCallback<any>): void;
|
||||
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#listIndexes */
|
||||
listIndexes(options?: { batchSize?: number, readPreference?: ReadPreference | string, session?: ClientSession }): CommandCursor;
|
||||
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#mapReduce */
|
||||
@@ -625,17 +742,17 @@ export interface Collection<TSchema = Default> {
|
||||
mapReduce(map: Function | string, reduce: Function | string, options?: MapReduceOptions): Promise<any>;
|
||||
mapReduce(map: Function | string, reduce: Function | string, options: MapReduceOptions, callback: MongoCallback<any>): void;
|
||||
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#options */
|
||||
options(options?: {session: ClientSession}): Promise<any>;
|
||||
options(options?: { session: ClientSession }): Promise<any>;
|
||||
options(callback: MongoCallback<any>): void;
|
||||
options(options: {session: ClientSession}, callback: MongoCallback<any>): void;
|
||||
options(options: { session: ClientSession }, callback: MongoCallback<any>): void;
|
||||
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#parallelCollectionScan */
|
||||
parallelCollectionScan(callback: MongoCallback<Cursor<any>[]>): void;
|
||||
parallelCollectionScan(options?: ParallelCollectionScanOptions): Promise<Cursor<any>[]>;
|
||||
parallelCollectionScan(options: ParallelCollectionScanOptions, callback: MongoCallback<Cursor<any>[]>): void;
|
||||
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#reIndex */
|
||||
reIndex(options?: {session: ClientSession}): Promise<any>;
|
||||
reIndex(options?: { session: ClientSession }): Promise<any>;
|
||||
reIndex(callback: MongoCallback<any>): void;
|
||||
reIndex(options: {session: ClientSession}, callback: MongoCallback<any>): void;
|
||||
reIndex(options: { session: ClientSession }, callback: MongoCallback<any>): void;
|
||||
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#remove */
|
||||
/** @deprecated Use use deleteOne, deleteMany or bulkWrite */
|
||||
remove(selector: Object, callback: MongoCallback<WriteOpResult>): void;
|
||||
@@ -678,7 +795,7 @@ export interface Collection<TSchema = Default> {
|
||||
updateOne(filter: FilterQuery<TSchema>, update: Object, options?: ReplaceOneOptions): Promise<UpdateWriteOpResult>;
|
||||
updateOne(filter: FilterQuery<TSchema>, update: Object, options: ReplaceOneOptions, callback: MongoCallback<UpdateWriteOpResult>): void;
|
||||
/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#watch */
|
||||
watch(pipeline?: Object[], options?: ChangeStreamOptions & { session?: ClientSession }): ChangeStream;
|
||||
watch(pipeline?: Object[], options?: ChangeStreamOptions & { startAtClusterTime?: Timestamp, session?: ClientSession }): ChangeStream;
|
||||
}
|
||||
|
||||
export type FilterQuery<T> = {
|
||||
@@ -718,7 +835,7 @@ export type FilterQuery<T> = {
|
||||
$bitsAnySet?: Object;
|
||||
[key: string]: any;
|
||||
};
|
||||
} | { [key:string]: any };
|
||||
} | { [key: string]: any };
|
||||
|
||||
// Documentation: http://docs.mongodb.org/manual/reference/command/collStats/
|
||||
export interface CollStats {
|
||||
@@ -1157,7 +1274,7 @@ export interface FindOneOptions {
|
||||
export interface InsertWriteOpResult {
|
||||
insertedCount: number;
|
||||
ops: Array<any>;
|
||||
insertedIds: {[key: number]: ObjectID};
|
||||
insertedIds: { [key: number]: ObjectID };
|
||||
connection: any;
|
||||
result: { ok: number, n: number }
|
||||
}
|
||||
@@ -1505,11 +1622,18 @@ export class GridFSBucketWriteStream extends Writable {
|
||||
|
||||
/** https://mongodb.github.io/node-mongodb-native/3.1/api/GridFSBucketWriteStream.html */
|
||||
export interface GridFSBucketWriteStreamOptions {
|
||||
/** Custom file id for the GridFS file. */
|
||||
id?: GridFSBucketWriteStreamId,
|
||||
/** The chunk size to use, in bytes */
|
||||
chunkSizeBytes?: number,
|
||||
/** The write concern */
|
||||
w?: number,
|
||||
/** The write concern timeout */
|
||||
wtimeout?: number,
|
||||
/** The journal write concern */
|
||||
j?: number
|
||||
/** Default false; If true, disables adding an md5 field to file data */
|
||||
disableMD5?: boolean
|
||||
}
|
||||
|
||||
/** http://mongodb.github.io/node-mongodb-native/3.1/api/ChangeStream.html */
|
||||
@@ -1565,29 +1689,29 @@ export interface LoggerState {
|
||||
export class Logger {
|
||||
constructor(className: string, options?: LoggerOptions)
|
||||
// Log a message at the debug level
|
||||
debug(message: string, state: LoggerState):void
|
||||
debug(message: string, state: LoggerState): void
|
||||
// Log a message at the warn level
|
||||
warn(message: string, state: LoggerState):void
|
||||
warn(message: string, state: LoggerState): void
|
||||
// Log a message at the info level
|
||||
info(message: string, state: LoggerState):void
|
||||
info(message: string, state: LoggerState): void
|
||||
// Log a message at the error level
|
||||
error(message: string, state: LoggerState):void
|
||||
error(message: string, state: LoggerState): void
|
||||
// Is the logger set at info level
|
||||
isInfo():boolean
|
||||
isInfo(): boolean
|
||||
// Is the logger set at error level
|
||||
isError():boolean
|
||||
isError(): boolean
|
||||
// Is the logger set at error level
|
||||
isWarn():boolean
|
||||
isWarn(): boolean
|
||||
// Is the logger set at debug level
|
||||
isDebug():boolean
|
||||
isDebug(): boolean
|
||||
// Resets the logger to default settings, error and no filtered classes
|
||||
static reset():void
|
||||
static reset(): void
|
||||
// Get the current logger function
|
||||
static currentLogger():log
|
||||
static currentLogger(): log
|
||||
//Set the current logger function
|
||||
static setCurrentLogger(log: log):void
|
||||
static setCurrentLogger(log: log): void
|
||||
// Set what classes to log.
|
||||
static filter(type: string, values: string[]):void
|
||||
static filter(type: string, values: string[]): void
|
||||
// Set the current log level
|
||||
static setLevel(level: string):void
|
||||
static setLevel(level: string): void
|
||||
}
|
||||
|
||||
@@ -175,5 +175,113 @@ let testFunc = async () => {
|
||||
testClient = await mongodb.connect(connectionString);
|
||||
};
|
||||
|
||||
mongodb.connect(connectionString, (err: mongodb.MongoError, client: mongodb.MongoClient) => {});
|
||||
mongodb.connect(connectionString, options, (err: mongodb.MongoError, client: mongodb.MongoClient) => {});
|
||||
mongodb.connect(connectionString, (err: mongodb.MongoError, client: mongodb.MongoClient) => { });
|
||||
mongodb.connect(connectionString, options, (err: mongodb.MongoError, client: mongodb.MongoClient) => { });
|
||||
|
||||
// https://docs.mongodb.com/manual/core/transactions/
|
||||
|
||||
async function commitWithRetry(session: mongodb.ClientSession) {
|
||||
try {
|
||||
await session.commitTransaction();
|
||||
console.log('Transaction committed.');
|
||||
} catch (error) {
|
||||
if (
|
||||
error.errorLabels &&
|
||||
error.errorLabels.indexOf('UnknownTransactionCommitResult') < 0
|
||||
) {
|
||||
console.log('UnknownTransactionCommitResult, retrying commit operation ...');
|
||||
await commitWithRetry(session);
|
||||
} else {
|
||||
console.log('Error during commit ...');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function runTransactionWithRetry(
|
||||
txnFunc: (client: mongodb.MongoClient, session: mongodb.ClientSession) => Promise<void>,
|
||||
client: mongodb.MongoClient,
|
||||
session: mongodb.ClientSession) {
|
||||
try {
|
||||
await txnFunc(client, session);
|
||||
} catch (error) {
|
||||
console.log('Transaction aborted. Caught exception during transaction.');
|
||||
|
||||
// If transient error, retry the whole transaction
|
||||
if (error.errorLabels && error.errorLabels.indexOf('TransientTransactionError') < 0) {
|
||||
console.log('TransientTransactionError, retrying transaction ...');
|
||||
await runTransactionWithRetry(txnFunc, client, session);
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function updateEmployeeInfo(client: mongodb.MongoClient, session: mongodb.ClientSession) {
|
||||
session.startTransaction({
|
||||
readConcern: { level: 'snapshot' },
|
||||
writeConcern: { w: 'majority' }
|
||||
});
|
||||
|
||||
const employeesCollection = client.db('hr').collection('employees');
|
||||
const eventsCollection = client.db('reporting').collection('events');
|
||||
|
||||
await employeesCollection.updateOne(
|
||||
{ employee: 3 },
|
||||
{ $set: { status: 'Inactive' } },
|
||||
{ session }
|
||||
);
|
||||
await eventsCollection.insertOne(
|
||||
{
|
||||
employee: 3,
|
||||
status: { new: 'Inactive', old: 'Active' }
|
||||
},
|
||||
{ session }
|
||||
);
|
||||
|
||||
try {
|
||||
await commitWithRetry(session);
|
||||
} catch (error) {
|
||||
await session.abortTransaction();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function transfer(client: mongodb.MongoClient, from: any, to: any, amount: number) {
|
||||
const db = client.db();
|
||||
const session = client.startSession();
|
||||
session.startTransaction();
|
||||
try {
|
||||
const opts = { session, returnOriginal: false };
|
||||
const A = await db.collection('Account').
|
||||
findOneAndUpdate({ name: from }, { $inc: { balance: -amount } }, opts).
|
||||
then(res => res.value);
|
||||
if (A.balance < 0) {
|
||||
// If A would have negative balance, fail and abort the transaction
|
||||
// `session.abortTransaction()` will undo the above `findOneAndUpdate()`
|
||||
throw new Error('Insufficient funds: ' + (A.balance + amount));
|
||||
}
|
||||
|
||||
const B = await db.collection('Account').
|
||||
findOneAndUpdate({ name: to }, { $inc: { balance: amount } }, opts).
|
||||
then(res => res.value);
|
||||
|
||||
await session.commitTransaction();
|
||||
session.endSession();
|
||||
return { from: A, to: B };
|
||||
} catch (error) {
|
||||
// If an error occurred, abort the whole transaction and
|
||||
// undo any changes that might have happened
|
||||
await session.abortTransaction();
|
||||
session.endSession();
|
||||
throw error; // Rethrow so calling function sees error
|
||||
}
|
||||
}
|
||||
|
||||
mongodb.connect(connectionString).then((client) => {
|
||||
client.startSession();
|
||||
client.withSession(session =>
|
||||
runTransactionWithRetry(updateEmployeeInfo, client, session)
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
Vendored
+64
-44
@@ -1,4 +1,4 @@
|
||||
// Type definitions for Mongoose 5.2.9
|
||||
// Type definitions for Mongoose 5.2.13
|
||||
// Project: http://mongoosejs.com/
|
||||
// Definitions by: horiuchi <https://github.com/horiuchi>
|
||||
// sindrenm <https://github.com/sindrenm>
|
||||
@@ -11,6 +11,7 @@
|
||||
// ondratra <https://github.com/ondratra>
|
||||
// alfirin <https://github.com/alfirin>
|
||||
// Idan Dardikman <https://github.com/idandrd>
|
||||
// Dominik Heigl <https://github.com/various89>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
// TypeScript Version: 2.3
|
||||
|
||||
@@ -62,9 +63,9 @@ declare module "mongoose" {
|
||||
* Some mongoose classes have the same name as the native JS classes
|
||||
* Keep references to native classes using a "Native" prefix
|
||||
*/
|
||||
class NativeBuffer extends global.Buffer {}
|
||||
class NativeDate extends global.Date {}
|
||||
class NativeError extends global.Error {}
|
||||
class NativeBuffer extends global.Buffer { }
|
||||
class NativeDate extends global.Date { }
|
||||
class NativeError extends global.Error { }
|
||||
|
||||
/*
|
||||
* section index.js
|
||||
@@ -72,7 +73,7 @@ declare module "mongoose" {
|
||||
*/
|
||||
export var DocumentProvider: any;
|
||||
// recursive constructor
|
||||
export var Mongoose: new(...args: any[]) => typeof mongoose;
|
||||
export var Mongoose: new (...args: any[]) => typeof mongoose;
|
||||
type Mongoose = typeof mongoose;
|
||||
export var SchemaTypes: typeof Schema.Types;
|
||||
|
||||
@@ -158,6 +159,8 @@ declare module "mongoose" {
|
||||
/** Sets mongoose options */
|
||||
export function set(key: string, value: any): void;
|
||||
|
||||
export function startSession(options?: mongodb.SessionOptions, cb?: (err: any, session: mongodb.ClientSession) => void): Promise<mongodb.ClientSession>;
|
||||
|
||||
class CastError extends Error {
|
||||
/**
|
||||
* The Mongoose CastError constructor
|
||||
@@ -210,16 +213,16 @@ declare module "mongoose" {
|
||||
open(connection_string: string, database?: string, port?: number,
|
||||
options?: ConnectionOpenOptions, callback?: (err: any) => void): any;
|
||||
|
||||
/**
|
||||
* Opens the connection to MongoDB.
|
||||
* @param mongodb://uri or the host to which you are connecting
|
||||
* @param database database name
|
||||
* @param port database port
|
||||
* @param options Mongoose forces the db option forceServerObjectId false and cannot be overridden.
|
||||
* Mongoose defaults the server auto_reconnect options to true which can be overridden.
|
||||
* See the node-mongodb-native driver instance for options that it understands.
|
||||
* Options passed take precedence over options included in connection strings.
|
||||
*/
|
||||
/**
|
||||
* Opens the connection to MongoDB.
|
||||
* @param mongodb://uri or the host to which you are connecting
|
||||
* @param database database name
|
||||
* @param port database port
|
||||
* @param options Mongoose forces the db option forceServerObjectId false and cannot be overridden.
|
||||
* Mongoose defaults the server auto_reconnect options to true which can be overridden.
|
||||
* See the node-mongodb-native driver instance for options that it understands.
|
||||
* Options passed take precedence over options included in connection strings.
|
||||
*/
|
||||
openUri(connection_string: string, database?: string, port?: number,
|
||||
options?: ConnectionOpenOptions, callback?: (err: any) => void): any;
|
||||
|
||||
@@ -346,7 +349,7 @@ declare module "mongoose" {
|
||||
/** Specify a journal write concern (default: false). */
|
||||
journal?: boolean;
|
||||
/** The write concern */
|
||||
w?: number|string;
|
||||
w?: number | string;
|
||||
/** The write concern timeout. */
|
||||
wTimeoutMS?: number;
|
||||
/** The ReadPreference mode as listed here: http://mongodb.github.io/node-mongodb-native/2.1/api/ReadPreference.html */
|
||||
@@ -425,7 +428,9 @@ declare module "mongoose" {
|
||||
|
||||
interface ConnectionOptions extends
|
||||
ConnectionOpenOptions,
|
||||
ConnectionOpenSetOptions {}
|
||||
ConnectionOpenSetOptions { }
|
||||
|
||||
interface ClientSession extends mongodb.ClientSession { }
|
||||
|
||||
/*
|
||||
* section drivers/node-mongodb-native/collection.js
|
||||
@@ -460,6 +465,8 @@ declare module "mongoose" {
|
||||
*/
|
||||
useDb(name: string): Connection;
|
||||
|
||||
startSession(options?: mongodb.SessionOptions, cb?: (err: any, session: mongodb.ClientSession) => void): Promise<mongodb.ClientSession>;
|
||||
|
||||
/** Expose the possible connection states. */
|
||||
static STATES: any;
|
||||
}
|
||||
@@ -870,7 +877,7 @@ declare module "mongoose" {
|
||||
/** defaults to true */
|
||||
validateBeforeSave?: boolean;
|
||||
/** defaults to "__v" */
|
||||
versionKey?: string|boolean;
|
||||
versionKey?: string | boolean;
|
||||
/**
|
||||
* skipVersioning allows excluding paths from
|
||||
* versioning (the internal revision will not be
|
||||
@@ -945,9 +952,9 @@ declare module "mongoose" {
|
||||
* to the front of this SchemaType's validators array using unshift().
|
||||
*/
|
||||
required?: SchemaTypeOpts.RequiredFn<T> |
|
||||
boolean | [boolean, string] |
|
||||
string | [string, string] |
|
||||
any;
|
||||
boolean | [boolean, string] |
|
||||
string | [string, string] |
|
||||
any;
|
||||
|
||||
/**
|
||||
* Sets default select() behavior for this path.
|
||||
@@ -975,11 +982,11 @@ declare module "mongoose" {
|
||||
* and must return Boolean. Returning false means validation failed.
|
||||
*/
|
||||
validate?: RegExp | [RegExp, string] |
|
||||
SchemaTypeOpts.ValidateFn<T> | [SchemaTypeOpts.ValidateFn<T>, string] |
|
||||
SchemaTypeOpts.ValidateOpts | SchemaTypeOpts.AsyncValidateOpts |
|
||||
SchemaTypeOpts.AsyncPromiseValidationFn<T> | SchemaTypeOpts.AsyncPromiseValidationOpts |
|
||||
(SchemaTypeOpts.ValidateOpts | SchemaTypeOpts.AsyncValidateOpts |
|
||||
SchemaTypeOpts.AsyncPromiseValidationFn<T> | SchemaTypeOpts.AsyncPromiseValidationOpts)[];
|
||||
SchemaTypeOpts.ValidateFn<T> | [SchemaTypeOpts.ValidateFn<T>, string] |
|
||||
SchemaTypeOpts.ValidateOpts | SchemaTypeOpts.AsyncValidateOpts |
|
||||
SchemaTypeOpts.AsyncPromiseValidationFn<T> | SchemaTypeOpts.AsyncPromiseValidationOpts |
|
||||
(SchemaTypeOpts.ValidateOpts | SchemaTypeOpts.AsyncValidateOpts |
|
||||
SchemaTypeOpts.AsyncPromiseValidationFn<T> | SchemaTypeOpts.AsyncPromiseValidationOpts)[];
|
||||
|
||||
/** Declares an unique index. */
|
||||
unique?: boolean | any;
|
||||
@@ -1006,16 +1013,16 @@ declare module "mongoose" {
|
||||
* Sets a minimum date validator.
|
||||
*/
|
||||
min?: number | [number, string] |
|
||||
Date | [Date, string] |
|
||||
any;
|
||||
Date | [Date, string] |
|
||||
any;
|
||||
|
||||
/**
|
||||
* Date, Number only - Sets a maximum number validator.
|
||||
* Sets a maximum date validator.
|
||||
*/
|
||||
max?: number | [number, string] |
|
||||
Date | [Date, string] |
|
||||
any;
|
||||
Date | [Date, string] |
|
||||
any;
|
||||
|
||||
/**
|
||||
* Date only - Declares a TTL index (rounded to the nearest second)
|
||||
@@ -1483,9 +1490,9 @@ declare module "mongoose" {
|
||||
|
||||
// var objectId: mongoose.Types.ObjectId should reference mongodb.ObjectID not
|
||||
// the ObjectIdConstructor, so we add the interface below
|
||||
interface ObjectId extends mongodb.ObjectID {}
|
||||
interface ObjectId extends mongodb.ObjectID { }
|
||||
|
||||
class Decimal128 extends mongodb.Decimal128 {}
|
||||
class Decimal128 extends mongodb.Decimal128 { }
|
||||
|
||||
/*
|
||||
* section types/embedded.js
|
||||
@@ -1531,7 +1538,7 @@ declare module "mongoose" {
|
||||
* So we save this type as the second type parameter in DocumentQuery. Since people have
|
||||
* been using Query<T>, we set it as an alias of DocumentQuery.
|
||||
*/
|
||||
class Query<T> extends DocumentQuery<T, any> {}
|
||||
class Query<T> extends DocumentQuery<T, any> { }
|
||||
class DocumentQuery<T, DocType extends Document> extends mquery {
|
||||
/**
|
||||
* Specifies a javascript function or expression to pass to MongoDBs query system.
|
||||
@@ -1922,6 +1929,13 @@ declare module "mongoose" {
|
||||
/** Sets query conditions to the provided JSON object. */
|
||||
setQuery(conditions: any): this;
|
||||
|
||||
/**
|
||||
* Sets the [MongoDB session](https://docs.mongodb.com/manual/reference/server-sessions/)
|
||||
* associated with this query. Sessions are how you mark a query as part of a
|
||||
* [transaction](/docs/transactions.html).
|
||||
*/
|
||||
session(session: mongodb.ClientSession | null): this;
|
||||
|
||||
/**
|
||||
* Specifies a $size query condition.
|
||||
* When called with one argument, the most recent path passed to where() is used.
|
||||
@@ -1972,14 +1986,14 @@ declare module "mongoose" {
|
||||
|
||||
/** Executes this query and returns a promise */
|
||||
then<TRes>(resolve?: (res: T) => void | TRes | PromiseLike<TRes>,
|
||||
reject?: (err: any) => void | TRes | PromiseLike<TRes>): Promise<TRes>;
|
||||
reject?: (err: any) => void | TRes | PromiseLike<TRes>): Promise<TRes>;
|
||||
|
||||
/**
|
||||
* Converts this query to a customized, reusable query
|
||||
* constructor with all arguments and options retained.
|
||||
*/
|
||||
toConstructor<T>(): new(...args: any[]) => Query<T>;
|
||||
toConstructor<T, Doc extends Document>(): new(...args: any[]) => DocumentQuery<T, Doc>;
|
||||
toConstructor<T>(): new (...args: any[]) => Query<T>;
|
||||
toConstructor<T, Doc extends Document>(): new (...args: any[]) => DocumentQuery<T, Doc>;
|
||||
|
||||
/**
|
||||
* Declare and/or execute this query as an update() operation.
|
||||
@@ -2007,7 +2021,7 @@ declare module "mongoose" {
|
||||
// https://github.com/aheckmann/mquery
|
||||
// mquery currently does not have a type definition please
|
||||
// replace it if one is ever created
|
||||
class mquery {}
|
||||
class mquery { }
|
||||
|
||||
interface QueryFindOneAndRemoveOptions {
|
||||
/** if multiple docs are found by the conditions, sets the sort order to choose which doc to update */
|
||||
@@ -2446,6 +2460,7 @@ declare module "mongoose" {
|
||||
*/
|
||||
sample(size: number): this;
|
||||
|
||||
session(session: mongodb.ClientSession | null): this;
|
||||
/**
|
||||
* Appends a new $skip operator to this aggregate pipeline.
|
||||
* @param num number of records to skip before next stage
|
||||
@@ -2462,8 +2477,8 @@ declare module "mongoose" {
|
||||
sort(arg: string | any): this;
|
||||
|
||||
/** Provides promise for aggregate. */
|
||||
then<TRes>(resolve?: (val: T) => void | TRes | PromiseLike<TRes>,
|
||||
reject?: (err: any) => void | TRes | PromiseLike<TRes>): Promise<TRes>;
|
||||
then<TRes>(resolve?: (val: T) => void | TRes | PromiseLike<TRes>,
|
||||
reject?: (err: any) => void | TRes | PromiseLike<TRes>): Promise<TRes>;
|
||||
|
||||
/**
|
||||
* Appends new custom $unwind operator(s) to this aggregate pipeline.
|
||||
@@ -2600,7 +2615,7 @@ declare module "mongoose" {
|
||||
* This function does not trigger any middleware. In particular, it does not trigger aggregate middleware.
|
||||
* @param options See https://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#watch
|
||||
*/
|
||||
watch(options?: mongodb.ChangeStreamOptions & {session?: any}): mongodb.ChangeStream;
|
||||
watch(options?: mongodb.ChangeStreamOptions & { session?: ClientSession }): mongodb.ChangeStream;
|
||||
|
||||
/**
|
||||
* Translate any aliases fields/conditions so the final query or document object is pure
|
||||
@@ -2847,9 +2862,9 @@ declare module "mongoose" {
|
||||
* with a `mongoose` property that contains `validationErrors` if this is an unordered `insertMany`.
|
||||
*/
|
||||
insertMany(docs: any[], callback?: (error: any, docs: T[]) => void): Promise<T[]>;
|
||||
insertMany(docs: any[], options?: { ordered?: boolean, rawResult?: boolean }, callback?: (error: any, docs: T[]) => void): Promise<T[]>;
|
||||
insertMany(docs: any[], options?: { ordered?: boolean, rawResult?: boolean } & ModelOptions, callback?: (error: any, docs: T[]) => void): Promise<T[]>;
|
||||
insertMany(doc: any, callback?: (error: any, doc: T) => void): Promise<T>;
|
||||
insertMany(doc: any, options?: { ordered?: boolean, rawResult?: boolean }, callback?: (error: any, doc: T) => void): Promise<T>;
|
||||
insertMany(doc: any, options?: { ordered?: boolean, rawResult?: boolean } & ModelOptions, callback?: (error: any, doc: T) => void): Promise<T>;
|
||||
|
||||
/**
|
||||
* Performs any async initialization of this model against MongoDB.
|
||||
@@ -2993,7 +3008,12 @@ declare module "mongoose" {
|
||||
schema: Schema;
|
||||
}
|
||||
|
||||
interface ModelFindByIdAndUpdateOptions {
|
||||
/** https://mongoosejs.com/docs/api.html#query_Query-setOptions */
|
||||
interface ModelOptions {
|
||||
session?: ClientSession | null;
|
||||
}
|
||||
|
||||
interface ModelFindByIdAndUpdateOptions extends ModelOptions {
|
||||
/** true to return the modified document rather than the original. defaults to false */
|
||||
new?: boolean;
|
||||
/** creates the object if it doesn't exist. defaults to false. */
|
||||
@@ -3045,7 +3065,7 @@ declare module "mongoose" {
|
||||
populate?: ModelPopulateOptions | ModelPopulateOptions[];
|
||||
}
|
||||
|
||||
interface ModelUpdateOptions {
|
||||
interface ModelUpdateOptions extends ModelOptions {
|
||||
/** safe mode (defaults to value set in schema (true)) */
|
||||
safe?: boolean;
|
||||
/** whether to create the doc if it doesn't match (false) */
|
||||
|
||||
@@ -1900,3 +1900,64 @@ MyModel.createIndexes((err: any): void => {}).then(() => {});
|
||||
mongoose.connection.createCollection('foo').then(() => {});
|
||||
mongoose.connection.createCollection('foo', {wtimeout: 5}).then(() => {});
|
||||
mongoose.connection.createCollection('foo', {wtimeout: 5}, (err: Error, coll): void => {coll.collectionName}).then(() => {});
|
||||
|
||||
const db = mongoose.connection;
|
||||
const User = mongoose.model('User', new mongoose.Schema({ name: String }));
|
||||
|
||||
let session: mongoose.ClientSession;
|
||||
mongoose.connection.createCollection('users').
|
||||
then(() => db.startSession()).
|
||||
then(_session => {
|
||||
session = _session;
|
||||
session.startTransaction();
|
||||
User.findOne({ name: 'foo' }).session(session);
|
||||
session.commitTransaction();
|
||||
return User.create({ name: 'foo' });
|
||||
});
|
||||
|
||||
const Event = db.model('Event', new mongoose.Schema({ createdAt: Date }), 'Event');
|
||||
|
||||
db.createCollection('users').
|
||||
then(() => db.startSession()).
|
||||
then(_session => {
|
||||
session = _session;
|
||||
return User.create({ name: 'foo' });
|
||||
}).
|
||||
then(() => {
|
||||
session.startTransaction();
|
||||
return User.findOne({ name: 'foo' }).session(session).exec();
|
||||
}).
|
||||
then(() => {
|
||||
session.commitTransaction();
|
||||
return User.findOne({ name: 'bar' }).exec();
|
||||
}).
|
||||
catch(() => {
|
||||
session.abortTransaction();
|
||||
});
|
||||
db.createCollection('Event').
|
||||
then(() => db.startSession()).
|
||||
then(_session => {
|
||||
session = _session;
|
||||
session.startTransaction();
|
||||
return Event.insertMany([
|
||||
{ createdAt: new Date('2018-06-01') },
|
||||
{ createdAt: new Date('2018-06-02') },
|
||||
{ createdAt: new Date('2017-06-01') },
|
||||
{ createdAt: new Date('2017-05-31') }
|
||||
], { session: session });
|
||||
}).
|
||||
then(() => Event.aggregate([
|
||||
{
|
||||
$group: {
|
||||
_id: {
|
||||
month: { $month: '$createdAt' },
|
||||
year: { $year: '$createdAt' }
|
||||
},
|
||||
count: { $sum: 1 }
|
||||
}
|
||||
},
|
||||
{ $sort: { count: -1, '_id.year': -1, '_id.month': -1 } }
|
||||
]).session(session).exec()).
|
||||
then((res: any) => {
|
||||
session.commitTransaction();
|
||||
});
|
||||
Vendored
+4
-6
@@ -5,8 +5,6 @@
|
||||
|
||||
/// <reference types="node" />
|
||||
|
||||
import { EventEmitter } from 'events';
|
||||
|
||||
export interface ConnectionOptions {
|
||||
pkg?: string;
|
||||
host?: string;
|
||||
@@ -17,7 +15,7 @@ export interface ConnectionOptions {
|
||||
options?: any;
|
||||
}
|
||||
|
||||
export class Connection extends EventEmitter {
|
||||
export class Connection extends NodeJS.EventEmitter {
|
||||
constructor(options: ConnectionOptions);
|
||||
|
||||
connect(): Promise<void>;
|
||||
@@ -38,7 +36,7 @@ export interface QueueOptions {
|
||||
connection?: ConnectionOptions;
|
||||
}
|
||||
|
||||
export class Queue extends EventEmitter {
|
||||
export class Queue extends NodeJS.EventEmitter {
|
||||
constructor(options: QueueOptions, jobs?: JobsHash);
|
||||
|
||||
connect(): Promise<void>;
|
||||
@@ -60,7 +58,7 @@ export interface WorkerOptions {
|
||||
|
||||
export type WorkerEvent = 'start' | 'end' | 'cleaning_worker' | 'poll' | 'ping' | 'job' | 'reEnqueue' | 'success' | 'failure' | 'error' | 'pause';
|
||||
|
||||
export class Worker extends EventEmitter {
|
||||
export class Worker extends NodeJS.EventEmitter {
|
||||
constructor(options: WorkerOptions, jobs?: JobsHash);
|
||||
|
||||
connect(): Promise<void>;
|
||||
@@ -100,7 +98,7 @@ export interface SchedulerOptions {
|
||||
|
||||
export type SchedulerEvent = 'start' | 'end' | 'poll' | 'master' | 'cleanStuckWorker' | 'error' | 'workingTimestamp' | 'transferredJob';
|
||||
|
||||
export class Scheduler extends EventEmitter {
|
||||
export class Scheduler extends NodeJS.EventEmitter {
|
||||
constructor(options: SchedulerOptions, jobs?: JobsHash);
|
||||
|
||||
connect(): Promise<void>;
|
||||
|
||||
+2
-2
@@ -47,9 +47,9 @@ declare namespace Mail {
|
||||
/** optional content type for the attachment, if not set will be derived from the filename property */
|
||||
contentType?: string;
|
||||
/** optional transfer encoding for the attachment, if not set it will be derived from the contentType property. Example values: quoted-printable, base64. If it is unset then base64 encoding is used for the attachment. If it is set to false then previous default applies (base64 for most, 7bit for text). */
|
||||
contentTransferEncoding?: string;
|
||||
contentTransferEncoding?: '7bit' | 'base64' | 'quoted-printable' | false;
|
||||
/** optional content disposition type for the attachment, defaults to ‘attachment’ */
|
||||
contentDisposition?: string;
|
||||
contentDisposition?: 'attachment' | 'inline';
|
||||
/** is an object of additional headers */
|
||||
headers?: Headers;
|
||||
/** an optional value that overrides entire node content in the mime message. If used then all other options set for this node are ignored. */
|
||||
|
||||
@@ -123,7 +123,7 @@ function message_attachments_test() {
|
||||
attachments: [
|
||||
{ // utf-8 string as an attachment
|
||||
filename: 'text1.txt',
|
||||
content: 'hello world!'
|
||||
content: 'hello world!',
|
||||
},
|
||||
{ // binary buffer as an attachment
|
||||
filename: 'text2.txt',
|
||||
@@ -138,12 +138,15 @@ function message_attachments_test() {
|
||||
},
|
||||
{ // stream as an attachment
|
||||
filename: 'text4.txt',
|
||||
content: fs.createReadStream('file.txt')
|
||||
content: fs.createReadStream('file.txt'),
|
||||
contentTransferEncoding: 'quoted-printable'
|
||||
},
|
||||
{ // define custom content type for the attachment
|
||||
filename: 'text.bin',
|
||||
content: 'hello world!',
|
||||
contentType: 'text/plain'
|
||||
contentType: 'text/plain',
|
||||
contentTransferEncoding: '7bit',
|
||||
contentDisposition: 'attachment'
|
||||
},
|
||||
{ // use URL as an attachment
|
||||
filename: 'license.txt',
|
||||
@@ -152,10 +155,13 @@ function message_attachments_test() {
|
||||
{ // encoded string as an attachment
|
||||
filename: 'text1.txt',
|
||||
content: 'aGVsbG8gd29ybGQh',
|
||||
encoding: 'base64'
|
||||
encoding: 'base64',
|
||||
contentTransferEncoding: 'base64'
|
||||
},
|
||||
{ // data uri as an attachment
|
||||
path: 'data:text/plain;base64,aGVsbG8gd29ybGQ='
|
||||
path: 'data:text/plain;base64,aGVsbG8gd29ybGQ=',
|
||||
contentDisposition: 'inline',
|
||||
contentTransferEncoding: false
|
||||
},
|
||||
{
|
||||
// use pregenerated MIME node
|
||||
|
||||
Vendored
+356
-341
File diff suppressed because it is too large
Load Diff
Vendored
+4
@@ -11,6 +11,10 @@ interface Fns {
|
||||
* * Validates length
|
||||
*/
|
||||
validateCardNumber(cardNumber: string): boolean;
|
||||
/**
|
||||
* Formats a card number
|
||||
*/
|
||||
formatCardNumber(cardNumber: string): string;
|
||||
/**
|
||||
* Validates a card expiry:
|
||||
* * Validates numbers
|
||||
|
||||
Vendored
+3
-3
@@ -346,8 +346,8 @@ declare namespace R {
|
||||
* `chain` maps a function over a list and concatenates the results.
|
||||
* This implementation is compatible with the Fantasy-land Chain spec
|
||||
*/
|
||||
chain<T, U>(fn: (n: T) => U[], list: ReadonlyArray<T>): U[];
|
||||
chain<T, U>(fn: (n: T) => U[]): (list: ReadonlyArray<T>) => U[];
|
||||
chain<T, U>(fn: (n: T) => ReadonlyArray<U>, list: ReadonlyArray<T>): U[];
|
||||
chain<T, U>(fn: (n: T) => ReadonlyArray<U>): (list: ReadonlyArray<T>) => U[];
|
||||
|
||||
/**
|
||||
* Restricts a number to be within a range.
|
||||
@@ -745,7 +745,7 @@ declare namespace R {
|
||||
* Returns a new list by pulling every item out of it (and all its sub-arrays) and putting
|
||||
* them in a new array, depth-first.
|
||||
*/
|
||||
flatten<T>(x: ReadonlyArray<T> | ReadonlyArray<T[]>): T[];
|
||||
flatten<T>(x: ReadonlyArray<T> | ReadonlyArray<T[]> | ReadonlyArray<ReadonlyArray<T>>): T[];
|
||||
|
||||
/**
|
||||
* Returns a new function much like the supplied one, except that the first two arguments'
|
||||
|
||||
+4
-8
@@ -9,11 +9,7 @@ export interface Options {
|
||||
assign: boolean;
|
||||
}
|
||||
|
||||
declare namespace ReactGlobalConfiguration {
|
||||
function set(newConfiguration: any, newOptions?: Options): void;
|
||||
function get(key?: string): any;
|
||||
function get<Value = any>(key: string, fallbackValue: Value): Value;
|
||||
function serialize(): string;
|
||||
}
|
||||
|
||||
export default ReactGlobalConfiguration;
|
||||
export function set(newConfiguration: any, newOptions?: Options): void;
|
||||
export function get(key?: string): any;
|
||||
export function get<Value = any>(key: string, fallbackValue: Value): Value;
|
||||
export function serialize(): string;
|
||||
|
||||
@@ -14,7 +14,8 @@
|
||||
],
|
||||
"types": [],
|
||||
"noEmit": true,
|
||||
"forceConsistentCasingInFileNames": true
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"allowSyntheticDefaultImports": true
|
||||
},
|
||||
"files": [
|
||||
"index.d.ts",
|
||||
|
||||
Vendored
+1
-1
@@ -600,7 +600,7 @@ export interface NavigationEventsProps extends ViewProps {
|
||||
export const NavigationEvents: React.ComponentType<NavigationEventsProps>;
|
||||
|
||||
export interface NavigationScreenProp<S, P = NavigationParams> {
|
||||
state: S;
|
||||
state: S & { params?: P };
|
||||
dispatch: NavigationDispatch;
|
||||
goBack: (routeKey?: string | null) => boolean;
|
||||
dismiss: () => boolean;
|
||||
|
||||
@@ -336,6 +336,24 @@ function renderBasicDrawerNavigator(): JSX.Element {
|
||||
);
|
||||
}
|
||||
|
||||
interface ParamsOnStateProps {
|
||||
navigation: NavigationScreenProp<{}, { foobar: string }>;
|
||||
}
|
||||
|
||||
class ParamsOnState extends React.Component<ParamsOnStateProps> {
|
||||
render() {
|
||||
if (this.props.navigation.state.params) {
|
||||
// $ExpectType string
|
||||
this.props.navigation.state.params.foobar;
|
||||
} else {
|
||||
// $ExpectType undefined
|
||||
this.props.navigation.state.params;
|
||||
}
|
||||
|
||||
return <View />;
|
||||
}
|
||||
}
|
||||
|
||||
interface CustomTransitionerProps {
|
||||
navigation: NavigationScreenProp<any, any>;
|
||||
}
|
||||
|
||||
Vendored
+11
-2
@@ -1,6 +1,7 @@
|
||||
// Type definitions for react-primitives 0.6
|
||||
// Project: https://github.com/lelandrichardson/react-primitives
|
||||
// Definitions by: Ahmed Ghoneim <https://github.com/aghoneim92>
|
||||
// David Pett <https://github.com/davidpett>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
// TypeScript Version: 2.8
|
||||
|
||||
@@ -11,7 +12,7 @@ import {
|
||||
Easing,
|
||||
Image,
|
||||
PixelRatio,
|
||||
Platform,
|
||||
PlatformOSType as RNPlatformOSType,
|
||||
StyleSheet,
|
||||
Text,
|
||||
TouchableOpacityProps,
|
||||
@@ -20,13 +21,21 @@ import {
|
||||
|
||||
export const Touchable: ComponentType<TouchableOpacityProps>;
|
||||
|
||||
// react-primitives also supports react-sketchapp and react-vr as platforms
|
||||
export type PlatformOSType = RNPlatformOSType | 'sketch' | 'vr';
|
||||
export interface PlatformStatic {
|
||||
OS: PlatformOSType;
|
||||
Version: number | string;
|
||||
select<T>(specifics: { [platform in PlatformOSType | 'default']?: T }): T;
|
||||
}
|
||||
export const Platform: PlatformStatic;
|
||||
|
||||
export {
|
||||
Animated,
|
||||
Dimensions,
|
||||
Easing,
|
||||
Image,
|
||||
PixelRatio,
|
||||
Platform,
|
||||
StyleSheet,
|
||||
Text,
|
||||
View
|
||||
|
||||
@@ -49,6 +49,9 @@ export default class Component extends React.Component<{}, State> {
|
||||
duration: 10000,
|
||||
easing: Easing.cubic
|
||||
}).start();
|
||||
if (Platform.OS === 'sketch') {
|
||||
console.log('The Platform is sketch');
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
|
||||
Vendored
-1
@@ -1,7 +1,6 @@
|
||||
// Type definitions for react-redux 6.0.4
|
||||
// Project: https://github.com/reduxjs/react-redux
|
||||
// Definitions by: Qubo <https://github.com/tkqubo>,
|
||||
// Thomas Hasner <https://github.com/thasner>,
|
||||
// Kenzie Togami <https://github.com/kenzierocks>,
|
||||
// Curits Layne <https://github.com/clayne11>
|
||||
// Frank Tan <https://github.com/tansongyang>
|
||||
|
||||
Vendored
+173
@@ -29,6 +29,16 @@ interface TwitchExt {
|
||||
*/
|
||||
actions: TwitchExtActions;
|
||||
|
||||
/**
|
||||
* @see https://dev.twitch.tv/docs/extensions/reference/#twitch-extension-feature-flags
|
||||
*/
|
||||
features: TwitchExtFeatures;
|
||||
|
||||
/**
|
||||
* @see https://dev.twitch.tv/docs/extensions/bits/#javascript-helper
|
||||
*/
|
||||
bits: TwitchExtBits;
|
||||
|
||||
/**
|
||||
* Helper methods for the Twitch Extension rig.
|
||||
* @see https://github.com/twitchdev/developer-rig
|
||||
@@ -160,6 +170,164 @@ interface TwitchExtActions {
|
||||
requestIdShare(): void;
|
||||
}
|
||||
|
||||
interface TwitchExtFeatureFlags {
|
||||
/**
|
||||
* If this flag is true, you can send a chat message to the current channel using Send Extension Chat Message
|
||||
* (subject to the authentication requirements documented for that endpoint).
|
||||
*/
|
||||
isChatEnabled: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* @see TwitchExt.features
|
||||
*/
|
||||
interface TwitchExtFeatures extends TwitchExtFeatureFlags {
|
||||
/**
|
||||
* This function enables you to receive real-time updates to changes of the features object.
|
||||
* If this callback is invoked, you should re-check the Twitch.ext.features object for a change
|
||||
* to any feature flag your extension cares about.
|
||||
*
|
||||
* @param callback The callback is called with an array of feature flags which were updated.
|
||||
*/
|
||||
onChanged(
|
||||
callback: (changed: ReadonlyArray<keyof TwitchExtFeatureFlags>) => void
|
||||
): void;
|
||||
}
|
||||
|
||||
interface TwitchExtBitsProductCost {
|
||||
/**
|
||||
* Number of Bits required for the product.
|
||||
*/
|
||||
amount: string;
|
||||
|
||||
/**
|
||||
* Always the string "bits". Reserved for future use.
|
||||
*/
|
||||
type: "bits";
|
||||
}
|
||||
|
||||
interface TwitchExtBitsProduct {
|
||||
/**
|
||||
* Cost object.
|
||||
*/
|
||||
cost: TwitchExtBitsProductCost;
|
||||
|
||||
/**
|
||||
* Registered display name for the SKU.
|
||||
*/
|
||||
displayName: string;
|
||||
|
||||
/**
|
||||
* This field is returned only for extension versions that are not in the Released state.
|
||||
*/
|
||||
inDevelopment?: boolean;
|
||||
|
||||
/**
|
||||
* Unique ID for the product.
|
||||
*/
|
||||
sku: string;
|
||||
}
|
||||
|
||||
interface TwitchExtBitsTransaction {
|
||||
/**
|
||||
* Display name of the user who executed the Bits in Extensions transaction.
|
||||
*/
|
||||
displayName: string;
|
||||
|
||||
initiator: "CURRENT_USER" | "OTHER";
|
||||
|
||||
/**
|
||||
* Full product object from getProducts call
|
||||
*/
|
||||
product: TwitchExtBitsProduct;
|
||||
|
||||
/**
|
||||
* ID of the transaction.
|
||||
*/
|
||||
transactionID: string;
|
||||
|
||||
/**
|
||||
* JWT containing the following transaction information in the payload.
|
||||
* The JWT is a large, base64-encoded string. It can be verified using your developer secret.
|
||||
*/
|
||||
transactionReceipt: string;
|
||||
|
||||
/**
|
||||
* Twitch ID of the user who executed the transaction.
|
||||
*/
|
||||
userId: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* @see TwitchExt.bits
|
||||
*/
|
||||
interface TwitchExtBits {
|
||||
/**
|
||||
* This function returns a promise which resolves to an array of products available for Bits,
|
||||
* for the extension, if the context supports Bits in Extensions actions. Otherwise, the
|
||||
* promise rejects with an error; this can occur, for instance, if the extension is running in
|
||||
* an older version of the developer rig or the mobile app, which does not support Bits in
|
||||
* Extensions actions.
|
||||
*
|
||||
* @see https://dev.twitch.tv/docs/extensions/bits/#getproducts
|
||||
*/
|
||||
getProducts(): Promise<ReadonlyArray<TwitchExtBitsProduct>>;
|
||||
|
||||
/**
|
||||
* This function takes a callback that is fired whenever a transaction is cancelled.
|
||||
* @param callback The callback that is fired whenever a transaction is cancelled.
|
||||
*
|
||||
* @see https://dev.twitch.tv/docs/extensions/bits/#ontransactioncancelledcallback
|
||||
*/
|
||||
onTransactionCancelled(callback: () => void): void;
|
||||
|
||||
/**
|
||||
* This function registers a callback that is fired whenever a Bits in Extensions transaction
|
||||
* is completed.
|
||||
* @param callback The callback that is fired.
|
||||
*
|
||||
* @see https://dev.twitch.tv/docs/extensions/bits/#ontransactioncompletecallbacktransactionobject
|
||||
*/
|
||||
onTransactionComplete(
|
||||
callback: (transaction: TwitchExtBitsTransaction) => void
|
||||
): void;
|
||||
|
||||
/**
|
||||
* This function sets the state of the extension helper, so it does not call live services for
|
||||
* usage of Bits. Instead, it does a local loopback to the completion handler, after a fixed
|
||||
* delay to simulate user approval and process latency.
|
||||
* @param useLoopback Whether to use local looback.
|
||||
*
|
||||
* @see https://dev.twitch.tv/docs/extensions/bits/#setuseloopbackboolean
|
||||
*/
|
||||
setUseLoopback(useLoopback: boolean): void;
|
||||
|
||||
/**
|
||||
* Call this function when the viewer hovers over a product in your extension UI, to cause the
|
||||
* Twitch UI to display a dialog showing the viewer’s Bits balance.
|
||||
* The dialog displays for 1.5 seconds, unless your extension calls showBitsBalance again, in
|
||||
* which case the 1.5-second timer resets.
|
||||
*
|
||||
* This is a “fire-and-forget” function: the extension developer does not need to tell Twitch
|
||||
* when the viewer stops hovering over the product.
|
||||
*
|
||||
* On mobile, this function is ignored.
|
||||
*
|
||||
* @see https://dev.twitch.tv/docs/extensions/bits/#showbitsbalance
|
||||
*/
|
||||
showBitsBalance(): void;
|
||||
|
||||
/**
|
||||
* This function redeems a product with the specified SKU for the number of Bits specified in
|
||||
* the catalog entry of that product.
|
||||
* @param sku
|
||||
*
|
||||
* @see https://dev.twitch.tv/docs/extensions/bits/#usebitssku
|
||||
* @see https://dev.twitch.tv/docs/extensions/bits/#exchanging-bits-for-a-product
|
||||
*/
|
||||
useBits(sku: string): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* The developer rig object as available under window.Twitch.ext.rig.
|
||||
*
|
||||
@@ -322,6 +490,11 @@ interface TwitchExtClientQueryParams {
|
||||
*/
|
||||
platform: "mobile" | "web";
|
||||
|
||||
/**
|
||||
* Indicates whether the extension is popped out.
|
||||
*/
|
||||
popout: "true" | "false";
|
||||
|
||||
/**
|
||||
* The release state of the extension.
|
||||
*/
|
||||
|
||||
@@ -36,5 +36,55 @@ window.Twitch.ext.actions.minimize();
|
||||
window.Twitch.ext.actions.followChannel("hearthsim");
|
||||
window.Twitch.ext.actions.requestIdShare();
|
||||
|
||||
// Twitch Extension Feature flags
|
||||
window.Twitch.ext.features.onChanged(changed => {
|
||||
if (changed.indexOf("isChatEnabled") !== -1) {
|
||||
if (window.Twitch.ext.features.isChatEnabled) {
|
||||
console.log("Chat is now enabled");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Twitch Extension Bits
|
||||
window.Twitch.ext.bits
|
||||
.getProducts()
|
||||
.then(products => {
|
||||
console.log(`Got ${products.length} products`);
|
||||
for (const product of products) {
|
||||
console.log(
|
||||
`Found product "${product.displayName}" with SKU ${product.sku}`
|
||||
);
|
||||
console.log(
|
||||
`Product costs ${product.cost.amount} ${product.cost.type}`
|
||||
);
|
||||
if (typeof product.inDevelopment !== "undefined") {
|
||||
if (product.inDevelopment) {
|
||||
console.log("Product is in development");
|
||||
} else {
|
||||
console.log("Product is not in development");
|
||||
}
|
||||
} else {
|
||||
console.log("");
|
||||
}
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error(`Got an error: ${error}`);
|
||||
});
|
||||
window.Twitch.ext.bits.onTransactionCancelled(() =>
|
||||
console.log("Transaction cancelled")
|
||||
);
|
||||
window.Twitch.ext.bits.onTransactionComplete(transaction => {
|
||||
console.log(
|
||||
`${transaction.initiator} (${transaction.userId}) bought ${
|
||||
transaction.product.displayName
|
||||
}`
|
||||
);
|
||||
console.log(`Transaction id was ${transaction.transactionID}`);
|
||||
});
|
||||
window.Twitch.ext.bits.setUseLoopback(true);
|
||||
window.Twitch.ext.bits.showBitsBalance();
|
||||
window.Twitch.ext.bits.useBits("MY-PRODUCT");
|
||||
|
||||
// Developer Rig
|
||||
window.Twitch.ext.rig.log("Hello, world!");
|
||||
|
||||
Vendored
+2
-2
@@ -133,8 +133,8 @@ declare var VRDisplay: {
|
||||
};
|
||||
|
||||
interface VRLayer {
|
||||
leftBounds?: number[] | null;
|
||||
rightBounds?: number[] | null;
|
||||
leftBounds?: number[] | Float32Array | null;
|
||||
rightBounds?: number[] | Float32Array | null;
|
||||
source?: HTMLCanvasElement | null;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user