From 7ebd6d4b24ea14918b3382248368c6ea8d9bed68 Mon Sep 17 00:00:00 2001 From: uzlopak Date: Sun, 6 Mar 2022 01:04:00 +0100 Subject: [PATCH] export PreMiddlewareFunction, PreSaveMiddlewareFunction, PostMiddlewareFunction, ErrorHandlingMiddlewareFunction --- test/types/middleware.test.ts | 11 ++++++++++- types/index.d.ts | 9 +++++---- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/test/types/middleware.test.ts b/test/types/middleware.test.ts index 33d013943fe..a5903e1c77b 100644 --- a/test/types/middleware.test.ts +++ b/test/types/middleware.test.ts @@ -1,10 +1,19 @@ -import { Schema, model, Model, Document, SaveOptions, Query, Aggregate, HydratedDocument } from 'mongoose'; +import { Schema, model, Model, Document, SaveOptions, Query, Aggregate, HydratedDocument, PreSaveMiddlewareFunction } from 'mongoose'; import { expectError, expectType } from 'tsd'; interface ITest extends Document { name?: string; } +const preMiddlewareFn: PreSaveMiddlewareFunction = function(next, opts) { + this.$markValid('name'); + if (opts.session) { + next(); + } else { + next(new Error('Operation must be in Session.')); + } +}; + const schema: Schema = new Schema({ name: { type: 'String' } }); schema.pre>('find', async function() { diff --git a/types/index.d.ts b/types/index.d.ts index 8ed68eaf039..15ee7cc1ab1 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -1092,10 +1092,10 @@ declare module 'mongoose' { type IndexDirection = 1 | -1 | '2d' | '2dsphere' | 'geoHaystack' | 'hashed' | 'text'; type IndexDefinition = Record; - type PreMiddlewareFunction = (this: T, next: (err?: CallbackError) => void) => void | Promise; - type PreSaveMiddlewareFunction = (this: T, next: (err?: CallbackError) => void, opts: SaveOptions) => void | Promise; - type PostMiddlewareFunction = (this: ThisType, res: ResType, next: (err?: CallbackError) => void) => void | Promise; - type ErrorHandlingMiddlewareFunction = (this: ThisType, err: NativeError, res: ResType, next: (err?: CallbackError) => void) => void; + export type PreMiddlewareFunction = (this: ThisType, next: CallbackWithoutResultAndOptionalError) => void | Promise; + export type PreSaveMiddlewareFunction = (this: ThisType, next: CallbackWithoutResultAndOptionalError, opts: SaveOptions) => void | Promise; + export type PostMiddlewareFunction = (this: ThisType, res: ResType, next: CallbackWithoutResultAndOptionalError) => void | Promise; + export type ErrorHandlingMiddlewareFunction = (this: ThisType, err: NativeError, res: ResType, next: CallbackWithoutResultAndOptionalError) => void; class Schema, TInstanceMethods = any, TQueryHelpers = any> extends events.EventEmitter { /** @@ -2942,6 +2942,7 @@ declare module 'mongoose' { type Callback = (error: CallbackError, result: T) => void; type CallbackWithoutResult = (error: CallbackError) => void; + type CallbackWithoutResultAndOptionalError = (error?: CallbackError) => void; /* for ts-mongoose */ class mquery {}