From d92a58b2ad91faab199c4cc0b3ced3ab88240461 Mon Sep 17 00:00:00 2001 From: Arash Sheyda Date: Sun, 9 Jul 2023 13:25:38 +0300 Subject: [PATCH] feat: mongoose schema hooks --- playground/server/models/user.schema.ts | 14 ++++++++++++-- src/runtime/server/services/mongoose.ts | 21 +++++++++++++++++---- tsconfig.json | 2 +- 3 files changed, 30 insertions(+), 7 deletions(-) diff --git a/playground/server/models/user.schema.ts b/playground/server/models/user.schema.ts index 6144700..3048225 100644 --- a/playground/server/models/user.schema.ts +++ b/playground/server/models/user.schema.ts @@ -7,10 +7,20 @@ export const UserSchema = defineMongooseModel({ type: 'string', required: true, }, - slug: { + email: { + type: 'string', + required: true, + unique: false, + }, + password: { type: 'string', required: true, - unique: true, }, }, + hooks(schema) { + schema.pre('save', function (this, next) { + this.password = `hash.${this.password}.${Math.random()}` + next() + }) + }, }) diff --git a/src/runtime/server/services/mongoose.ts b/src/runtime/server/services/mongoose.ts index 2381403..2f4239a 100644 --- a/src/runtime/server/services/mongoose.ts +++ b/src/runtime/server/services/mongoose.ts @@ -18,7 +18,17 @@ export async function defineMongooseConnection({ uri, options }: { uri?: string; } } -export function defineMongooseModel(nameOrOptions: string | { name: string; schema: SchemaDefinition; options?: SchemaOptions }, schema?: SchemaDefinition, options?: SchemaOptions): Model { +export function defineMongooseModel( + nameOrOptions: string | { + name: string + schema: SchemaDefinition + options?: SchemaOptions + hooks?: (schema: mongoose.Schema) => void + }, + schema?: SchemaDefinition, + options?: SchemaOptions, + hooks?: (schema: mongoose.Schema) => void, +): Model { let name: string if (typeof nameOrOptions === 'string') { name = nameOrOptions @@ -27,10 +37,13 @@ export function defineMongooseModel(nameOrOptions: string | { name: string; s name = nameOrOptions.name schema = nameOrOptions.schema options = nameOrOptions.options + hooks = nameOrOptions.hooks } - const newSchema = new mongoose.Schema({ - ...schema, - }, { ...options }) + const newSchema = new mongoose.Schema(schema, options as any) + + if (hooks) + hooks(newSchema) + return mongoose.model(name, newSchema) } diff --git a/tsconfig.json b/tsconfig.json index dbe438d..9dd826f 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,3 +1,3 @@ { - "extends": "./client/.nuxt/tsconfig.json" + "extends": "./playground/.nuxt/tsconfig.json" }