forked from Kong/httpsnippet
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathclient.ts
More file actions
79 lines (67 loc) · 2.24 KB
/
client.ts
File metadata and controls
79 lines (67 loc) · 2.24 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
/**
* @description
* HTTP code snippet generator for OCaml using CoHTTP.
*
* @author
* @SGrondin
*
* for any questions or issues regarding the generated code snippet, please open an issue mentioning the author.
*/
import type { Client } from '../../index.js';
import { CodeBuilder } from '../../../helpers/code-builder.js';
import { escapeForDoubleQuotes } from '../../../helpers/escape.js';
export const cohttp: Client = {
info: {
key: 'cohttp',
title: 'CoHTTP',
link: 'https://github.com/mirage/ocaml-cohttp',
description: 'Cohttp is a very lightweight HTTP server using Lwt or Async for OCaml',
extname: '.ml',
installation: () => 'opam install cohttp-lwt-unix cohttp-async',
},
convert: ({ fullUrl, allHeaders, postData, method }, options) => {
const opts = {
indent: ' ',
...options,
};
const methods = ['get', 'post', 'head', 'delete', 'patch', 'put', 'options'];
const { push, blank, join } = new CodeBuilder({ indent: opts.indent });
push('open Cohttp_lwt_unix');
push('open Cohttp');
push('open Lwt');
blank();
push(`let uri = Uri.of_string "${fullUrl}" in`);
// Add headers, including the cookies
const headers = Object.keys(allHeaders);
if (headers.length === 1) {
push(
`let headers = Header.add (Header.init ()) "${headers[0]}" "${escapeForDoubleQuotes(
allHeaders[headers[0]],
)}" in`,
);
} else if (headers.length > 1) {
push('let headers = Header.add_list (Header.init ()) [');
headers.forEach(key => {
push(`("${key}", "${escapeForDoubleQuotes(allHeaders[key])}");`, 1);
});
push('] in');
}
// Add body
if (postData.text) {
// Just text
push(`let body = Cohttp_lwt_body.of_string ${JSON.stringify(postData.text)} in`);
}
// Do the request
blank();
const h = headers.length ? '~headers ' : '';
const b = postData.text ? '~body ' : '';
const m = methods.includes(method.toLowerCase())
? `\`${method.toUpperCase()}`
: `(Code.method_of_string "${method}")`;
push(`Client.call ${h}${b}${m} uri`);
// Catch result
push('>>= fun (res, body_stream) ->');
push('(* Do stuff with the result *)', 1);
return join();
},
};