Skip to content

Commit 1af2c47

Browse files
committed
Improve code examples for Clojure and C#
1 parent 6fb34ba commit 1af2c47

File tree

3 files changed

+186
-116
lines changed

3 files changed

+186
-116
lines changed

examples.md

Lines changed: 60 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -4,27 +4,29 @@
44

55
```Clojure
66
(ns my.namespace
7-
(:require [clj-http.client :as client]))
7+
(:require [clj-http.client :as client]))
88

99
(defn make-request []
10-
(let [options {:url "http://example.com"
11-
:method :post
12-
:headers {"Content-Type":"application/json"}
13-
:body "{"name":"John Doe"}"}]
14-
(client/request options))
10+
(let [options {:url "http://example.com"
11+
:method :post
12+
:headers {"Content-Type":"application/json"}
13+
:body {"name" "John Doe"}}]
14+
(let [response (client/request options)]
15+
response)))
1516
```
1617

1718
## Clojure (GET)
1819

1920
```Clojure
2021
(ns my.namespace
21-
(:require [clj-http.client :as client]))
22+
(:require [clj-http.client :as client]))
2223

2324
(defn make-request []
24-
(let [options {:url "http://example.com"
25-
:query {"foo":"bar"}
26-
:method :get}]
27-
(client/request options))
25+
(let [options {:url "http://example.com"
26+
:query {"foo":"bar"}
27+
:method :get}]
28+
(let [response (client/request options)]
29+
response)))
2830
```
2931

