-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPocketbaseExtended.h
More file actions
393 lines (348 loc) · 14.6 KB
/
PocketbaseExtended.h
File metadata and controls
393 lines (348 loc) · 14.6 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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
/**
* @file PocketbaseExtended.h
* @brief PocketBase client library for ESP8266 and ESP32.
*
* Provides full CRUD, authentication, structured error responses,
* and optional debug logging for PocketBase (https://pocketbase.io).
* No heavy dependencies — uses only the platform's built-in HTTP stack.
*
* Supported platforms: ESP8266, ESP32
* PocketBase API compatibility: v0.16+
*
* @version 1.0.0
* @author Jeo Carlo Lubao
* @license GPL-3.0
*/
#ifndef PocketbaseExtended_h
#define PocketbaseExtended_h
#include "Arduino.h"
#if defined(ESP8266)
# include <BearSSLHelpers.h>
# include <ESP8266HTTPClient.h>
# include <ESP8266WiFi.h>
#elif defined(ESP32)
# include <HTTPClient.h>
# include <WiFi.h>
# include <WiFiClientSecure.h>
#endif
// ---------------------------------------------------------------------------
// Response type
// ---------------------------------------------------------------------------
/**
* @brief Structured result returned by all @c Ex record and auth methods.
*
* Convenience methods (those without the @c Ex suffix) return only
* @c body as a @c String; use the @c Ex variants when you need the
* status code or a machine-readable error.
*/
struct PBResponse {
bool ok; ///< @c true when the HTTP status is 2xx.
int statusCode; ///< HTTP status code; @c 0 when the connection itself failed.
String body; ///< Raw JSON response body.
String error; ///< Human-readable error; equals @c body on 4xx/5xx responses.
};
// ---------------------------------------------------------------------------
// Client class
// ---------------------------------------------------------------------------
/**
* @brief PocketBase REST client for ESP8266 / ESP32.
*
* @par Basic usage
* @code
* PocketbaseExtended pb("https://my-pb-host.com");
* pb.collection("notes").getOne("RECORD_ID");
* @endcode
*
* @par Auth usage
* @code
* pb.collection("users").authWithPassword("user@example.com", "password");
* // token is stored automatically; all subsequent requests carry it
* pb.collection("notes").getListEx("1", "10");
* @endcode
*/
class PocketbaseExtended {
public:
// -----------------------------------------------------------------------
// Constructor
// -----------------------------------------------------------------------
/**
* @brief Construct a new PocketbaseExtended client.
*
* Trailing slashes in @p baseUrl are normalised automatically.
*
* @param[in] baseUrl Root URL of the PocketBase instance,
* e.g. @c "https://my-pb-host.com".
*/
explicit PocketbaseExtended(const char* baseUrl);
// -----------------------------------------------------------------------
// Collection selector
// -----------------------------------------------------------------------
/**
* @brief Set the active collection for subsequent requests.
*
* Returns a reference to @c *this so calls can be chained:
* @code
* pb.collection("notes").getOne("id");
* @endcode
*
* @param[in] name PocketBase collection name.
* @return Reference to this instance (chainable).
*/
PocketbaseExtended& collection(const char* name);
// -----------------------------------------------------------------------
// Record methods — extended (return PBResponse)
// -----------------------------------------------------------------------
/**
* @brief Fetch a single record by ID.
*
* PocketBase endpoint: @c GET /api/collections/{collection}/records/{id}
*
* @param[in] recordId ID of the record to fetch. Must not be empty.
* @param[in] expand Comma-separated relation fields to auto-expand,
* e.g. @c "author,tags.name". Pass @c nullptr to skip.
* @param[in] fields Comma-separated fields to include in the response,
* e.g. @c "id,title,created". Pass @c nullptr for all fields.
* @return PBResponse
*/
PBResponse getOneEx(const char* recordId,
const char* expand = nullptr,
const char* fields = nullptr);
/**
* @brief Fetch a paginated list of records.
*
* PocketBase endpoint: @c GET /api/collections/{collection}/records
*
* All parameters are optional. Pass @c nullptr or omit to use the
* server default for that parameter.
*
* @param[in] page Page number (1-based). Default: @c 1.
* @param[in] perPage Records per page (max 500). Default: @c 30.
* @param[in] sort Sort expression, e.g. @c "-created,id"
* (@c - prefix = DESC, no prefix = ASC).
* @param[in] filter PocketBase filter expression,
* e.g. @c "active = true && views > 100".
* @param[in] skipTotal Set to @c "1" to omit @c totalItems / @c totalPages
* from the response for faster queries.
* @param[in] expand Comma-separated relation fields to auto-expand.
* @param[in] fields Comma-separated fields to include in each record.
* @return PBResponse
*/
PBResponse getListEx(const char* page = nullptr,
const char* perPage = nullptr,
const char* sort = nullptr,
const char* filter = nullptr,
const char* skipTotal = nullptr,
const char* expand = nullptr,
const char* fields = nullptr);
/**
* @brief Create a new record.
*
* PocketBase endpoint: @c POST /api/collections/{collection}/records
*
* @param[in] requestBody JSON string of fields to set,
* e.g. @c "{\"title\":\"Hello\",\"active\":true}".
* @return PBResponse
*/
PBResponse createEx(const String& requestBody);
/**
* @brief Update an existing record (partial update).
*
* PocketBase endpoint: @c PATCH /api/collections/{collection}/records/{id}
*
* Only the fields present in @p requestBody are changed; omitted fields
* retain their current values.
*
* @param[in] recordId ID of the record to update. Must not be empty.
* @param[in] requestBody JSON string of fields to update.
* @return PBResponse
*/
PBResponse updateEx(const char* recordId, const String& requestBody);
/**
* @brief Delete a record by ID.
*
* PocketBase endpoint: @c DELETE /api/collections/{collection}/records/{id}
*
* A successful delete returns HTTP 204 with an empty body;
* @c PBResponse::ok will be @c true and @c body will be empty.
*
* @param[in] recordId ID of the record to delete. Must not be empty.
* @return PBResponse
*/
PBResponse deleteRecordEx(const char* recordId);
// -----------------------------------------------------------------------
// Record methods — convenience (return body String)
// -----------------------------------------------------------------------
/**
* @brief Convenience wrapper for getOneEx(). Returns the response body.
* @see getOneEx()
*/
String getOne(const char* recordId,
const char* expand = nullptr,
const char* fields = nullptr);
/**
* @brief Convenience wrapper for getListEx(). Returns the response body.
* @see getListEx()
*/
String getList(const char* page = nullptr,
const char* perPage = nullptr,
const char* sort = nullptr,
const char* filter = nullptr,
const char* skipTotal = nullptr,
const char* expand = nullptr,
const char* fields = nullptr);
/**
* @brief Convenience wrapper for createEx(). Returns the response body.
* @see createEx()
*/
String create(const String& requestBody);
/**
* @brief Convenience wrapper for updateEx(). Returns the response body.
* @see updateEx()
*/
String update(const char* recordId, const String& requestBody);
/**
* @brief Convenience wrapper for deleteRecordEx(). Returns the response body.
* @see deleteRecordEx()
*/
String deleteRecord(const char* recordId);
// -----------------------------------------------------------------------
// Authentication
// -----------------------------------------------------------------------
/**
* @brief Authenticate with an identity (email/username) and password.
*
* PocketBase endpoint:
* @c POST /api/collections/{collection}/auth-with-password
*
* On success, the returned JWT token is automatically extracted from
* the response body and stored internally. All subsequent requests will
* include @c Authorization: Bearer <token> until clearAuthToken() is called.
*
* @note Call @c collection() with the auth collection name (e.g. @c "users")
* before calling this method.
*
* @param[in] identity Email address or username of the user.
* @param[in] password Account password.
* @return PBResponse Full auth response body (contains @c token and @c record).
*/
PBResponse authWithPassword(const char* identity, const char* password);
/**
* @brief Refresh the currently stored auth token.
*
* PocketBase endpoint:
* @c POST /api/collections/{collection}/auth-refresh
*
* Exchanges the existing token for a new one with a renewed expiry.
* The updated token is stored automatically on success.
* Useful for long-running devices that need to stay authenticated
* without re-entering credentials.
*
* @note Requires an existing token (via authWithPassword() or setAuthToken())
* and the correct collection to be set.
*
* @return PBResponse Full auth response body (contains new @c token and @c record).
*/
PBResponse authRefresh();
/**
* @brief Manually set the auth token (e.g. a token restored from storage).
* @param[in] token JWT token string.
*/
void setAuthToken(const String& token);
/**
* @brief Retrieve the currently stored auth token.
* @return JWT token string, or an empty String if not authenticated.
*/
String getAuthToken() const;
/**
* @brief Clear the stored auth token (effective logout).
*
* Subsequent requests will no longer include an Authorization header.
*/
void clearAuthToken();
// -----------------------------------------------------------------------
// Configuration
// -----------------------------------------------------------------------
/**
* @brief Set the HTTP request timeout.
* @param[in] ms Timeout in milliseconds. Default: @c 10000.
*/
void setTimeout(uint32_t ms);
/**
* @brief Enable or disable TLS certificate verification.
*
* When @c true (default), the TLS certificate of the server is not
* verified — use this for self-signed or development certificates.
* Set to @c false in production environments with valid certificates.
*
* @param[in] enabled @c true to skip verification (insecure), @c false to verify.
*/
void setInsecureTLS(bool enabled);
/**
* @brief Enable or disable verbose debug logging to Serial.
*
* When enabled, request URLs, HTTP status codes, and response bodies
* are printed via @c Serial.println(). Disabled by default.
*
* @param[in] enabled @c true to enable logging, @c false to disable.
*/
void setDebug(bool enabled);
// -----------------------------------------------------------------------
// Health
// -----------------------------------------------------------------------
/**
* @brief Check whether the PocketBase server is healthy.
*
* PocketBase endpoint: @c GET /api/health
*
* Does not require a collection to be set.
* Useful as a connectivity probe at device startup.
*
* @return PBResponse Body is @c {"code":200,"message":"API is healthy."} on success.
*/
PBResponse checkHealth();
// -----------------------------------------------------------------------
// Files
// -----------------------------------------------------------------------
/**
* @brief Build the URL for a record file attachment.
*
* PocketBase file URL: @c GET /api/files/{collection}/{recordId}/{filename}
*
* This is a URL-construction helper — it does not make an HTTP request.
* Use the returned URL with an HTTP GET (or pass it to a browser / display).
*
* @param[in] recordId ID of the record that owns the file.
* @param[in] filename Exact filename as stored in the record field.
* @param[in] thumb Optional thumbnail size string, e.g. @c "100x100" or @c "0x50".
* Pass @c nullptr to get the original file.
* @return String Full URL to the file.
*
* @see https://pocketbase.io/docs/files-handling/
*/
String getFileUrl(const char* recordId,
const char* filename,
const char* thumb = nullptr);
private:
String _baseUrl; ///< Normalised base URL ending with @c "/api/".
String _collection; ///< Active collection name set by collection().
String _authToken; ///< Stored JWT; empty when not authenticated.
uint32_t _timeout; ///< Request timeout in milliseconds.
bool _insecureTLS; ///< Skip TLS certificate verification when @c true.
bool _debug; ///< Print debug output to Serial when @c true.
/** @brief Build the records endpoint URL, optionally appending a record ID. */
String _buildRecordsUrl(const char* recordId = nullptr);
/** @brief Append @c key=value to a URL query string; no-op if @p value is null or empty. */
String _appendParam(const String& url, const char* key, const char* value);
/** @brief Unified HTTP dispatcher for GET, POST, PATCH, and DELETE. */
PBResponse _request(const char* method,
const String& url,
const String& body = "");
/** @brief Print @p msg to Serial when debug mode is enabled. */
void _debugPrint(const String& msg);
};
// ---------------------------------------------------------------------------
// Backward-compatibility alias
// ---------------------------------------------------------------------------
/** @brief Alias for PocketbaseExtended. Retained for v0.x sketch compatibility. */
using PocketbaseArduino = PocketbaseExtended;
#endif // PocketbaseExtended_h