Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

enhancement(connection&base): add support for continueOnError #11266

Merged
merged 14 commits into from
Feb 1, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 16 additions & 4 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,8 @@ declare module 'mongoose' {
* the model's schema except the `_id` index, and build any indexes that
* are in your schema but not in MongoDB.
*/
export function syncIndexes(options?: Record<string, unknown>): Promise<Array<string>>;
export function syncIndexes(options: Record<string, unknown> | null, callback: Callback<Array<string>>): void;
export function syncIndexes(options?: SyncIndexesOptions): Promise<ConnectionSyncIndexesResult>;
export function syncIndexes(options: SyncIndexesOptions | null, callback: Callback<ConnectionSyncIndexesResult>): void;

/* Tells `sanitizeFilter()` to skip the given object when filtering out potential query selector injection attacks.
* Use this method when you have a known query selector that you want to use. */
Expand Down Expand Up @@ -165,6 +165,7 @@ declare module 'mongoose' {
export const version: string;

export type CastError = Error.CastError;
export type SyncIndexesError = Error.SyncIndexesError;

type Mongoose = typeof mongoose;

Expand Down Expand Up @@ -442,8 +443,8 @@ declare module 'mongoose' {
* the model's schema except the `_id` index, and build any indexes that
* are in your schema but not in MongoDB.
*/
syncIndexes(options?: Record<string, unknown>): Promise<Array<string>>;
syncIndexes(options: Record<string, unknown> | null, callback: Callback<Array<string>>): void;
syncIndexes(options?: SyncIndexesOptions): Promise<ConnectionSyncIndexesResult>;
syncIndexes(options: SyncIndexesOptions | null, callback: Callback<ConnectionSyncIndexesResult>): void;

/**
* _Requires MongoDB >= 3.6.0._ Executes the wrapped async function
Expand Down Expand Up @@ -3303,6 +3304,11 @@ declare module 'mongoose' {
type?: string): this;
}

export interface SyncIndexesOptions extends mongodb.CreateIndexesOptions {
continueOnError?: boolean
}
export type ConnectionSyncIndexesResult = Record<string, OneCollectionSyncIndexesResult>;
type OneCollectionSyncIndexesResult = Array<string> & mongodb.MongoServerError;
type Callback<T = any> = (error: CallbackError, result: T) => void;

type CallbackWithoutResult = (error: CallbackError) => void;
Expand Down Expand Up @@ -3333,6 +3339,12 @@ declare module 'mongoose' {

constructor(type: string, value: any, path: string, reason?: NativeError, schemaType?: SchemaType);
}
export class SyncIndexesError extends Error {
name: 'SyncIndexesError';
errors?: Record<string, mongodb.MongoServerError>;

constructor(type: string, value: any, path: string, reason?: NativeError, schemaType?: SchemaType);
}

export class DisconnectedError extends Error {
name: 'DisconnectedError';
Expand Down
36 changes: 33 additions & 3 deletions lib/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const Schema = require('./schema');
const Collection = require('./driver').get().Collection;
const STATES = require('./connectionstate');
const MongooseError = require('./error/index');
const SyncIndexesError = require('./error/syncIndexes');
const PromiseProvider = require('./promise_provider');
const ServerSelectionError = require('./error/serverSelection');
const applyPlugins = require('./helpers/schema/applyPlugins');
Expand Down Expand Up @@ -1380,11 +1381,40 @@ Connection.prototype.setClient = function setClient(client) {
return this;
};

Connection.prototype.syncIndexes = async function syncIndexes() {
/**
*
* Syncs all the indexes for the models registered with this connection.
*
* @param {Object} options
* @param {Boolean} options.continueOnError `false` by default. If set to `true`, mongoose will not throw an error if one model syncing failed, and will return an object where the keys are the names of the models, and the values are the results/errors for each model.
* @returns
*/
Connection.prototype.syncIndexes = async function syncIndexes(options = {}) {
const result = {};
for (const model in this.models) {
result[model] = await this.model(model).syncIndexes();
const errorsMap = { };

const { continueOnError } = options;
delete options.continueOnError;

for (const model of Object.values(this.models)) {
try {
result[model.modelName] = await model.syncIndexes(options);
} catch (err) {
if (!continueOnError) {
errorsMap[model.modelName] = err;
break;
} else {
result[model.modelName] = err;
AbdelrahmanHafez marked this conversation as resolved.
Show resolved Hide resolved
}
}
}

if (!continueOnError && Object.keys(errorsMap).length) {
const message = Object.entries(errorsMap).map(([modelName, err]) => `${modelName}: ${err.message}`).join(', ');
const syncIndexesError = new SyncIndexesError(message, errorsMap);
throw syncIndexesError;
}

return result;
};

Expand Down
30 changes: 30 additions & 0 deletions lib/error/syncIndexes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
'use strict';

/*!
* Module dependencies.
*/

const MongooseError = require('./mongooseError');

/**
* SyncIndexes Error constructor.
*
* @param {String} message
* @param {String} errorsMap
* @inherits MongooseError
* @api private
*/

class SyncIndexesError extends MongooseError {
constructor(message, errorsMap) {
super(message);
this.errors = errorsMap;
}
}

Object.defineProperty(SyncIndexesError.prototype, 'name', {
value: 'SyncIndexesError'
});


module.exports = SyncIndexesError;
12 changes: 10 additions & 2 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -993,9 +993,17 @@ Mongoose.prototype.isValidObjectId = function(v) {
return false;
};

Mongoose.prototype.syncIndexes = function() {
/**
*
* Syncs all the indexes for the models registered with this connection.
*
* @param {Object} options
* @param {Boolean} options.continueOnError `false` by default. If set to `true`, mongoose will not throw an error if one model syncing failed, and will return an object where the keys are the names of the models, and the values are the results/errors for each model.
* @returns
*/
Mongoose.prototype.syncIndexes = function(options) {
const _mongoose = this instanceof Mongoose ? this : mongoose;
return _mongoose.connection.syncIndexes();
return _mongoose.connection.syncIndexes(options);
};

/**
Expand Down
Loading