1
1
module mongoschema ;
2
2
3
3
import core.time ;
4
+ import std.array : appender;
5
+ import std.conv ;
4
6
import std.traits ;
5
7
import std.typecons : BitFlags, isTuple;
6
8
public import vibe.data.bson;
@@ -172,19 +174,33 @@ T bsonToMember(T)(auto ref T member, Bson value)
172
174
auto bsons = value.get ! (Bson[]);
173
175
T values ;
174
176
foreach (i, val; values )
175
- {
176
177
values [i] = bsonToMember! (typeof (val))(values [i], bsons[i]);
177
- }
178
178
return values ;
179
179
}
180
- else static if (isArray! T && ! isSomeString! T)
180
+ else static if (isDynamicArray! T && ! isSomeString! T)
181
+ { // Arrays of anything except strings
182
+ alias Type = typeof (member[0 ]);
183
+ if (value.type != Bson.Type.array)
184
+ throw new Exception (" Cannot convert from BSON type " ~ value.type.to! string ~ " to array" );
185
+ auto arr = value.get ! (Bson[]);
186
+ auto ret = appender! T();
187
+ ret.reserve (arr.length);
188
+ foreach (val; arr)
189
+ ret.put(bsonToMember! Type(Type.init, val));
190
+ return ret.data;
191
+ }
192
+ else static if (isStaticArray! T)
181
193
{ // Arrays of anything except strings
182
194
alias Type = typeof (member[0 ]);
183
195
T values ;
184
- foreach (val; value)
185
- {
186
- values ~= bsonToMember! Type(Type.init, val);
187
- }
196
+ if (value.type != Bson.Type.array)
197
+ throw new Exception (" Cannot convert from BSON type " ~ value.type.to! string ~ " to array" );
198
+ auto arr = value.get ! (Bson[]);
199
+ if (arr.length != values .length)
200
+ throw new Exception (" Cannot convert from BSON array of length "
201
+ ~ arr.length.to! string ~ " to array of length " ~ arr.length.to! string );
202
+ foreach (i, val; arr)
203
+ values [i] = bsonToMember! Type(Type.init, val);
188
204
return values ;
189
205
}
190
206
else static if (isAssociativeArray! T)
@@ -200,13 +216,20 @@ T bsonToMember(T)(auto ref T member, Bson value)
200
216
{ // Already a Bson object
201
217
return value;
202
218
}
219
+ else static if (isNumeric! T)
220
+ {
221
+ if (value.type == Bson.Type.int_)
222
+ return cast (T) value.get ! int ;
223
+ else if (value.type == Bson.Type.long_)
224
+ return cast (T) value.get ! long ;
225
+ else if (value.type == Bson.Type.double_)
226
+ return cast (T) value.get ! double ;
227
+ else
228
+ throw new Exception (
229
+ " Cannot convert BSON from type " ~ value.type.to! string ~ " to " ~ T.stringof);
230
+ }
203
231
else static if (__traits(compiles, { value.get ! T(); }))
204
- { // Check if this can be passed
205
- static if (is (T == long ))
206
- { // If the output expects a long, but the data is a int, do .get!int
207
- if (value.type == Bson.Type.int_)
208
- return value.get ! int ();
209
- }
232
+ {
210
233
return value.get ! T();
211
234
}
212
235
else static if (! isBasicType! T)
0 commit comments