1 module vibedstruct2mongo;
2 
3 class MongoDBConnection {
4     import vibe.d;
5     import vibe.core.connectionpool;
6 
7     import mondo : Mongo;
8     ConnectionPool!Mongo connections;
9     private string connectionString;
10 
11     auto connectionFactory () {
12         return new Mongo(this.connectionString);
13     }
14 
15     this (string connectionString, uint maxConnections) {
16         this.connectionString = connectionString;
17 
18         this.connections = new ConnectionPool!Mongo (
19             &connectionFactory, maxConnections
20         );
21     }
22     auto opIndex (string collection) {
23         return connections.lockConnection [collection];
24     }
25 
26     import std.traits : MemberFunctionsTuple;
27     auto opDispatch (string fun, Args ...)(Args args) 
28         if (MemberFunctionsTuple!(Mongo, fun).length) {
29             auto conn = connections.lockConnection ();
30             enum called = `conn.` ~ fun ~ ` (args)`;
31             static if (__traits (compiles, mixin (called))) {
32                 import std.traits : ReturnType;
33                 static if (is (ReturnType!(mixin (called)) == void)) {
34                     // Doesn't return.
35                     mixin (called);
36                 } else { // Returns.
37                     return mixin (called);
38                 }
39             } else {
40                 static assert (0, `Don't know what to do.`);
41             }
42         }
43 }
44 
45 unittest {
46     auto pool = new MongoDBConnection ("mongodb://localhost", 10);
47     import struct2mongo;
48     assert (pool.connected, `Not connected to Mongo.`);
49     auto col = Col (pool [`newBase`][`newCollection`]);
50     if (col.exists) col.drop;
51     struct Example {
52         int a = 0;
53     }
54     col.insert (Example (5));
55 }