refactor(base-model): remove unused instance methods save/delete/refresh and instance fields
This commit is contained in:
1 parent
991173aa05
commit
3693d0c0a5
1 file changed
-37
@@ -11,10 +11,6 @@ import { getMongoDb } from '#providers/mongodb_provider'
|
||||
export abstract class BaseModel {
|
||||
static collectionName: string
|
||||
|
||||
_id?: ObjectId
|
||||
createdAt?: Date
|
||||
updatedAt?: Date
|
||||
|
||||
static getDb(): Db {
|
||||
return getMongoDb()
|
||||
}
|
||||
@@ -110,37 +106,4 @@ export abstract class BaseModel {
|
||||
return collection
|
||||
}
|
||||
|
||||
async save(): Promise<void> {
|
||||
const constructor = this.constructor as typeof BaseModel
|
||||
const collection = constructor.getDb().collection(constructor.collectionName)
|
||||
this.updatedAt = new Date()
|
||||
if (!this.createdAt) {
|
||||
this.createdAt = new Date()
|
||||
}
|
||||
const { _id, ...data } = this as any
|
||||
if (_id) {
|
||||
await collection.updateOne({ _id }, { $set: data })
|
||||
} else {
|
||||
const result = await collection.insertOne(data)
|
||||
this._id = result.insertedId
|
||||
}
|
||||
}
|
||||
|
||||
async delete(): Promise<boolean> {
|
||||
const constructor = this.constructor as typeof BaseModel
|
||||
const collection = constructor.getDb().collection(constructor.collectionName)
|
||||
if (!this._id) return false
|
||||
const result = await collection.deleteOne({ _id: this._id })
|
||||
return result.deletedCount === 1
|
||||
}
|
||||
|
||||
async refresh(): Promise<void> {
|
||||
const constructor = this.constructor as typeof BaseModel
|
||||
const collection = constructor.getDb().collection(constructor.collectionName)
|
||||
if (!this._id) return
|
||||
const doc = await collection.findOne({ _id: this._id })
|
||||
if (doc) {
|
||||
Object.assign(this, doc)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user