-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathFormData__test.res
More file actions
52 lines (40 loc) · 1.9 KB
/
Copy pathFormData__test.res
File metadata and controls
52 lines (40 loc) · 1.9 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
/* This works when your form has an id of "myForm" */
@scope(("document", "forms"))
external myForm: HTMLFormElement.t = "myForm"
module EntryValue = FormDataEntryValue
open EntryValue
let logEntry = (~stringPrefix: string, ~filePrefix: string, entry: EntryValue.t) =>
switch entry {
| String(value) => Console.log(`${stringPrefix}${value}`)
| File(file) => Console.log(`${filePrefix}${file.name}`)
}
let formData: FormData.t = FormData.make(~form=myForm)
// Get a form field - returns formDataEntryValue which could be string or WebApiFile
let phoneEntry: null<EntryValue.t> = formData->FormData.get("phone")
// Decode the entry to handle both string and WebApiFile cases
let _ = switch phoneEntry->Null.toOption {
| None => Console.log("No phone field")
| Some(entry) => logEntry(~stringPrefix="Phone: ", ~filePrefix="Unexpected file: ", entry)
}
// Get all values for a field (useful for multi-select or multiple file inputs)
let allImages: array<EntryValue.t> = formData->FormData.getAll("images")
let _ =
allImages->Array.forEach(entry =>
logEntry(~stringPrefix="String value: ", ~filePrefix="WebApiFile: ", entry)
)
// Create formDataEntryValue from string or file
let stringEntry = EntryValue.String("test value")
let blob: Blob.t = Blob.make(~blobParts=[])
let file: File.t = File.make(~fileBits=[], ~fileName="test.txt")
let fileEntry = EntryValue.File(file)
formData->FormData.appendBlob(~name="avatar", ~blobValue=blob)
logEntry(~stringPrefix="String entry: ", ~filePrefix="Unexpected file entry: ", stringEntry)
logEntry(~stringPrefix="Unexpected string entry: ", ~filePrefix="File entry: ", fileEntry)
// Iterate over all entries in the FormData
let entries: Iterator.t<(string, EntryValue.t)> = formData->FormData.entries
let _ = entries->Iterator.forEach(((key, value)) => {
switch value {
| String(s) => Console.log(`${key}: ${s}`)
| File(f) => Console.log(`${key}: [WebApiFile] ${f.name}`)
}
})