Skip to content

Commit 03e00a7

Browse files
authored
Support alternative HTTP methods
This change proposed supporting the use of alternative HTTP methods. For example, now a user can define `http-method=GET` and then component will issue a `GET` request using encoded query params instead. All values other than POST will use this new approach. The default remains POST.
1 parent 342da47 commit 03e00a7

File tree

1 file changed

+18
-5
lines changed

1 file changed

+18
-5
lines changed

src/auto-check-element.ts

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,14 @@ export class AutoCheckElement extends HTMLElement {
176176
set csrfField(value: string) {
177177
this.setAttribute('csrf-field', value)
178178
}
179+
180+
get httpMethod(): string {
181+
return this.getAttribute('http-method') || 'POST'
182+
}
183+
184+
get isHttpPost(): bool {
185+
return this.httpMethod == 'POST'
186+
}
179187
}
180188

181189
function setLoadingState(event: Event) {
@@ -190,7 +198,7 @@ function setLoadingState(event: Event) {
190198
const state = states.get(autoCheckElement)
191199

192200
// If some attributes are missing we want to exit early and make sure that the element is valid.
193-
if (!src || !csrf || !state) {
201+
if (!src || (isHttpPost && !csrf) || !state) {
194202
return
195203
}
196204

@@ -240,7 +248,7 @@ async function check(autoCheckElement: AutoCheckElement) {
240248
const state = states.get(autoCheckElement)
241249

242250
// If some attributes are missing we want to exit early and make sure that the element is valid.
243-
if (!src || !csrf || !state) {
251+
if (!src || (isHttpPost && !csrf) || !state) {
244252
if (autoCheckElement.required) {
245253
input.setCustomValidity('')
246254
}
@@ -255,8 +263,13 @@ async function check(autoCheckElement: AutoCheckElement) {
255263
}
256264

257265
const body = new FormData()
258-
body.append(csrfField, csrf)
259-
body.append('value', input.value)
266+
if (isHttpPost) {
267+
body.append(csrfField, csrf)
268+
body.append('value', input.value)
269+
} else {
270+
url = new URL(src);
271+
url.search = new URLSearchParams({ value: input.value }).toString();
272+
}
260273

261274
input.dispatchEvent(new AutoCheckSendEvent(body))
262275

@@ -272,7 +285,7 @@ async function check(autoCheckElement: AutoCheckElement) {
272285
const response = await fetchWithNetworkEvents(autoCheckElement, src, {
273286
credentials: 'same-origin',
274287
signal: state.controller.signal,
275-
method: 'POST',
288+
method: httpMethod,
276289
body,
277290
})
278291
if (response.ok) {

0 commit comments

Comments
 (0)