forked from albertodeago/curl-generator
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathform-body.ts
More file actions
67 lines (55 loc) · 1.74 KB
/
form-body.ts
File metadata and controls
67 lines (55 loc) · 1.74 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
import { CurlFileBody } from "./file-body";
import { CurlRawBody } from "./raw-body";
export interface CurlFormBody {
/**
* Form body type for URL-encoded form data.
*/
type: "form",
/**
* The content of the body.
*/
content: Record<string, string | CurlFileBody | CurlRawBody> | URLSearchParams,
}
export function formBodyToString(body: CurlFormBody): string {
if (body.content instanceof URLSearchParams) {
return body.content.toString();
}
return Object.entries(body.content)
.map(([key, value]) => {
if (typeof value === "string") {
return `${key}=${value}`;
}
if (value.type === "file") {
throw new Error(`Cannot use file body in form body when converting to string. Please use formBodyToCommand instead.`);
}
if (value.type === "raw") {
return `${key}=${value.content}`;
}
throw new Error(`Invalid form body value type: ${value}`);
})
.join("&");
}
export function isCurlFormBody(body: unknown): body is CurlFormBody {
return typeof body === "object" && body !== null && "type" in body && (body as {
[key: string]: unknown
}).type === "form" && "content" in body;
}
export function formBodyToCommand(body: CurlFormBody): string {
if (body.content instanceof URLSearchParams) {
return `-d '${body.content.toString()}'`;
}
return Object.entries(body.content)
.map(([key, value]) => {
if (typeof value === "string") {
return `-F ${key}=${value}`;
}
if (value.type === "file") {
return `-F ${key}=@${value.fileName}`;
}
if (value.type === "raw") {
return `-F ${key}=${value.content}`;
}
throw new Error(`Invalid form body value type: ${value}`);
})
.join(" \\\n ");
}