-
Notifications
You must be signed in to change notification settings - Fork 3
/
jsonApi.post.ts
62 lines (53 loc) · 1.56 KB
/
jsonApi.post.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
import { HttpClient, HttpOptions } from '@coolio/http';
import { RequestBuilder } from './jsonApi.builder';
import { Headers, RawResponse } from './jsonApi.interface';
import { JsonResponse } from './jsonApi.response';
export class PostBuilder<Raw extends RawResponse<any, any>> extends RequestBuilder<JsonResponse<Raw>> {
type?: string;
id?: string;
attributes?: object;
relationships?: Record<string, { data: { id: string; type: string } }>;
constructor(private httpClient: HttpClient, uri: string) {
super(uri, {});
}
ofType(type: string): this {
this.type = type;
return this;
}
withId(id: string): this {
this.id = id;
return this;
}
withAttributes(attributes: object): this {
this.attributes = attributes;
return this;
}
withRelationship(rel?: { name: string; uuid: string; type: string }): this {
if (!this.relationships) {
this.relationships = {};
}
if (rel) {
this.relationships[rel.name] = { data: { id: rel.uuid, type: rel.type } };
}
return this;
}
send(options: HttpOptions = {}): Promise<JsonResponse<Raw>> {
if (!this.type) {
throw new Error('Missing object type');
}
return this.httpClient.post<Raw>(this.uri, {
...options,
query: this.parameters,
body: {
data: {
id: this.id,
type: this.type,
attributes: this.attributes,
relationships: this.relationships,
},
},
headers: { ...Headers, ...options.headers },
})
.then(response => this.parseResponse(response));
}
}