Skip to content

Commit

Permalink
feat: add discriminator helper (#47)
Browse files Browse the repository at this point in the history
* add discriminator.ts helper

Allow extension and inheritance of base models with discriminator models.

* Update index.ts

* fix typo in index.ts
  • Loading branch information
jbool24 committed Apr 24, 2024
1 parent 3ef0d69 commit 6b4d1ed
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
33 changes: 33 additions & 0 deletions src/runtime/server/services/discriminator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import type { Model, SchemaDefinition, SchemaOptions } from 'mongoose'
import mongoose from 'mongoose'

export function defineMongooseDiscriminatorModel<T>(
nameOrOptions: string | {
name: string;
baseModel: Model<T>;
schema: SchemaDefinition<T>;
options?: SchemaOptions;
hooks?: (schema: mongoose.Schema<T>) => void;
},
baseModel?: Model<T>,
schema?: SchemaDefinition<T>,
options?: SchemaOptions,
hooks?: (schema: mongoose.Schema<T>) => void,
): Model<T> {
let name: string
if (typeof nameOrOptions === 'string') { name = nameOrOptions }
else {
name = nameOrOptions.name
baseModel = nameOrOptions.baseModel
schema = nameOrOptions.schema
options = nameOrOptions.options
hooks = nameOrOptions.hooks
}

const newSchema = new mongoose.Schema<T>(schema, options as any)

if (hooks)
hooks(newSchema)

return baseModel!.discriminator<T>(name, newSchema)
}
1 change: 1 addition & 0 deletions src/runtime/server/services/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export { defineMongooseConnection } from './connection'
export { defineMongooseModel } from './model'
export { defineMongooseDiscriminatorModel } from './discriminator'

0 comments on commit 6b4d1ed

Please sign in to comment.