-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathassets.ts
79 lines (62 loc) · 2.05 KB
/
assets.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
import { IDatabase } from "pg-promise";
import squel from "squel";
import { Asset } from "stellar-sdk";
import { PagingParams } from "../datasource/horizon/base";
import { BalanceFactory } from "../model/factories";
import { parseCursorPagination, properlyOrdered, SortOrder } from "../util/paging";
export default class AssetsRepo {
private db: IDatabase<any>;
constructor(db: any) {
this.db = db;
}
public async findAll(code?: string, issuer?: string, limit?: number, offset?: number) {
const queryBuilder = squel
.select()
.field("assetcode")
.field("issuer")
.from("trustlines")
.group("assetcode")
.group("issuer")
.order("assetcode");
if (code) {
queryBuilder.having("assetcode = ?", code);
}
if (issuer) {
queryBuilder.having("issuer = ?", issuer);
}
if (limit) {
queryBuilder.limit(limit);
}
if (offset) {
queryBuilder.offset(offset);
}
const res = await this.db.manyOrNone(queryBuilder.toString());
return res.map(a => new Asset(a.assetcode, a.issuer));
}
public async findHolders(asset: Asset, paging: PagingParams) {
const queryBuilder = squel
.select()
.from("trustlines")
.where("assetcode = ?", asset.getCode())
.where("issuer = ?", asset.getIssuer());
const { limit, cursor, order } = parseCursorPagination(paging);
queryBuilder.limit(limit);
// Order of these stetements is important,
// we must order by balance first to support cursor pagination
queryBuilder.order("balance", order === SortOrder.ASC);
queryBuilder.order("accountid");
if (cursor) {
const [, , balance] = Buffer.from(cursor, "base64")
.toString()
.split("_");
if (paging.after) {
queryBuilder.where("balance < ?", balance);
} else {
queryBuilder.where("balance > ?", balance);
}
}
const res = await this.db.manyOrNone(queryBuilder.toString());
const balances = res.map(r => BalanceFactory.fromDb(r));
return properlyOrdered(balances, paging);
}
}