This repository has been archived by the owner on Jan 9, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
Repository.ts
89 lines (73 loc) · 2.03 KB
/
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/* eslint "@typescript-eslint/camelcase": "off" */
import { v4 as uuidv4 } from 'uuid'
import AbstractDBModel from '../../model/AbstractDBModel'
import { Unsorted } from './SortRequest'
function mapDocument(document: any): any {
const { _id, _rev, ...values } = document
return {
id: _id,
rev: _rev,
...values,
}
}
export default class Repository<T extends AbstractDBModel> {
db: PouchDB.Database
constructor(db: PouchDB.Database) {
this.db = db
}
async find(id: string): Promise<T> {
const document = await this.db.get(id)
return mapDocument(document)
}
async findAll(sort = Unsorted): Promise<T[]> {
const selector: any = {
_id: { $gt: null },
}
sort.sorts.forEach((s) => {
selector[s.field] = { $gt: null }
})
const result = await this.db.find({
selector,
sort: sort.sorts.length > 0 ? sort.sorts.map((s) => ({ [s.field]: s.direction })) : undefined,
})
return result.docs.map(mapDocument)
}
async search(criteria: any): Promise<T[]> {
const response = await this.db.find(criteria)
return response.docs.map(mapDocument)
}
async save(entity: T): Promise<T> {
const currentTime = new Date().toISOString()
const { id, rev, ...valuesToSave } = entity
const savedEntity = await this.db.put({
_id: uuidv4(),
...valuesToSave,
createdAt: currentTime,
updatedAt: currentTime,
})
return this.find(savedEntity.id)
}
async saveOrUpdate(entity: T): Promise<T> {
if (!entity.id) {
return this.save(entity)
}
const { id, rev, ...dataToSave } = entity
try {
await this.find(entity.id)
const entityToUpdate = {
_id: id,
_rev: rev,
...dataToSave,
updatedAt: new Date().toISOString(),
}
await this.db.put(entityToUpdate)
return this.find(entity.id)
} catch (error) {
return this.save(entity)
}
}
async delete(entity: T): Promise<T> {
const e = entity as any
return mapDocument(this.db.remove(e.id, e.rev))
}
}