Skip to content

Instantly share code, notes, and snippets.

@martialanouman
Created March 14, 2022 18:55
Show Gist options
  • Save martialanouman/155c00e43ea62e858a80a91af0eccc65 to your computer and use it in GitHub Desktop.
Save martialanouman/155c00e43ea62e858a80a91af0eccc65 to your computer and use it in GitHub Desktop.
Base TypeOrm repository mock
class MockUserRepo<T extends { id: number; [key: string]: any }> {
private db: T[] = []
async create(data: Partial<T>) {
return { ...data, id: this.db.length + 1 } as T
}
async save(entity: T) {
this.db = [...this.db, entity]
return Promise.resolve(entity)
}
async findOne(criteria: Partial<T>) {
return this.db.find((user) =>
Object.keys(criteria).every((key) => user[key] === criteria[key])
)
}
async update(id: number, data: Partial<CreateUserDto>) {
const user = this.db.find((user) => user.id === id)
const updatedUser = { ...user, ...data } as T
this.db = this.db.map((user) => (user.id === id ? updatedUser : user))
}
async delete(id: number) {
this.db = this.db.filter((user) => user.id !== id)
}
clear() {
this.db = []
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment