Skip to content

Commit 4053598

Browse files
committed
Added batch start
1 parent 4a5837b commit 4053598

File tree

1 file changed

+110
-0
lines changed

1 file changed

+110
-0
lines changed

src/batch.ts

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
import { HttpMethod } from "./drivers/default/enums/httpMethod";
2+
import { Model } from "./model";
3+
import { Orion } from "./orion";
4+
5+
export class Batch
6+
{
7+
private static $httpClient() {
8+
const httpClient = Orion.makeHttpClient(Orion.getBaseUrl());
9+
10+
return httpClient;
11+
}
12+
13+
public static async store<M extends Model>(items: M[])
14+
{
15+
if (!items.length)
16+
return;
17+
18+
const client = this.$httpClient();
19+
const url = items[0].$resource();
20+
21+
const data = {
22+
resources: items.map(x => x.$attributes)
23+
};
24+
25+
return client.request(
26+
`${url}/batch`,
27+
HttpMethod.POST,
28+
null,
29+
data
30+
)
31+
}
32+
33+
public static async update<M extends Model>(items: M[])
34+
{
35+
if (!items.length)
36+
return;
37+
38+
const client = this.$httpClient();
39+
const url = items[0].$resource();
40+
41+
const data = {
42+
resources: {}
43+
};
44+
items.forEach((v, i) => data.resources[v.$getKey()] = v.$attributes);
45+
46+
return client.request(
47+
`${url}/batch`,
48+
HttpMethod.PATCH,
49+
null,
50+
data
51+
)
52+
}
53+
54+
public static async delete<M extends Model>(items: number[] | M[], baseUrl?: string)
55+
{
56+
const {ids, url} = this.getBatchIds(items);
57+
const data = {
58+
resources: ids
59+
};
60+
const finalUrl = url || baseUrl;
61+
const client = this.$httpClient();
62+
63+
64+
if (!finalUrl)
65+
throw "BuilderError: url not found"
66+
return client.request(
67+
`${finalUrl}/batch`,
68+
HttpMethod.DELETE,
69+
data
70+
)
71+
}
72+
73+
74+
public static async restore<M extends Model>(items: number[] | M[], baseUrl?: string)
75+
{
76+
const {ids, url} = this.getBatchIds(items);
77+
const data = {
78+
resources: ids
79+
};
80+
const finalUrl = url || baseUrl;
81+
const client = this.$httpClient();
82+
83+
84+
if (!finalUrl)
85+
throw "BuilderError: url not found"
86+
return client.request(
87+
`${finalUrl}/batch/restore`,
88+
HttpMethod.POST,
89+
data
90+
)
91+
}
92+
93+
private static getBatchIds<M extends Model>(items: number[] | M[]): {ids: unknown[], url: string | undefined} {
94+
let foundUrl: string | undefined = undefined;
95+
96+
let ids = items.map((x: number | M) => {
97+
// also find the url while we're at it
98+
if (typeof (x) == 'object' && x.$resource() && foundUrl == undefined) {
99+
foundUrl = x.$resource();
100+
}
101+
102+
return typeof(x) == 'number' ? x : x.$attributes[x.$getKeyName()]
103+
})
104+
105+
return {
106+
ids,
107+
url: foundUrl,
108+
}
109+
}
110+
}

0 commit comments

Comments
 (0)