-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbook.repository.ts
72 lines (68 loc) · 2.14 KB
/
book.repository.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import { Injectable } from '@nestjs/common';
import { InjectConnection } from '@nestjs/mongoose';
import { ClientSession, Connection } from 'mongoose';
import {
DeleteAllOptions,
DeleteByIdOptions,
IllegalArgumentException,
MongooseTransactionalRepository,
TransactionalRepository,
runInTransaction,
} from 'monguito';
import { AuditOptions } from '../../../dist/util/operation-options';
import { AudioBook, Book, PaperBook } from './book';
import { AudioBookSchema, BookSchema, PaperBookSchema } from './book.schemas';
type SoftDeleteAllOptions = DeleteAllOptions<Book> & AuditOptions;
type SoftDeleteByIdOptions = DeleteByIdOptions & AuditOptions;
@Injectable()
export class MongooseBookRepository
extends MongooseTransactionalRepository<Book>
implements TransactionalRepository<Book>
{
constructor(@InjectConnection() connection: Connection) {
super(
{
type: Book,
schema: BookSchema,
subtypes: [
{ type: PaperBook, schema: PaperBookSchema },
{ type: AudioBook, schema: AudioBookSchema },
],
},
connection,
);
}
async deleteById(
id: string,
options?: SoftDeleteByIdOptions,
): Promise<boolean> {
if (!id) throw new IllegalArgumentException('The given ID must be valid');
return this.entityModel
.findByIdAndUpdate(id, { isDeleted: true }, { new: true })
.session(options?.session)
.exec()
.then((book) => !!book);
}
async deleteAll(options?: SoftDeleteAllOptions): Promise<number> {
if (options?.filters === null) {
throw new IllegalArgumentException(
'The given search criteria (filters) cannot be null',
);
}
return await runInTransaction(
async (session: ClientSession) => {
const books = await this.findAll({
filters: options?.filters,
session,
});
const booksToDelete = books.map((book) => {
book.isDeleted = true;
return book;
});
const deletedBooks = await this.saveAll(booksToDelete, { session });
return deletedBooks.length;
},
{ ...options, connection: this.connection },
);
}
}