-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
🧑💻 Introduce fetch util to make it more easy to do requests and to r…
…educe code duplication
- Loading branch information
1 parent
eaa4496
commit d4d17a7
Showing
3 changed files
with
38 additions
and
19 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
const std = @import("std"); | ||
|
||
const InitOptions = struct { | ||
allocator: std.mem.Allocator, | ||
method: std.http.Method, | ||
body: ?[]u8 = null, | ||
headers: ?std.http.Client.Request.Headers = null, | ||
}; | ||
|
||
/// Very loosely based on the `fetch` API from JavaScript to make it slightly more user friendly to perform requests | ||
pub fn fetch(comptime T: type, url: []const u8, options: InitOptions) !T { | ||
var client: std.http.Client = .{ .allocator = options.allocator }; | ||
defer client.deinit(); | ||
|
||
const headers = options.headers orelse std.http.Client.Request.Headers{ .content_type = std.http.Client.Request.Headers.Value{ .override = "application/json" } }; | ||
var body = std.ArrayList(u8).init(options.allocator); | ||
_ = try client.fetch(.{ .location = .{ .url = url }, .method = options.method, .headers = headers, .response_storage = .{ .dynamic = &body }, .payload = options.body }); | ||
|
||
const data = try std.json.parseFromSlice(T, options.allocator, body.items, .{ .allocate = .alloc_always, .ignore_unknown_fields = true }); | ||
|
||
return data.value; | ||
} |