Skip to content

Commit c122a7d

Browse files
committed
Improve in code docs.
1 parent 6460c0a commit c122a7d

File tree

1 file changed

+48
-3
lines changed

1 file changed

+48
-3
lines changed

lib/Encoder.ts

Lines changed: 48 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,23 @@ export class Encoder {
3232
*/
3333
readonly #form: FormDataLike
3434

35+
/**
36+
* Creates a multipart/form-data encoder.
37+
*
38+
* @param form - A FormData object to encode. This object must be a spec-compatible FormData implementation.
39+
* @param boundary - An optional boundary string that will be used by the encoder. If there's no boundary string is present, Encoder will generate it automatically.
40+
*
41+
* @example
42+
*
43+
* import {Encoder} from "form-data-encoder"
44+
* import {FormData} from "formdata-node"
45+
*
46+
* const fd = new FormData()
47+
*
48+
* fd.set("greeting", "Hello, World!")
49+
*
50+
* const encoder = new Encoder(fd)
51+
*/
3552
constructor(form: FormDataLike, boundary: string = createBoundary()) {
3653
if (!isFormData(form)) {
3754
throw new TypeError("Expected first argument to be a FormData instance.")
@@ -45,8 +62,9 @@ export class Encoder {
4562
this.contentType = `multipart/form-data; boundary=${this.boundary}`
4663

4764
this.#form = form
48-
this.#footer = new TextEncoder()
49-
.encode(`${DASHES}${this.boundary}${DASHES}${CRLF.repeat(2)}`)
65+
this.#footer = new TextEncoder().encode(
66+
`${DASHES}${this.boundary}${DASHES}${CRLF.repeat(2)}`
67+
)
5068
}
5169

5270
/**
@@ -55,7 +73,7 @@ export class Encoder {
5573
get headers() {
5674
return {
5775
"Content-Type": this.contentType,
58-
"Content-Length": this.getContentLength()
76+
"Content-Length": this.getContentLength(),
5977
}
6078
}
6179

@@ -94,6 +112,33 @@ export class Encoder {
94112

95113
/**
96114
* Creates an async iterator allowing to perform the encoding by portions.
115+
*
116+
* @example
117+
*
118+
* import {Readable} from "stream"
119+
*
120+
* import {FormData, File, fileFromPath} from "formdata-node"
121+
* import {Encoder} from "form-data-encoder"
122+
*
123+
* import fetch from "node-fetch"
124+
*
125+
* const fd = new FormData()
126+
*
127+
* fd.set("field", "Just a random string")
128+
* fd.set("file", new File(["Using files is class amazing"]))
129+
* fd.set("fileFromPath", await fileFromPath("path/to/a/file.txt"))
130+
*
131+
* const encoder = new Encoder(fd)
132+
*
133+
* const options = {
134+
* method: "post",
135+
* headers: encoder.headers,
136+
* body: Readable.from(encoder.encode()) // or Readable.from(encoder)
137+
* }
138+
*
139+
* const response = await fetch("https://httpbin.org/post", options)
140+
*
141+
* console.log(await response.json())
97142
*/
98143
async* encode(): AsyncGenerator<Uint8Array, void, undefined> {
99144
for (const [name, value] of this.#form) {

0 commit comments

Comments
 (0)