-
Notifications
You must be signed in to change notification settings - Fork 284
/
rest.d
1957 lines (1656 loc) · 58.8 KB
/
rest.d
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
Automatic REST interface and client code generation facilities.
Copyright: © 2012-2016 RejectedSoftware e.K.
License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file.
Authors: Sönke Ludwig, Михаил Страшун
*/
module vibe.web.rest;
public import vibe.web.common;
import vibe.core.log;
import vibe.http.router : URLRouter;
import vibe.http.client : HTTPClientSettings;
import vibe.http.common : HTTPMethod;
import vibe.http.server : HTTPServerRequestDelegate;
import vibe.http.status : isSuccessCode;
import vibe.internal.meta.uda;
import vibe.internal.meta.funcattr;
import vibe.inet.url;
import vibe.inet.message : InetHeaderMap;
import vibe.web.internal.rest.common : RestInterface, Route, SubInterfaceType;
import vibe.web.auth : AuthInfo, handleAuthentication, handleAuthorization, isAuthenticated;
import std.algorithm : startsWith, endsWith;
import std.range : isOutputRange;
import std.typecons : Nullable;
import std.typetuple : anySatisfy, Filter;
import std.traits;
/**
Registers a REST interface and connects it the the given instance.
Each method of the given class instance is mapped to the corresponing HTTP
verb. Property methods are mapped to GET/PUT and all other methods are
mapped according to their prefix verb. If the method has no known prefix,
POST is used. The rest of the name is mapped to the path of the route
according to the given `method_style`. Note that the prefix word must be
all-lowercase and is delimited by either an upper case character, a
non-alphabetic character, or the end of the string.
The following table lists the mappings from prefix verb to HTTP verb:
$(TABLE
$(TR $(TH HTTP method) $(TH Recognized prefixes))
$(TR $(TD GET) $(TD get, query))
$(TR $(TD PUT) $(TD set, put))
$(TR $(TD POST) $(TD add, create, post))
$(TR $(TD DELETE) $(TD remove, erase, delete))
$(TR $(TD PATCH) $(TD update, patch))
)
If a method has its first parameter named 'id', it will be mapped to ':id/method' and
'id' is expected to be part of the URL instead of a JSON request. Parameters with default
values will be optional in the corresponding JSON request.
Any interface that you return from a getter will be made available with the
base url and its name appended.
Params:
router = The HTTP router on which the interface will be registered
instance = Class instance to use for the REST mapping - Note that TImpl
must either be an interface type, or a class which derives from a
single interface
settings = Additional settings, such as the $(D MethodStyle), or the prefix.
See $(D RestInterfaceSettings) for more details.
See_Also:
$(D RestInterfaceClient) class for a seamless way to access such a generated API
*/
URLRouter registerRestInterface(TImpl)(URLRouter router, TImpl instance, RestInterfaceSettings settings = null)
{
import std.algorithm : filter, map, all;
import std.array : array;
import std.range : front;
import vibe.web.internal.rest.common : ParameterKind;
auto intf = RestInterface!TImpl(settings, false);
foreach (i, ovrld; intf.SubInterfaceFunctions) {
enum fname = __traits(identifier, intf.SubInterfaceFunctions[i]);
alias R = ReturnType!ovrld;
static if (isInstanceOf!(Collection, R)) {
auto ret = __traits(getMember, instance, fname)(R.ParentIDs.init);
router.registerRestInterface!(R.Interface)(ret.m_interface, intf.subInterfaces[i].settings);
} else {
auto ret = __traits(getMember, instance, fname)();
router.registerRestInterface!R(ret, intf.subInterfaces[i].settings);
}
}
foreach (i, func; intf.RouteFunctions) {
auto route = intf.routes[i];
// normal handler
auto handler = jsonMethodHandler!(func, i)(instance, intf);
auto diagparams = route.parameters.filter!(p => p.kind != ParameterKind.internal).map!(p => p.fieldName).array;
logDiagnostic("REST route: %s %s %s", route.method, route.fullPattern, diagparams);
router.match(route.method, route.fullPattern, handler);
}
// here we filter our already existing OPTIONS routes, so we don't overwrite whenever the user explicitly made his own OPTIONS route
auto routesGroupedByPattern = intf.getRoutesGroupedByPattern.filter!(rs => rs.all!(r => r.method != HTTPMethod.OPTIONS));
foreach(routes; routesGroupedByPattern){
auto route = routes.front;
auto handler = optionsMethodHandler(routes, settings);
auto diagparams = route.parameters.filter!(p => p.kind != ParameterKind.internal).map!(p => p.fieldName).array;
logDiagnostic("REST route: %s %s %s", HTTPMethod.OPTIONS, route.fullPattern, diagparams);
router.match(HTTPMethod.OPTIONS, route.fullPattern, handler);
}
return router;
}
/// ditto
URLRouter registerRestInterface(TImpl)(URLRouter router, TImpl instance, MethodStyle style)
{
return registerRestInterface(router, instance, "/", style);
}
/// ditto
URLRouter registerRestInterface(TImpl)(URLRouter router, TImpl instance, string url_prefix,
MethodStyle style = MethodStyle.lowerUnderscored)
{
auto settings = new RestInterfaceSettings;
if (!url_prefix.startsWith("/")) url_prefix = "/"~url_prefix;
settings.baseURL = URL("http://127.0.0.1"~url_prefix);
settings.methodStyle = style;
return registerRestInterface(router, instance, settings);
}
/**
This is a very limited example of REST interface features. Please refer to
the "rest" project in the "examples" folder for a full overview.
All details related to HTTP are inferred from the interface declaration.
*/
@safe unittest
{
@path("/")
interface IMyAPI
{
@safe:
// GET /api/greeting
@property string greeting();
// PUT /api/greeting
@property void greeting(string text);
// POST /api/users
@path("/users")
void addNewUser(string name);
// GET /api/users
@property string[] users();
// GET /api/:id/name
string getName(int id);
// GET /some_custom_json
Json getSomeCustomJson();
}
// vibe.d takes care of all JSON encoding/decoding
// and actual API implementation can work directly
// with native types
class API : IMyAPI
{
private {
string m_greeting;
string[] m_users;
}
@property string greeting() { return m_greeting; }
@property void greeting(string text) { m_greeting = text; }
void addNewUser(string name) { m_users ~= name; }
@property string[] users() { return m_users; }
string getName(int id) { return m_users[id]; }
Json getSomeCustomJson()
{
Json ret = Json.emptyObject;
ret["somefield"] = "Hello, World!";
return ret;
}
}
// actual usage, this is usually done in app.d module
// constructor
void static_this()
{
import vibe.http.server, vibe.http.router;
auto router = new URLRouter;
router.registerRestInterface(new API());
listenHTTP(new HTTPServerSettings(), router);
}
}
/**
Returns a HTTP handler delegate that serves a JavaScript REST client.
*/
HTTPServerRequestDelegate serveRestJSClient(I)(RestInterfaceSettings settings)
if (is(I == interface))
{
import std.digest.md : md5Of;
import std.digest.digest : toHexString;
import std.array : appender;
import vibe.http.server : HTTPServerRequest, HTTPServerResponse;
import vibe.http.status : HTTPStatus;
auto app = appender!string();
generateRestJSClient!I(app, settings);
auto hash = app.data.md5Of.toHexString.idup;
void serve(HTTPServerRequest req, HTTPServerResponse res)
{
if (auto pv = "If-None-Match" in res.headers) {
res.statusCode = HTTPStatus.notModified;
res.writeVoidBody();
return;
}
res.headers["Etag"] = hash;
res.writeBody(app.data, "application/javascript; charset=UTF-8");
}
return &serve;
}
/// ditto
HTTPServerRequestDelegate serveRestJSClient(I)(URL base_url)
{
auto settings = new RestInterfaceSettings;
settings.baseURL = base_url;
return serveRestJSClient!I(settings);
}
/// ditto
HTTPServerRequestDelegate serveRestJSClient(I)(string base_url)
{
auto settings = new RestInterfaceSettings;
settings.baseURL = URL(base_url);
return serveRestJSClient!I(settings);
}
///
unittest {
import vibe.http.server;
interface MyAPI {
string getFoo();
void postBar(string param);
}
void test()
{
auto restsettings = new RestInterfaceSettings;
restsettings.baseURL = URL("http://api.example.org/");
auto router = new URLRouter;
router.get("/myapi.js", serveRestJSClient!MyAPI(restsettings));
//router.get("/myapi.js", serveRestJSClient!MyAPI(URL("http://api.example.org/")));
//router.get("/myapi.js", serveRestJSClient!MyAPI("http://api.example.org/"));
//router.get("/", staticTemplate!"index.dt");
listenHTTP(new HTTPServerSettings, router);
}
/*
index.dt:
html
head
title JS REST client test
script(src="myapi.js")
body
button(onclick="MyAPI.postBar('hello');")
*/
}
/**
Generates JavaScript code to access a REST interface from the browser.
*/
void generateRestJSClient(I, R)(ref R output, RestInterfaceSettings settings = null)
if (is(I == interface) && isOutputRange!(R, char))
{
import vibe.web.internal.rest.jsclient : generateInterface, JSRestClientSettings;
auto jsgenset = new JSRestClientSettings;
output.generateInterface!I(settings, jsgenset, true);
}
/// Writes a JavaScript REST client to a local .js file.
unittest {
import vibe.core.file;
interface MyAPI {
void getFoo();
void postBar(string param);
}
void generateJSClientImpl()
{
import std.array : appender;
auto app = appender!string;
auto settings = new RestInterfaceSettings;
settings.baseURL = URL("http://localhost/");
generateRestJSClient!MyAPI(app, settings);
}
generateJSClientImpl();
}
/**
Implements the given interface by forwarding all public methods to a REST server.
The server must talk the same protocol as registerRestInterface() generates. Be sure to set
the matching method style for this. The RestInterfaceClient class will derive from the
interface that is passed as a template argument. It can be used as a drop-in replacement
of the real implementation of the API this way.
*/
class RestInterfaceClient(I) : I
{
import vibe.inet.url : URL, PathEntry;
import vibe.http.client : HTTPClientRequest;
import std.typetuple : staticMap;
private alias Info = RestInterface!I;
//pragma(msg, "imports for "~I.stringof~":");
//pragma(msg, generateModuleImports!(I)());
mixin(generateModuleImports!I());
private {
// storing this struct directly causes a segfault when built with
// LDC 0.15.x, so we are using a pointer here:
RestInterface!I* m_intf;
RequestFilter m_requestFilter;
staticMap!(RestInterfaceClient, Info.SubInterfaceTypes) m_subInterfaces;
}
alias RequestFilter = void delegate(HTTPClientRequest req);
/**
Creates a new REST client implementation of $(D I).
*/
this(RestInterfaceSettings settings)
{
m_intf = new Info(settings, true);
foreach (i, SI; Info.SubInterfaceTypes)
m_subInterfaces[i] = new RestInterfaceClient!SI(m_intf.subInterfaces[i].settings);
}
/// ditto
this(string base_url, MethodStyle style = MethodStyle.lowerUnderscored)
{
this(URL(base_url), style);
}
/// ditto
this(URL base_url, MethodStyle style = MethodStyle.lowerUnderscored)
{
scope settings = new RestInterfaceSettings;
settings.baseURL = base_url;
settings.methodStyle = style;
this(settings);
}
/**
An optional request filter that allows to modify each request before it is made.
*/
final @property RequestFilter requestFilter()
{
return m_requestFilter;
}
/// ditto
final @property void requestFilter(RequestFilter v)
{
m_requestFilter = v;
foreach (i, SI; Info.SubInterfaceTypes)
m_subInterfaces[i].requestFilter = v;
}
//pragma(msg, "restinterface:");
mixin(generateRestClientMethods!I());
protected {
import vibe.data.json : Json;
import vibe.textfilter.urlencode;
/**
* Perform a request to the interface using the given parameters.
*
* Params:
* verb = Kind of request (See $(D HTTPMethod) enum).
* name = Location to request. For a request on https://github.com/rejectedsoftware/vibe.d/issues?q=author%3ASantaClaus,
* it will be '/rejectedsoftware/vibe.d/issues'.
* hdrs = The headers to send. Some field might be overriden (such as Content-Length). However, Content-Type will NOT be overriden.
* query = The $(B encoded) query string. For a request on https://github.com/rejectedsoftware/vibe.d/issues?q=author%3ASantaClaus,
* it will be 'author%3ASantaClaus'.
* body_ = The body to send, as a string. If a Content-Type is present in $(D hdrs), it will be used, otherwise it will default to
* the generic type "application/json".
* reqReturnHdrs = A map of required return headers.
* To avoid returning unused headers, nothing is written
* to this structure unless there's an (usually empty)
* entry (= the key exists) with the same key.
* If any key present in `reqReturnHdrs` is not present
* in the response, an Exception is thrown.
* optReturnHdrs = A map of optional return headers.
* This behaves almost as exactly as reqReturnHdrs,
* except that non-existent key in the response will
* not cause it to throw, but rather to set this entry
* to 'null'.
*
* Returns:
* The Json object returned by the request
*/
Json request(HTTPMethod verb, string name,
in ref InetHeaderMap hdrs, string query, string body_,
ref InetHeaderMap reqReturnHdrs,
ref InetHeaderMap optReturnHdrs) const
{
auto path = URL(m_intf.baseURL).pathString;
if (name.length)
{
if (path.length && path[$ - 1] == '/' && name[0] == '/')
path ~= name[1 .. $];
else if (path.length && path[$ - 1] == '/' || name[0] == '/')
path ~= name;
else
path ~= '/' ~ name;
}
auto httpsettings = m_intf.settings.httpClientSettings;
return .request(URL(m_intf.baseURL), m_requestFilter, verb, path,
hdrs, query, body_, reqReturnHdrs, optReturnHdrs, httpsettings);
}
}
}
///
unittest
{
interface IMyApi
{
// GET /status
string getStatus();
// GET /greeting
@property string greeting();
// PUT /greeting
@property void greeting(string text);
// POST /new_user
void addNewUser(string name);
// GET /users
@property string[] users();
// GET /:id/name
string getName(int id);
Json getSomeCustomJson();
}
void test()
{
auto api = new RestInterfaceClient!IMyApi("http://127.0.0.1/api/");
logInfo("Status: %s", api.getStatus());
api.greeting = "Hello, World!";
logInfo("Greeting message: %s", api.greeting);
api.addNewUser("Peter");
api.addNewUser("Igor");
logInfo("Users: %s", api.users);
logInfo("First user name: %s", api.getName(0));
}
}
/**
Encapsulates settings used to customize the generated REST interface.
*/
class RestInterfaceSettings {
/** The public URL below which the REST interface is registered.
*/
URL baseURL;
/** List of allowed origins for CORS
Empty list is interpreted as allowing all origins (e.g. *)
*/
string[] allowedOrigins;
/** Naming convention used for the generated URLs.
*/
MethodStyle methodStyle = MethodStyle.lowerUnderscored;
/** Ignores a trailing underscore in method and function names.
With this setting set to $(D true), it's possible to use names in the
REST interface that are reserved words in D.
*/
bool stripTrailingUnderscore = true;
/// Overrides the default HTTP client settings used by the `RestInterfaceClient`.
HTTPClientSettings httpClientSettings;
@property RestInterfaceSettings dup()
const @safe {
auto ret = new RestInterfaceSettings;
ret.baseURL = this.baseURL;
ret.methodStyle = this.methodStyle;
ret.stripTrailingUnderscore = this.stripTrailingUnderscore;
ret.allowedOrigins = this.allowedOrigins.dup;
return ret;
}
}
/**
Models REST collection interfaces using natural D syntax.
Use this type as the return value of a REST interface getter method/property
to model a collection of objects. `opIndex` is used to make the individual
entries accessible using the `[index]` syntax. Nested collections are
supported.
The interface `I` needs to define a struct named `CollectionIndices`. The
members of this struct denote the types and names of the indexes that lead
to a particular resource. If a collection is nested within another
collection, the order of these members must match the nesting order
(outermost first).
The parameter list of all of `I`'s methods must begin with all but the last
entry in `CollectionIndices`. Methods that also match the last entry will be
considered methods of a collection item (`collection[index].method()`),
wheres all other methods will be considered methods of the collection
itself (`collection.method()`).
The name of the index parameters affects the default path of a method's
route. Normal parameter names will be subject to the same rules as usual
routes (see `registerRestInterface`) and will be mapped to query or form
parameters at the protocol level. Names starting with an underscore will
instead be mapped to path placeholders. For example,
`void getName(int __item_id)` will be mapped to a GET request to the
path `":item_id/name"`.
*/
struct Collection(I)
if (is(I == interface))
{
import std.typetuple;
static assert(is(I.CollectionIndices == struct), "Collection interfaces must define a CollectionIndices struct.");
alias Interface = I;
alias AllIDs = TypeTuple!(typeof(I.CollectionIndices.tupleof));
alias AllIDNames = FieldNameTuple!(I.CollectionIndices);
static assert(AllIDs.length >= 1, I.stringof~".CollectionIndices must define at least one member.");
static assert(AllIDNames.length == AllIDs.length);
alias ItemID = AllIDs[$-1];
alias ParentIDs = AllIDs[0 .. $-1];
alias ParentIDNames = AllIDNames[0 .. $-1];
private {
I m_interface;
ParentIDs m_parentIDs;
}
/** Constructs a new collection instance that is tied to a particular
parent collection entry.
Params:
api = The target interface imstance to be mapped as a collection
pids = The indexes of all collections in which this collection is
nested (if any)
*/
this(I api, ParentIDs pids)
{
m_interface = api;
m_parentIDs = pids;
}
static struct Item {
private {
I m_interface;
AllIDs m_id;
}
this(I api, AllIDs id)
{
m_interface = api;
m_id = id;
}
// forward all item methods
mixin(() {
string ret;
foreach (m; __traits(allMembers, I)) {
foreach (ovrld; MemberFunctionsTuple!(I, m)) {
alias PT = ParameterTypeTuple!ovrld;
static if (matchesAllIDs!ovrld)
ret ~= "auto "~m~"(ARGS...)(ARGS args) { return m_interface."~m~"(m_id, args); }\n";
}
}
return ret;
} ());
}
// Note: the example causes a recursive template instantiation if done as a documented unit test:
/** Accesses a single collection entry.
Example:
---
interface IMain {
@property Collection!IItem items();
}
interface IItem {
struct CollectionIndices {
int _itemID;
}
@method(HTTPMethod.GET)
string name(int _itemID);
}
void test(IMain main)
{
auto item_name = main.items[23].name; // equivalent to IItem.name(23)
}
---
*/
Item opIndex(ItemID id)
{
return Item(m_interface, m_parentIDs, id);
}
// forward all non-item methods
mixin(() {
string ret;
foreach (m; __traits(allMembers, I)) {
foreach (ovrld; MemberFunctionsTuple!(I, m)) {
alias PT = ParameterTypeTuple!ovrld;
static if (!matchesAllIDs!ovrld) {
static assert(matchesParentIDs!ovrld,
"Collection methods must take all parent IDs as the first parameters."~PT.stringof~" "~ParentIDs.stringof);
ret ~= "auto "~m~"(ARGS...)(ARGS args) { return m_interface."~m~"(m_parentIDs, args); }\n";
}
}
}
return ret;
} ());
private template matchesParentIDs(alias func) {
static if (is(ParameterTypeTuple!func[0 .. ParentIDs.length] == ParentIDs)) {
static if (ParentIDNames.length == 0) enum matchesParentIDs = true;
else static if (ParameterIdentifierTuple!func[0 .. ParentIDNames.length] == ParentIDNames)
enum matchesParentIDs = true;
else enum matchesParentIDs = false;
} else enum matchesParentIDs = false;
}
private template matchesAllIDs(alias func) {
static if (is(ParameterTypeTuple!func[0 .. AllIDs.length] == AllIDs)) {
static if (ParameterIdentifierTuple!func[0 .. AllIDNames.length] == AllIDNames)
enum matchesAllIDs = true;
else enum matchesAllIDs = false;
} else enum matchesAllIDs = false;
}
}
/// Model two nested collections using path based indexes
unittest {
//
// API definition
//
interface SubItemAPI {
// Define the index path that leads to a sub item
struct CollectionIndices {
// The ID of the base item. This must match the definition in
// ItemAPI.CollectionIndices
string _item;
// The index if the sub item
int _index;
}
// GET /items/:item/subItems/length
@property int length(string _item);
// GET /items/:item/subItems/:index/squared_position
int getSquaredPosition(string _item, int _index);
}
interface ItemAPI {
// Define the index that identifies an item
struct CollectionIndices {
string _item;
}
// base path /items/:item/subItems
Collection!SubItemAPI subItems(string _item);
// GET /items/:item/name
@property string name(string _item);
}
interface API {
// a collection of items at the base path /items/
Collection!ItemAPI items();
}
//
// Local API implementation
//
class SubItemAPIImpl : SubItemAPI {
@property int length(string _item) { return 10; }
int getSquaredPosition(string _item, int _index) { return _index ^^ 2; }
}
class ItemAPIImpl : ItemAPI {
private SubItemAPIImpl m_subItems;
this() { m_subItems = new SubItemAPIImpl; }
Collection!SubItemAPI subItems(string _item) { return Collection!SubItemAPI(m_subItems, _item); }
string name(string _item) { return _item; }
}
class APIImpl : API {
private ItemAPIImpl m_items;
this() { m_items = new ItemAPIImpl; }
Collection!ItemAPI items() { return Collection!ItemAPI(m_items); }
}
//
// Resulting API usage
//
API api = new APIImpl; // A RestInterfaceClient!API would work just as well
assert(api.items["foo"].name == "foo");
assert(api.items["foo"].subItems.length == 10);
assert(api.items["foo"].subItems[2].getSquaredPosition() == 4);
}
unittest {
interface I {
struct CollectionIndices {
int id1;
string id2;
}
void a(int id1, string id2);
void b(int id1, int id2);
void c(int id1, string p);
void d(int id1, string id2, int p);
void e(int id1, int id2, int p);
void f(int id1, string p, int q);
}
Collection!I coll;
static assert(is(typeof(coll["x"].a()) == void));
static assert(is(typeof(coll.b(42)) == void));
static assert(is(typeof(coll.c("foo")) == void));
static assert(is(typeof(coll["x"].d(42)) == void));
static assert(is(typeof(coll.e(42, 42)) == void));
static assert(is(typeof(coll.f("foo", 42)) == void));
}
/// Model two nested collections using normal query parameters as indexes
unittest {
//
// API definition
//
interface SubItemAPI {
// Define the index path that leads to a sub item
struct CollectionIndices {
// The ID of the base item. This must match the definition in
// ItemAPI.CollectionIndices
string item;
// The index if the sub item
int index;
}
// GET /items/subItems/length?item=...
@property int length(string item);
// GET /items/subItems/squared_position?item=...&index=...
int getSquaredPosition(string item, int index);
}
interface ItemAPI {
// Define the index that identifies an item
struct CollectionIndices {
string item;
}
// base path /items/subItems?item=...
Collection!SubItemAPI subItems(string item);
// GET /items/name?item=...
@property string name(string item);
}
interface API {
// a collection of items at the base path /items/
Collection!ItemAPI items();
}
//
// Local API implementation
//
class SubItemAPIImpl : SubItemAPI {
@property int length(string item) { return 10; }
int getSquaredPosition(string item, int index) { return index ^^ 2; }
}
class ItemAPIImpl : ItemAPI {
private SubItemAPIImpl m_subItems;
this() { m_subItems = new SubItemAPIImpl; }
Collection!SubItemAPI subItems(string item) { return Collection!SubItemAPI(m_subItems, item); }
string name(string item) { return item; }
}
class APIImpl : API {
private ItemAPIImpl m_items;
this() { m_items = new ItemAPIImpl; }
Collection!ItemAPI items() { return Collection!ItemAPI(m_items); }
}
//
// Resulting API usage
//
API api = new APIImpl; // A RestInterfaceClient!API would work just as well
assert(api.items["foo"].name == "foo");
assert(api.items["foo"].subItems.length == 10);
assert(api.items["foo"].subItems[2].getSquaredPosition() == 4);
}
unittest {
interface C {
struct CollectionIndices {
int _ax;
int _b;
}
void testB(int _ax, int _b);
}
interface B {
struct CollectionIndices {
int _a;
}
Collection!C c();
void testA(int _a);
}
interface A {
Collection!B b();
}
static assert (!is(typeof(A.init.b[1].c[2].testB())));
}
/** Allows processing the server request/response before the handler method is called.
Note that this attribute is only used by `registerRestInterface`, but not
by the client generators. This attribute expects the name of a parameter that
will receive its return value.
Writing to the response body from within the specified hander function
causes any further processing of the request to be skipped. In particular,
the route handler method will not be called.
Note:
The example shows the drawback of this attribute. It generally is a
leaky abstraction that propagates to the base interface. For this
reason the use of this attribute is not recommended, unless there is
no suitable alternative.
*/
alias before = vibe.internal.meta.funcattr.before;
///
unittest {
import vibe.http.server : HTTPServerRequest, HTTPServerResponse;
interface MyService {
long getHeaderCount(size_t foo = 0);
}
size_t handler(HTTPServerRequest req, HTTPServerResponse res)
{
return req.headers.length;
}
class MyServiceImpl : MyService {
// the "foo" parameter will receive the number of request headers
@before!handler("foo")
long getHeaderCount(size_t foo)
{
return foo;
}
}
void test(URLRouter router)
{
router.registerRestInterface(new MyServiceImpl);
}
}
/** Allows processing the return value of a handler method and the request/response objects.
The value returned by the REST API will be the value returned by the last
`@after` handler, which allows to post process the results of the handler
method.
Writing to the response body from within the specified handler function
causes any further processing of the request ot be skipped, including
any other `@after` annotations and writing the result value.
*/
alias after = vibe.internal.meta.funcattr.after;
///
unittest {
import vibe.http.server : HTTPServerRequest, HTTPServerResponse;
interface MyService {
long getMagic();
}
long handler(long ret, HTTPServerRequest req, HTTPServerResponse res)
{
return ret * 2;
}
class MyServiceImpl : MyService{
// the result reported by the REST API will be 42
@after!handler
long getMagic()
{
return 21;
}
}
void test(URLRouter router)
{
router.registerRestInterface(new MyServiceImpl);
}
}
/**
* Generate an handler that will wrap the server's method
*
* This function returns an handler, generated at compile time, that
* will deserialize the parameters, pass them to the function implemented
* by the user, and return what it needs to return, be it header parameters
* or body, which is at the moment either a pure string or a Json object.
*
* One thing that makes this method more complex that it needs be is the
* inability for D to attach UDA to parameters. This means we have to roll
* our own implementation, which tries to be as easy to use as possible.
* We'll require the user to give the name of the parameter as a string to
* our UDA. Hopefully, we're also able to detect at compile time if the user
* made a typo of any kind (see $(D genInterfaceValidationError)).
*
* Note:
* Lots of abbreviations are used to ease the code, such as
* PTT (ParameterTypeTuple), WPAT (WebParamAttributeTuple)
* and PWPAT (ParameterWebParamAttributeTuple).
*
* Params:
* T = type of the object which represent the REST server (user implemented).
* Func = An alias to the function of $(D T) to wrap.
*
* inst = REST server on which to call our $(D Func).
* settings = REST server configuration.
*