-
Notifications
You must be signed in to change notification settings - Fork 242
Expand file tree
/
Copy pathclient.ts
More file actions
101 lines (86 loc) · 2.65 KB
/
client.ts
File metadata and controls
101 lines (86 loc) · 2.65 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
/**
* @description
* HTTP code snippet generator for Dart http package.
*
* @author
* @AI-Generated
*
* for any questions or issues regarding the generated code snippet, please open an issue mentioning the author.
*/
import { CodeBuilder } from '../../../helpers/code-builder';
import { escapeForSingleQuotes } from '../../../helpers/escape';
import { Client } from '../../targets';
export interface DartHttpOptions {
showBoilerplate?: boolean;
checkErrors?: boolean;
printBody?: boolean;
timeout?: number;
insecureSkipVerify?: boolean;
}
export const http: Client<DartHttpOptions> = {
info: {
key: 'http',
title: 'HTTP',
link: 'https://pub.dev/packages/http',
description: 'Dart HTTP client request using the http package',
},
convert: ({ postData, method, allHeaders, fullUrl }, options = {}) => {
const { blank, push, join } = new CodeBuilder({ indent: ' ' });
const {
showBoilerplate = true,
checkErrors = false,
printBody = true,
timeout = -1,
insecureSkipVerify = false,
} = options;
const indent = showBoilerplate ? 1 : 0;
// Create boilerplate
if (showBoilerplate) {
push('import \'package:http/http.dart\' as http;');
blank();
push('void main() async {');
blank();
}
// Create client with timeout if specified
if (timeout > 0) {
push('final client = http.Client();', indent);
push(`client.timeout = Duration(seconds: ${timeout});`, indent);
blank();
}
// Add headers setup
if (Object.keys(allHeaders).length) {
push('final headers = {', indent);
Object.keys(allHeaders).forEach(key => {
push(`'${key}': '${escapeForSingleQuotes(allHeaders[key])}',`, indent + 1);
});
push('};', indent);
blank();
}
// Prepare request
const headersVar = Object.keys(allHeaders).length ? 'headers' : '{}';
if (postData.text) {
push(`final response = await http.${method.toLowerCase()}(`, indent);
push(` Uri.parse('${fullUrl}'),`, indent);
push(` headers: ${headersVar},`, indent);
push(` body: ${JSON.stringify(postData.text)},`, indent);
push(');', indent);
} else {
push(`final response = await http.${method.toLowerCase()}(`, indent);
push(` Uri.parse('${fullUrl}'),`, indent);
push(` headers: ${headersVar},`, indent);
push(');', indent);
}
// Print response
blank();
push('print(response.statusCode);', indent);
if (printBody) {
push('print(response.body);', indent);
}
// End main block
if (showBoilerplate) {
blank();
push('}');
}
return join();
},
};