platform/lib/angel_mongo.dart

93 lines
2.5 KiB
Dart
Raw Normal View History

2016-05-09 22:51:07 +00:00
library angel_mongo;
2016-06-22 18:34:28 +00:00
2016-05-09 22:51:07 +00:00
import 'dart:async';
2016-06-22 18:34:28 +00:00
import 'dart:mirrors';
2016-05-09 22:51:07 +00:00
import 'package:angel_framework/angel_framework.dart';
2016-06-22 18:34:28 +00:00
import 'package:json_god/json_god.dart' as god;
2016-05-09 22:51:07 +00:00
import 'package:merge_map/merge_map.dart';
import 'package:mongo_dart/mongo_dart.dart';
part 'mongo_service.dart';
2016-06-22 18:34:28 +00:00
part 'mongo_service_typed.dart';
/// A data type that can be serialized to MongoDB.
class Model {
/// This instance's ID.
String id;
/// The time at which this instance was created.
DateTime createdAt;
/// The time at which this instance was last updated.
DateTime updatedAt;
}
Map _transformId(Map doc) {
Map result = mergeMap([doc]);
result['id'] = doc['_id'];
return result..remove('_id');
}
_lastItem(DbCollection collection, Function _jsonify, [Map params]) async {
return (await (await collection
2016-06-23 04:58:21 +00:00
.find(where.sortBy('\$natural', descending: true)))
.toList())
2016-06-22 18:34:28 +00:00
.map((x) => _jsonify(x, params))
.first;
}
ObjectId _makeId(id) {
try {
return (id is ObjectId) ? id : new ObjectId.fromHexString(id.toString());
} catch (e) {
throw new AngelHttpException.BadRequest();
}
}
Map _removeSensitive(Map data) {
2016-06-23 04:58:21 +00:00
return data
..remove('id')
..remove('_id')
..remove('createdAt')
..remove('updatedAt');
2016-06-22 18:34:28 +00:00
}
SelectorBuilder _makeQuery([Map params_]) {
Map params = params_ ?? {};
params = params..remove('provider');
SelectorBuilder result = where.exists('_id');
// You can pass a SelectorBuilder as 'query';
2016-06-23 19:59:10 +00:00
if (params['query'] != null && params['query'] is SelectorBuilder) {
2016-06-22 18:34:28 +00:00
return params['query'];
2016-06-23 19:59:10 +00:00
}
2016-06-22 18:34:28 +00:00
for (var key in params.keys) {
2016-06-23 19:59:10 +00:00
if (key == r'$sort' || key == r'$query') {
2016-06-22 18:34:28 +00:00
if (params[key] is Map) {
// If they send a map, then we'll sort by every key in the map
for (String fieldName in params[key].keys.where((x) => x is String)) {
var sorter = params[key][fieldName];
if (sorter is num) {
result = result.sortBy(fieldName, descending: sorter == -1);
} else if (sorter is String) {
result = result.sortBy(fieldName, descending: sorter == "-1");
2016-06-23 19:59:10 +00:00
} else if (sorter is SelectorBuilder) {
result = result.and(sorter);
2016-06-22 18:34:28 +00:00
}
}
2016-06-23 19:59:10 +00:00
} else if (params[key] is String && key == r'$sort') {
2016-06-22 18:34:28 +00:00
// If they send just a string, then we'll sort
// by that, ascending
result = result.sortBy(params[key]);
}
} else if (key is String) {
result = result.and(where.eq(key, params[key]));
}
}
return result;
}