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
82 lines (68 loc) · 1.79 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
/* eslint "@typescript-eslint/camelcase": "off" */
import { getTime } from 'date-fns'
import { v4 as uuidv4 } from 'uuid'
import AbstractDBModel from '../../model/AbstractDBModel'
function mapRow(row: any): any {
const { value, doc } = row
const { id, _rev, _id, rev, ...restOfDoc } = doc
return {
id: _id,
rev: value.rev,
...restOfDoc,
}
}
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 search(criteria: any): Promise<T[]> {
const response = await this.db.find(criteria)
return response.docs.map(mapDocument)
}
async findAll(): Promise<T[]> {
const allDocs = await this.db.allDocs({
include_docs: true,
})
return allDocs.rows.map(mapRow)
}
async save(entity: T): Promise<T> {
const { id, rev, ...valuesToSave } = entity
const savedEntity = await this.db.put({ _id: uuidv4(), ...valuesToSave })
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,
}
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))
}
}