3032
## C# (POST)
@@ -33,36 +35,34 @@
3335
using System;
3436
using System.Net.Http;
3537
using System.Threading.Tasks;
36-
37-
public class Program
38-
{
39-
public static async Task Main(string[] args)
40-
{
41-
using (var client = new HttpClient())
42-
{
43-
var request = new HttpRequestMessage
44-
{
45-
Method = new HttpMethod("POST"),
46-
RequestUri = new Uri("http://example.com"),
47-
};
48-
49-
request.Headers.Add("Content-Type", "application/json");
50-
51-
request.Content = new StringContent("{"name":"John Doe"}");
52-
53-
54-
55-
try
56-
{
57-
using (var response = await client.SendAsync(request))
58-
{
59-
response.EnsureSuccessStatusCode();
60-
}
61-
}
62-
catch (Exception ex)
63-
{
64-
Console.WriteLine(ex.ToString());
65-
}
38+
using System.Text.Json;
39+
40+
public class Program {
41+
public static async Task Main(string[] args) {
42+
using var client = new HttpClient();
43+
var requestData = new {
44+
name = "John Doe"
45+
};
46+
47+
var request = new HttpRequestMessage {
48+
Method = new HttpMethod("POST"),
49+
RequestUri = new Uri("http://example.com")
50+
};
51+
request.Headers.Add("Content-Type", "application/json");
52+
53+
var jsonOptions = new JsonSerializerOptions {
54+
};
55+
request.Content = new StringContent(
56+
JsonSerializer.Serialize(requestData, jsonOptions),
57+
System.Text.Encoding.UTF8,
58+
"application/json"
59+
);
60+
61+
try {
62+
using var response = await client.SendAsync(request);
63+
response.EnsureSuccessStatusCode();
64+
} catch (Exception ex) {
65+
Console.WriteLine(ex.ToString());
6666
}
6767
}
6868
}
@@ -74,38 +74,25 @@ public class Program
7474
using System;
7575
using System.Net.Http;
7676
using System.Threading.Tasks;
77-
78-
public class Program
79-
{
80-
public static async Task Main(string[] args)
81-
{
82-
using (var client = new HttpClient())
83-
{
84-
var request = new HttpRequestMessage
85-
{
86-
Method = new HttpMethod("GET"),
87-
RequestUri = new Uri("http://example.com"),
88-
};
89-
90-
91-
92-
93-
94-
var query = System.Web.HttpUtility.ParseQueryString(string.Empty);
95-
query["foo"] = "bar";
96-
request.RequestUri = new Uri(request.RequestUri + "?" + query);
97-
98-
try
99-
{
100-
using (var response = await client.SendAsync(request))
101-
{
102-
response.EnsureSuccessStatusCode();
103-
}
104-
}
105-
catch (Exception ex)
106-
{
107-
Console.WriteLine(ex.ToString());
108-
}
77+
using System.Text.Json;
78+
79+
public class Program {
80+
public static async Task Main(string[] args) {
81+
using var client = new HttpClient();
82+
var request = new HttpRequestMessage {
83+
Method = new HttpMethod("GET"),
84+
RequestUri = new Uri("http://example.com")
85+
};
86+
87+
88+
var query = System.Web.HttpUtility.ParseQueryString(string.Empty);
89+
query["foo"] = "bar";
90+
request.RequestUri = new Uri(request.RequestUri + "?" + query);
91+
try {
92+
using var response = await client.SendAsync(request);
93+
response.EnsureSuccessStatusCode();
94+
} catch (Exception ex) {
95+
Console.WriteLine(ex.ToString());
10996
}
11097
}
11198
}

src/generators/clojure.ts

Lines changed: 31 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,50 @@
11
import { RequestOptions } from "../request";
22

3+
function jsonToClojure(jsonStr: string): string {
4+
try {
5+
const obj = JSON.parse(jsonStr);
6+
return JSON.stringify(obj)
7+
.replace(/:/g, " ")
8+
.replace(/,/g, "")
9+
.replace(/"\s*{/g, "{")
10+
.replace(/}"/g, "}")
11+
.replace(/"([^"]+)"\s+"([^"]+)"/g, '"$1" "$2"');
12+
} catch (e) {
13+
return `"${jsonStr}"`;
14+
}
15+
}
16+
317
export function generateClojureCode(options: RequestOptions): string {
4-
let code = `(ns my.namespace\n(:require [clj-http.client :as client]))\n\n(defn make-request []\n`;
18+
let code = `(ns my.namespace
19+
(:require [clj-http.client :as client]))
520
6-
code += `(let [options {:url "${options.url}"`;
21+
(defn make-request []
22+
(let [options {:url "${options.url}"`;
723

824
if (options.query) {
9-
code += `\n:query ${JSON.stringify(options.query)}`;
25+
const queryStr = JSON.stringify(options.query)
26+
.replace(/:\s*/g, ":")
27+
.replace(/,\s*/g, ",");
28+
code += `\n :query ${queryStr}`;
1029
}
1130

1231
if (options.method) {
13-
code += `\n:method :${options.method.toLowerCase()}`;
32+
code += `\n :method :${options.method.toLowerCase()}`;
1433
}
1534

1635
if (options.headers) {
17-
code += `\n:headers ${JSON.stringify(options.headers)}`;
36+
const headersStr = JSON.stringify(options.headers)
37+
.replace(/:\s*/g, ":")
38+
.replace(/,\s*/g, ",");
39+
code += `\n :headers ${headersStr}`;
1840
}
1941

2042
if (options.body) {
21-
code += `\n:body "${options.body}"`;
43+
code += `\n :body ${jsonToClojure(options.body)}`;
2244
}
2345

24-
code += `}]\n(client/request options))`;
46+
code += `}]\n (let [response (client/request options)]
47+
response)))`;
2548

2649
return code;
27-
}
50+
}

src/generators/csharp.ts

Lines changed: 95 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,109 @@
11
import { RequestOptions } from "../request";
22

33
export function generateCSharpCode(options: RequestOptions): string {
4+
// Remove content-type from headers if it's JSON since it will be set by StringContent
5+
const headers = { ...options.headers };
6+
const isJsonContent =
7+
headers &&
8+
Object.entries(headers).some(
9+
([key, value]) =>
10+
key.toLowerCase() === "content-type" &&
11+
value.toLowerCase().includes("json")
12+
);
13+
14+
// Helper function to convert JSON to C# object initialization syntax
15+
function toCSharpObject(obj: any, indent: number = 3): string {
16+
if (obj === null) return "null";
17+
if (typeof obj === "string") return `"${obj}"`;
18+
if (typeof obj === "number" || typeof obj === "boolean")
19+
return obj.toString();
20+
if (Array.isArray(obj)) {
21+
if (obj.length === 0) return "new object[] {}";
22+
const items = obj
23+
.map((item) => toCSharpObject(item, indent + 1))
24+
.join(",\n" + " ".repeat(indent * 4));
25+
return `new object[] {\n${" ".repeat(
26+
indent * 4
27+
)}${items}\n${" ".repeat((indent - 1) * 4)}}`;
28+
}
29+
if (typeof obj === "object") {
30+
const entries = Object.entries(obj);
31+
if (entries.length === 0) return "new {}";
32+
const props = entries
33+
.map(
34+
([key, value]) =>
35+
`${key} = ${toCSharpObject(value, indent + 1)}`
36+
)
37+
.join(",\n" + " ".repeat(indent * 4));
38+
return `new {\n${" ".repeat(indent * 4)}${props}\n${" ".repeat(
39+
(indent - 1) * 4
40+
)}}`;
41+
}
42+
return "null";
43+
}
44+
445
let code = `using System;
546
using System.Net.Http;
647
using System.Threading.Tasks;
48+
using System.Text.Json;
749
8-
public class Program
9-
{
10-
public static async Task Main(string[] args)
11-
{
12-
using (var client = new HttpClient())
13-
{
14-
var request = new HttpRequestMessage
15-
{
16-
Method = new HttpMethod("${options.method || 'GET'}"),
17-
RequestUri = new Uri("${options.url}"),
18-
};
19-
20-
${options.headers ? Object.entries(options.headers).map(([key, value]) => `request.Headers.Add("${key}", "${value}");`).join('\n') : ''}
21-
22-
${options.body ? `request.Content = new StringContent("${options.body}");` : ''}
23-
24-
${options.query ? `var query = System.Web.HttpUtility.ParseQueryString(string.Empty);
25-
${Object.entries(options.query).map(([key, value]) => {
50+
public class Program {
51+
public static async Task Main(string[] args) {
52+
using var client = new HttpClient();
53+
${
54+
isJsonContent && options.body
55+
? `var requestData = ${toCSharpObject(
56+
JSON.parse(options.body)
57+
)};\n\n `
58+
: ""
59+
}var request = new HttpRequestMessage {
60+
Method = new HttpMethod("${options.method || "GET"}"),
61+
RequestUri = new Uri("${options.url}")
62+
};
63+
${Object.entries(headers || {})
64+
.map(
65+
([key, value]) =>
66+
`request.Headers.Add("${key}", "${value}");\n `
67+
)
68+
.join("")}
69+
${
70+
options.body
71+
? isJsonContent
72+
? `var jsonOptions = new JsonSerializerOptions {
73+
};
74+
request.Content = new StringContent(
75+
JsonSerializer.Serialize(requestData, jsonOptions),
76+
System.Text.Encoding.UTF8,
77+
"application/json"
78+
);`
79+
: `request.Content = new StringContent("${options.body}");`
80+
: ""
81+
}
82+
${
83+
options.query
84+
? `var query = System.Web.HttpUtility.ParseQueryString(string.Empty);
85+
${Object.entries(options.query)
86+
.map(([key, value]) => {
2687
if (Array.isArray(value)) {
27-
return value.map(v => `query["${key}"] = "${v}";`).join('\n');
88+
return value
89+
.map((v) => `query["${key}"] = "${v}";\n `)
90+
.join("");
2891
} else {
29-
return `query["${key}"] = "${value}";`;
92+
return `query["${key}"] = "${value}";\n `;
3093
}
31-
}).join('\n')}
32-
request.RequestUri = new Uri(request.RequestUri + "?" + query);` : ''}
33-
34-
try
35-
{
36-
using (var response = await client.SendAsync(request))
37-
{
38-
response.EnsureSuccessStatusCode();
39-
}
40-
}
41-
catch (Exception ex)
42-
{
43-
Console.WriteLine(ex.ToString());
44-
}
94+
})
95+
.join(
96+
""
97+
)}request.RequestUri = new Uri(request.RequestUri + "?" + query);`
98+
: ""
99+
}
100+
try {
101+
using var response = await client.SendAsync(request);
102+
response.EnsureSuccessStatusCode();
103+
} catch (Exception ex) {
104+
Console.WriteLine(ex.ToString());
45105
}
46106
}
47107
}`;
48108
return code;
49-
}
109+
}

0 commit comments

Comments
 (0)