Objectively
Object oriented framework for C.
Loading...
Searching...
No Matches
RESTClient.c
Go to the documentation of this file.
1/*
2 * Objectively: Ultra-lightweight object oriented framework for GNU C.
3 * Copyright (C) 2014 Jay Dolan <jay@jaydolan.com>
4 *
5 * This software is provided 'as-is', without any express or implied
6 * warranty. In no event will the authors be held liable for any damages
7 * arising from the use of this software.
8 *
9 * Permission is granted to anyone to use this software for any purpose,
10 * including commercial applications, and to alter it and redistribute it
11 * freely, subject to the following restrictions:
12 *
13 * 1. The origin of this software must not be misrepresented; you must not
14 * claim that you wrote the original software. If you use this software
15 * in a product, an acknowledgment in the product documentation would be
16 * appreciated but is not required.
17 *
18 * 2. Altered source versions must be plainly marked as such, and must not be
19 * misrepresented as being the original software.
20 *
21 * 3. This notice may not be removed or altered from any source distribution.
22 */
23
24#include <assert.h>
25#include <stdlib.h>
26
27#include <curl/curl.h>
28
29#include "RESTClient.h"
30#include "URL.h"
31#include "URLRequest.h"
32#include "URLSessionDataTask.h"
33
34#define _Class _RESTClient
35
36#pragma mark - Async internals
37
42
43static void RESTClient_AsyncCompletion(URLSessionTask *task, bool success) {
44
45 RESTClient_AsyncState *state = task->data;
46 URLSessionDataTask *dataTask = (URLSessionDataTask *) task;
47
48 if (state->completion) {
49 if (success) {
50 state->completion(task->response->httpStatusCode, dataTask->data, state->userData);
51 } else {
52 state->completion(0, NULL, state->userData);
53 }
54 }
55
56 free(state);
57 release(task);
58}
59
60#pragma mark - Request helpers
61
62static int request(RESTClient *self, HTTPMethod method, const char *url_string,
63 const Data *body, const char **headers, Data **out_data) {
64
65 if (out_data) {
66 *out_data = NULL;
67 }
68
70
71 if (method == HTTP_GET && !headers) {
72 URL *url = $(alloc(URL), initWithCharacters, url_string);
73 task = $(self->session, dataTaskWithURL, url, NULL);
74 release(url);
75 } else {
76 URL *url = $(alloc(URL), initWithCharacters, url_string);
78 release(url);
79 request->httpMethod = method;
80 if (body) {
81 request->httpBody = retain((Data *) body);
82 $(request, setValueForHTTPHeaderField, "application/json", "Content-Type");
83 }
84 if (headers) {
85 for (size_t i = 0; headers[i] && headers[i + 1]; i += 2) {
86 $(request, setValueForHTTPHeaderField, headers[i + 1], headers[i]);
87 }
88 }
89 task = $(self->session, dataTaskWithRequest, request, NULL);
91 }
92
93 if (task == NULL) {
94 return 0;
95 }
96
97 $((URLSessionTask *) task, execute);
98
99 const URLSessionTask *t = (URLSessionTask *) task;
100 const bool success = t->state == URLSESSIONTASK_COMPLETED && t->result == CURLE_OK;
101
102 const int status = success ? t->response->httpStatusCode : 0;
103 if (success && out_data && task->data) {
104 *out_data = retain(task->data);
105 }
106
107 release(task);
108 return status;
109}
110
111static void requestAsync(RESTClient *self, HTTPMethod method, const char *url_string,
112 const Data *body, const char **headers, RESTClientCompletion completion, void *userData) {
113
114 URLSessionDataTask *task;
115
116 if (method == HTTP_GET && !headers) {
117 URL *url = $(alloc(URL), initWithCharacters, url_string);
119 release(url);
120 } else {
121 URL *url = $(alloc(URL), initWithCharacters, url_string);
123 release(url);
124 request->httpMethod = method;
125 if (body) {
126 request->httpBody = retain((Data *) body);
127 $(request, setValueForHTTPHeaderField, "application/json", "Content-Type");
128 }
129 if (headers) {
130 for (size_t i = 0; headers[i] && headers[i + 1]; i += 2) {
131 $(request, setValueForHTTPHeaderField, headers[i + 1], headers[i]);
132 }
133 }
136 }
137
138 if (task == NULL) {
139 if (completion) {
140 completion(0, NULL, userData);
141 }
142 return;
143 }
144
145 RESTClient_AsyncState *state = calloc(1, sizeof(RESTClient_AsyncState));
146 state->completion = completion;
147 state->userData = userData;
148 task->urlSessionTask.data = state;
149
150 $((URLSessionTask *) task, resume);
151}
152
153#pragma mark - Object
154
158static void dealloc(Object *self) {
159
160 RESTClient *this = (RESTClient *) self;
161
162 release(this->session);
163
164 super(Object, self, dealloc);
165}
166
167#pragma mark - RESTClient
168
173static int del(RESTClient *self, const char *url, const char **headers, Data **data) {
174 return request(self, HTTP_DELETE, url, NULL, headers, data);
175}
176
181static void delAsync(RESTClient *self, const char *url, const char **headers,
182 RESTClientCompletion completion, void *userData) {
183 requestAsync(self, HTTP_DELETE, url, NULL, headers, completion, userData);
184}
185
190static int get(RESTClient *self, const char *url, const char **headers, Data **data) {
191 return request(self, HTTP_GET, url, NULL, headers, data);
192}
193
198static void getAsync(RESTClient *self, const char *url, const char **headers,
199 RESTClientCompletion completion, void *userData) {
200 requestAsync(self, HTTP_GET, url, NULL, headers, completion, userData);
201}
202
207static int head(RESTClient *self, const char *url, const char **headers) {
208 return request(self, HTTP_HEAD, url, NULL, headers, NULL);
209}
210
215static void headAsync(RESTClient *self, const char *url, const char **headers,
216 RESTClientCompletion completion, void *userData) {
217 requestAsync(self, HTTP_HEAD, url, NULL, headers, completion, userData);
218}
219
224static RESTClient *init(RESTClient *self) {
225 return $(self, initWithSession, $$(URLSession, sharedInstance));
226}
227
233
234 self = (RESTClient *) super(Object, self, init);
235 if (self) {
236 assert(session);
237 self->session = retain(session);
238 }
239 return self;
240}
241
246static int options(RESTClient *self, const char *url, const char **headers, Data **data) {
247 return request(self, HTTP_OPTIONS, url, NULL, headers, data);
248}
249
254static void optionsAsync(RESTClient *self, const char *url, const char **headers,
255 RESTClientCompletion completion, void *userData) {
256 requestAsync(self, HTTP_OPTIONS, url, NULL, headers, completion, userData);
257}
258
263static int patch(RESTClient *self, const char *url, const Data *body, const char **headers, Data **data) {
264 return request(self, HTTP_PATCH, url, body, headers, data);
265}
266
271static void patchAsync(RESTClient *self, const char *url, const Data *body, const char **headers,
272 RESTClientCompletion completion, void *userData) {
273 requestAsync(self, HTTP_PATCH, url, body, headers, completion, userData);
274}
275
280static int post(RESTClient *self, const char *url, const Data *body, const char **headers, Data **data) {
281 return request(self, HTTP_POST, url, body, headers, data);
282}
283
288static void postAsync(RESTClient *self, const char *url, const Data *body, const char **headers,
289 RESTClientCompletion completion, void *userData) {
290 requestAsync(self, HTTP_POST, url, body, headers, completion, userData);
291}
292
297static int put(RESTClient *self, const char *url, const Data *body, const char **headers, Data **data) {
298 return request(self, HTTP_PUT, url, body, headers, data);
299}
300
305static void putAsync(RESTClient *self, const char *url, const Data *body, const char **headers,
306 RESTClientCompletion completion, void *userData) {
307 requestAsync(self, HTTP_PUT, url, body, headers, completion, userData);
308}
309
311
317
318 static Once once;
319
320 do_once(&once, {
322 });
323
324 return _sharedInstance;
325}
326
327#pragma mark - Class lifecycle
328
329static void destroy(Class *clazz) {
331}
332
333static void initialize(Class *clazz) {
334
335 ((ObjectInterface *) clazz->interface)->dealloc = dealloc;
336
337 RESTClientInterface *rest = (RESTClientInterface *) clazz->interface;
338
339 rest->init = init;
341
342 rest->del = del;
343 rest->get = get;
344 rest->head = head;
345 rest->options = options;
346 rest->patch = patch;
347 rest->post = post;
348 rest->put = put;
349
350 rest->delAsync = delAsync;
351 rest->getAsync = getAsync;
352 rest->headAsync = headAsync;
353 rest->optionsAsync = optionsAsync;
354 rest->patchAsync = patchAsync;
355 rest->postAsync = postAsync;
356 rest->putAsync = putAsync;
357
358 rest->sharedInstance = sharedInstance;
359}
360
362
363 static Class *clazz;
364 static Once once;
365
366 do_once(&once, {
367 clazz = _initialize(&(const ClassDef) {
368 .name = "RESTClient",
369 .superclass = _Object(),
370 .instanceSize = sizeof(RESTClient),
371 .interfaceSize = sizeof(RESTClientInterface),
372 .initialize = initialize,
373 .destroy = destroy,
374 });
375 });
376
377 return clazz;
378}
379
380#undef _Class
ident release(ident obj)
Atomically decrement the given Object's reference count. If the resulting reference count is 0,...
Definition Class.c:356
Class * _initialize(const ClassDef *def)
Initializes the given Class.
Definition Class.c:151
ident retain(ident obj)
Atomically increment the given Object's reference count.
Definition Class.c:372
#define alloc(type)
Allocate and initialize and instance of type.
Definition Class.h:226
#define super(type, obj, method,...)
static Data * data(void)
Definition Data.c:286
Class * _Object(void)
Definition Object.c:136
static void resume(OperationQueue *self)
static int head(RESTClient *self, const char *url, const char **headers)
Definition RESTClient.c:207
static void destroy(Class *clazz)
Definition RESTClient.c:329
static void getAsync(RESTClient *self, const char *url, const char **headers, RESTClientCompletion completion, void *userData)
Definition RESTClient.c:198
static void putAsync(RESTClient *self, const char *url, const Data *body, const char **headers, RESTClientCompletion completion, void *userData)
Definition RESTClient.c:305
static void requestAsync(RESTClient *self, HTTPMethod method, const char *url_string, const Data *body, const char **headers, RESTClientCompletion completion, void *userData)
Definition RESTClient.c:111
static void optionsAsync(RESTClient *self, const char *url, const char **headers, RESTClientCompletion completion, void *userData)
Definition RESTClient.c:254
static void delAsync(RESTClient *self, const char *url, const char **headers, RESTClientCompletion completion, void *userData)
Definition RESTClient.c:181
static int del(RESTClient *self, const char *url, const char **headers, Data **data)
Definition RESTClient.c:173
static RESTClient * _sharedInstance
Definition RESTClient.c:310
static void patchAsync(RESTClient *self, const char *url, const Data *body, const char **headers, RESTClientCompletion completion, void *userData)
Definition RESTClient.c:271
static int put(RESTClient *self, const char *url, const Data *body, const char **headers, Data **data)
Definition RESTClient.c:297
static int request(RESTClient *self, HTTPMethod method, const char *url_string, const Data *body, const char **headers, Data **out_data)
Definition RESTClient.c:62
static RESTClient * init(RESTClient *self)
Definition RESTClient.c:224
static void postAsync(RESTClient *self, const char *url, const Data *body, const char **headers, RESTClientCompletion completion, void *userData)
Definition RESTClient.c:288
Class * _RESTClient(void)
Definition RESTClient.c:361
static void dealloc(Object *self)
Definition RESTClient.c:158
static RESTClient * initWithSession(RESTClient *self, URLSession *session)
Definition RESTClient.c:232
static int post(RESTClient *self, const char *url, const Data *body, const char **headers, Data **data)
Definition RESTClient.c:280
static int get(RESTClient *self, const char *url, const char **headers, Data **data)
Definition RESTClient.c:190
static int patch(RESTClient *self, const char *url, const Data *body, const char **headers, Data **data)
Definition RESTClient.c:263
static void initialize(Class *clazz)
Definition RESTClient.c:333
static void RESTClient_AsyncCompletion(URLSessionTask *task, bool success)
Definition RESTClient.c:43
static RESTClient * sharedInstance(void)
Definition RESTClient.c:316
static void headAsync(RESTClient *self, const char *url, const char **headers, RESTClientCompletion completion, void *userData)
Definition RESTClient.c:215
static int options(RESTClient *self, const char *url, const char **headers, Data **data)
Definition RESTClient.c:246
An HTTP REST client backed by URLSession.
static String * initWithCharacters(String *self, const char *chars)
Definition String.c:633
static ThreadPoolWork * execute(ThreadPool *self, ThreadFunction function, ident data)
Definition ThreadPool.c:192
Uniform Resource Locators (RFC 3986).
static URLRequest * initWithURL(URLRequest *self, URL *url)
Definition URLRequest.c:150
static void setValueForHTTPHeaderField(URLRequest *self, const char *value, const char *field)
Definition URLRequest.c:169
A protocol-agnostic abstraction for requesting resources via URLs.
HTTPMethod
Definition URLRequest.h:42
@ HTTP_PUT
Definition URLRequest.h:48
@ HTTP_DELETE
Definition URLRequest.h:50
@ HTTP_GET
Definition URLRequest.h:46
@ HTTP_OPTIONS
Definition URLRequest.h:45
@ HTTP_POST
Definition URLRequest.h:47
@ HTTP_HEAD
Definition URLRequest.h:44
@ HTTP_PATCH
Definition URLRequest.h:49
static URLSessionDataTask * dataTaskWithRequest(URLSession *self, URLRequest *request, URLSessionTaskCompletion completion)
Definition URLSession.c:85
static URLSessionDataTask * dataTaskWithURL(URLSession *self, URL *url, URLSessionTaskCompletion completion)
Definition URLSession.c:129
Use data tasks to send and receive Data in-memory.
@ URLSESSIONTASK_COMPLETED
long Once
The Once type.
Definition Once.h:37
#define do_once(once, block)
Executes the given block at most one time.
Definition Once.h:43
void(* RESTClientCompletion)(int status, Data *data, void *userData)
A completion handler for asynchronous RESTClient requests.
Definition RESTClient.h:50
ClassDefs are passed to _initialize via an archetype to initialize a Class.
Definition Class.h:41
The runtime representation of a Class.
Definition Class.h:90
ident interface
The interface of the Class.
Definition Class.h:100
Data buffers.
Definition Data.h:50
Object is the root Class of The Objectively Class hierarchy.
Definition Object.h:46
RESTClientCompletion completion
Definition RESTClient.c:39
An HTTP REST client backed by URLSession.
Definition RESTClient.h:62
RESTClient * initWithSession(RESTClient *, URLSession *)
Initializes this RESTClient with the specified URLSession.
Definition RESTClient.c:232
URLSession * session
The URLSession backing this client.
Definition RESTClient.h:78
int del(RESTClient *, const char *, const char **, Data **)
Synchronously performs an HTTP DELETE request.
Definition RESTClient.c:173
Uniform Resource Locators (RFC 3986).
Definition URL.h:44
A protocol-agnostic abstraction for requesting resources via URLs.
Definition URLRequest.h:58
int httpStatusCode
The HTTP response status code.
Definition URLResponse.h:63
Use data tasks to send and receive Data in-memory.
Data * data
The data received.
URLSessionTask urlSessionTask
The superclass.
A management context for loading resources via URLs.
Definition URLSession.h:59
URL session tasks are handles to pending URL operations.
struct URLResponse * response
The response.
int result
The libcurl result code (CURLcode) of the transfer, 0 on success.
ident data
User data.
URLSessionTaskState state
The state.