-
Notifications
You must be signed in to change notification settings - Fork 8
/
Feed.ts
95 lines (81 loc) · 2.49 KB
/
Feed.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
90
91
92
93
94
95
import {
FeedDbObjectNormalized,
FeedDbObject,
Collection,
Db,
ObjectId,
FeedInfo
} from '../types'
import { containFalsyValues } from './containFalsyValues'
export class FeedRepository {
collection: Collection<FeedDbObject>
// list of addresses to include in the search queries using address as an id for each data feed
dataFeedsAddresses: Array<string>
constructor (db: Db, dataFeeds: Array<FeedInfo>) {
this.collection = db.collection('feed')
this.dataFeedsAddresses = dataFeeds.map(dataFeed => dataFeed.address)
}
async getAll (): Promise<Array<FeedDbObjectNormalized>> {
return (
await this.collection
.find({ address: { $in: this.dataFeedsAddresses } })
.toArray()
).map(this.normalizeId)
}
async insert (
feed: Omit<FeedDbObject, '_id'>
): Promise<FeedDbObjectNormalized | null> {
if (this.isValidFeed(feed)) {
const response = await this.collection.insertOne(feed)
return this.normalizeId(response.ops[0])
} else {
console.error('Error inserting feed: Validation Error', feed)
return null
}
}
async addResultRequest (
feedId: ObjectId,
resultRequestId: ObjectId
): Promise<FeedDbObjectNormalized> {
const response = await this.collection.findOneAndUpdate(
{ _id: feedId },
{ $push: { requests: resultRequestId } },
{ returnDocument: 'after' }
)
return this.normalizeId(response.value)
}
async get (id: string): Promise<FeedDbObjectNormalized> {
return this.normalizeId(
await this.collection.findOne({ _id: new ObjectId(id) })
)
}
async getFeeds (
page: number,
size: number
): Promise<Array<FeedDbObjectNormalized>> {
return (
await this.collection
.find({ address: { $in: this.dataFeedsAddresses } })
.skip(size * (page - 1))
.limit(size)
.toArray()
).map(this.normalizeId)
}
async getByAddress (address: string): Promise<FeedDbObjectNormalized> {
return this.normalizeId(await this.collection.findOne({ address }))
}
public getTotalCount (): Promise<number> {
return this.collection.count()
}
private normalizeId (feed: FeedDbObject): FeedDbObjectNormalized | null {
if (feed && feed._id) {
return { ...feed, id: feed._id.toString() }
} else {
// this code should be unreachable: value from db always contains _id
return null
}
}
private isValidFeed (feed: Omit<FeedDbObject, '_id'>): boolean {
return !containFalsyValues(feed)
}
}