-
-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathaction.ts
More file actions
206 lines (168 loc) · 4.79 KB
/
action.ts
File metadata and controls
206 lines (168 loc) · 4.79 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
import { State } from './state';
import * as qs from 'querystring';
import Client from './client';
import { Field } from './field';
import Resource from './resource';
export interface ActionInfo {
/**
* What url to post the form to.
*/
uri: string;
/**
* Action name.
*
* Some formats call this the 'rel'
*/
name: string | null;
/**
* Form title.
*
* Should be human-friendly.
*/
title?: string;
/**
* The HTTP method to use
*/
method: string;
/**
* The contentType to use for the form submission
*/
contentType: string;
/**
* Returns the list of fields associated to an action
*/
fields: Field[];
}
/**
* An action represents a hypermedia form submission or action.
*/
export interface Action<T extends Record<string, any> = Record<string, any>> extends ActionInfo {
/**
* Execute the action or submit the form.
*/
submit(formData: T): Promise<State>;
/**
* Execute the action or submit the form, then return the next resource.
*
* If a server responds with a 201 Status code and a Location header,
* it will automatically return the newly created resource.
*
* If the server responded with a 204 or 205, this function will return
* `this`.
*/
submitFollow(formData: T): Promise<Resource>;
}
export class SimpleAction<TFormData extends Record<string, any>> implements Action {
/**
* What url to post the form to.
*/
uri!: string;
/**
* Action name.
*
* Some formats call this the 'rel'
*/
name!: string | null;
/**
* Form title.
*
* Should be human-friendly.
*/
title!: string;
/**
* The HTTP method to use
*/
method!: string;
/**
* The contentType to use for the form submission
*/
contentType!: string;
/**
* Returns the list of fields associated to an action
*/
fields!: Field[];
/**
* Reference to client
*/
client: Client;
constructor(client: Client, formInfo: ActionInfo) {
this.client = client;
for(const [k, v] of Object.entries(formInfo)) {
this[k as keyof ActionInfo] = v;
}
}
/**
* Execute the action or submit the form.
*/
async submit(formData: TFormData): Promise<State<any>> {
const uri = new URL(this.uri);
const newFormData = this.validateForm(formData);
if (this.method === 'GET') {
uri.search = qs.stringify(newFormData);
const resource = this.client.go(uri.toString());
return resource.get();
}
const response = await this.fetchOrThrowWithBody(uri, newFormData);
const state = this.client.getStateForResponse(uri.toString(), response);
return state;
}
async submitFollow(formData: TFormData): Promise<Resource> {
const uri = new URL(this.uri);
const newFormData = this.validateForm(formData);
if (this.method === 'GET') {
uri.search = qs.stringify(newFormData);
return this.client.go(uri.toString());
}
const response = await this.fetchOrThrowWithBody(uri, newFormData);
switch (response.status) {
case 201:
if (response.headers.has('location')) {
return this.client.go(response.headers.get('location')!);
}
throw new Error('Could not follow after a 201 request, because the server did not reply with a Location header. If you sent a Location header, check if your service is returning "Access-Control-Expose-Headers: Location".');
case 204 :
case 205 :
return this.client.go(uri.toString());
default:
throw new Error('Did not receive a 201, 204 or 205 status code so we could not follow to the next resource');
}
}
private validateForm(formData: TFormData): TFormData {
const newFormData: TFormData = {
...formData
};
for (const field of this.fields) {
if (!(field.name in formData)) {
if (field.value) {
// We don't have perfect types for fields vs. FormData and how they
// related, so 'any' is needed here.
(newFormData as any)[field.name] = field.value;
} else if (field.required) {
throw new Error(`The ${field.name} field is required in this form`);
}
}
}
return newFormData;
}
private fetchOrThrowWithBody(uri: URL, formData: TFormData): Promise<Response> {
let body;
switch (this.contentType) {
case 'application/x-www-form-urlencoded' :
body = qs.stringify(formData);
break;
case 'application/json':
body = JSON.stringify(formData);
break;
default :
throw new Error(`Serializing mimetype ${this.contentType} is not yet supported in actions`);
}
return this.client.fetcher.fetchOrThrow(uri.toString(), {
method: this.method,
body,
headers: {
'Content-Type': this.contentType
}
});
}
}
export class ActionNotFound extends Error {}