Last active
December 14, 2020 03:50
-
-
Save eduardopc/9303f706e00344bd20ebb9f64909c23e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { DocumentType, ReturnModelType } from "@typegoose/typegoose"; | |
import { DocumentQuery, CreateQuery, Types } from 'mongoose'; | |
import { AnyParamConstructor } from '@typegoose/typegoose/lib/types'; | |
type QueryList<T> = DocumentQuery< | |
Array<DocumentType<T>>, | |
DocumentType<T> | |
>; | |
type QueryItem<T> = DocumentQuery< | |
DocumentType<T>, | |
DocumentType<T> | |
>; | |
export class BaseService<T> { | |
protected model: ReturnModelType<AnyParamConstructor<T>>; | |
protected toObjectId(id: string): Types.ObjectId { | |
try { | |
return Types.ObjectId(id); | |
} catch (err) { | |
console.log(err); | |
} | |
} | |
async find(filter = {}): Promise<QueryList<T>> { | |
return this.model.find(filter); | |
} | |
async findOneById(filter = {}): Promise<QueryItem<T>> { | |
return this.model.findOne(filter); | |
} | |
async create(item: CreateQuery<T>): Promise<DocumentType<T>> { | |
return this.model.create(item); | |
} | |
async removeById(id: string): Promise<QueryItem<T>> { | |
return this.model.findByIdAndDelete(this.toObjectId(id)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment