Published mongo

This commit is contained in:
thomashii 2021-06-18 19:10:38 +08:00
parent bba3948a2b
commit 3adf9d62bc
8 changed files with 98 additions and 105 deletions

View file

@ -1,16 +1,18 @@
# angel_mongo
# angel3_mongo
[![version](https://img.shields.io/badge/pub-v3.0.0-brightgreen)](https://pub.dartlang.org/packages/angel3_mongo)
[![Null Safety](https://img.shields.io/badge/null-safety-brightgreen)](https://dart.dev/null-safety)
[![Gitter](https://img.shields.io/gitter/room/angel_dart/discussion)](https://gitter.im/angel_dart/discussion)
[![Pub](https://img.shields.io/pub/v/angel_mongo.svg)](https://pub.dartlang.org/packages/angel_mongo)
[![build status](https://travis-ci.org/angel-dart/mongo.svg)](https://travis-ci.org/angel-dart/mongo)
[![License](https://img.shields.io/github/license/dukefirehawk/angel)](https://github.com/dukefirehawk/angel/tree/angel3/packages/mongo/LICENSE)
MongoDB-enabled services for the Angel framework.
MongoDB-enabled services for the Angel3 framework.
# Installation
Add the following to your `pubspec.yaml`:
```yaml
dependencies:
angel_mongo: ^2.0.0
angel3_mongo: ^3.0.0
```
# Usage
@ -26,11 +28,11 @@ class User extends Model {
String password;
}
main() async {
var db = new Db('mongodb://localhost:27017/local');
void main() async {
var db = Db('mongodb://localhost:27017/local');
await db.open();
var service = app.use('/api/users', new MongoService(db.collection("users")));
var service = app.use('/api/users', MongoService(db.collection("users")));
service.afterCreated.listen((event) {
print("New user: ${event.result}");

View file

@ -1,5 +1,5 @@
import 'package:angel_framework/angel_framework.dart';
import 'package:angel_mongo/angel_mongo.dart';
import 'package:angel3_framework/angel3_framework.dart';
import 'package:angel3_mongo/angel3_mongo.dart';
import 'package:mongo_dart/mongo_dart.dart';
void main() async {

View file

@ -1,3 +1,3 @@
library angel_mongo;
library angel3_mongo;
export 'services.dart';

View file

@ -1,14 +1,14 @@
library angel_mongo.model;
library angel3_mongo.model;
/// Use the `Model` class defined in `package:angel_framework/common.dart` instead.
@deprecated
class Model {
/// This instance's ID.
String id;
String? id;
/// The time at which this instance was created.
DateTime createdAt;
DateTime? createdAt;
/// The time at which this instance was last updated.
DateTime updatedAt;
DateTime? updatedAt;
}

View file

@ -1,4 +1,4 @@
part of angel_mongo.services;
part of angel3_mongo.services;
/// Manipulates data from MongoDB as Maps.
class MongoService extends Service<String, Map<String, dynamic>> {
@ -20,14 +20,14 @@ class MongoService extends Service<String, Map<String, dynamic>> {
{this.allowRemoveAll = false, this.allowQuery = true, this.debug = true})
: super();
SelectorBuilder _makeQuery([Map<String, dynamic> params_]) {
SelectorBuilder? _makeQuery([Map<String, dynamic>? params_]) {
var params = Map.from(params_ ?? {});
params = params..remove('provider');
var result = where.exists('_id');
// You can pass a SelectorBuilder as 'query';
if (params['query'] is SelectorBuilder) {
return params['query'] as SelectorBuilder;
return params['query'] as SelectorBuilder?;
}
for (var key in params.keys) {
@ -54,7 +54,7 @@ class MongoService extends Service<String, Map<String, dynamic>> {
}
} else if (key == 'query' &&
(allowQuery == true || !params.containsKey('provider'))) {
var query = params[key] as Map;
var query = params[key] as Map?;
query?.forEach((key, v) {
var value = v is Map<String, dynamic> ? _filterNoQuery(v) : v;
@ -71,7 +71,7 @@ class MongoService extends Service<String, Map<String, dynamic>> {
}
Map<String, dynamic> _jsonify(Map<String, dynamic> doc,
[Map<String, dynamic> params]) {
[Map<String, dynamic>? params]) {
var result = <String, dynamic>{};
for (var key in doc.keys) {
@ -88,7 +88,7 @@ class MongoService extends Service<String, Map<String, dynamic>> {
@override
Future<List<Map<String, dynamic>>> index(
[Map<String, dynamic> params]) async {
[Map<String, dynamic>? params]) async {
return await (collection.find(_makeQuery(params)))
.map((x) => _jsonify(x, params))
.toList();
@ -98,16 +98,16 @@ class MongoService extends Service<String, Map<String, dynamic>> {
@override
Future<Map<String, dynamic>> create(Map<String, dynamic> data,
[Map<String, dynamic> params]) async {
[Map<String, dynamic>? params]) async {
var item = _removeSensitive(data);
try {
var nonce = (await collection.db.getNonce())['nonce'] as String;
var result = await collection.findAndModify(
var nonce = (await collection.db.getNonce())['nonce'] as String?;
var result = await (collection.findAndModify(
query: where.eq(_NONCE_KEY, nonce),
update: item,
returnNew: true,
upsert: true);
upsert: true) as FutureOr<Map<String, dynamic>>);
return _jsonify(result);
} catch (e, st) {
throw AngelHttpException(e, stackTrace: st);
@ -116,7 +116,7 @@ class MongoService extends Service<String, Map<String, dynamic>> {
@override
Future<Map<String, dynamic>> findOne(
[Map<String, dynamic> params,
[Map<String, dynamic>? params,
String errorMessage =
'No record was found matching the given query.']) async {
var found = await collection.findOne(_makeQuery(params));
@ -130,9 +130,10 @@ class MongoService extends Service<String, Map<String, dynamic>> {
@override
Future<Map<String, dynamic>> read(String id,
[Map<String, dynamic> params]) async {
[Map<String, dynamic>? params]) async {
var _id = _makeId(id);
var found = await collection.findOne(where.id(_id).and(_makeQuery(params)));
var found =
await collection.findOne(where.id(_id).and(_makeQuery(params)!));
if (found == null) {
throw AngelHttpException.notFound(
@ -144,15 +145,15 @@ class MongoService extends Service<String, Map<String, dynamic>> {
@override
Future<List<Map<String, dynamic>>> readMany(List<String> ids,
[Map<String, dynamic> params]) async {
[Map<String, dynamic>? params]) async {
var q = _makeQuery(params);
q = ids.fold(q, (q, id) => q.or(where.id(_makeId(id))));
q = ids.fold(q, (q, id) => q!.or(where.id(_makeId(id))));
return await (collection.find(q)).map((x) => _jsonify(x, params)).toList();
}
@override
Future<Map<String, dynamic>> modify(String id, data,
[Map<String, dynamic> params]) async {
[Map<String, dynamic>? params]) async {
Map<String, dynamic> target;
try {
@ -169,8 +170,10 @@ class MongoService extends Service<String, Map<String, dynamic>> {
//result['updatedAt'] = new DateTime.now().toIso8601String();
try {
var modified = await collection.findAndModify(
query: where.id(_makeId(id)), update: result, returnNew: true);
var modified = await (collection.findAndModify(
query: where.id(_makeId(id)),
update: result,
returnNew: true) as FutureOr<Map<String, dynamic>>);
result = _jsonify(modified, params);
result['id'] = _makeId(id).toHexString();
return result;
@ -182,7 +185,7 @@ class MongoService extends Service<String, Map<String, dynamic>> {
@override
Future<Map<String, dynamic>> update(String id, Map<String, dynamic> data,
[Map<String, dynamic> params]) async {
[Map<String, dynamic>? params]) async {
var result = _removeSensitive(data);
result['_id'] = _makeId(id);
/*result['createdAt'] =
@ -194,11 +197,11 @@ class MongoService extends Service<String, Map<String, dynamic>> {
result['updatedAt'] = new DateTime.now().toIso8601String();*/
try {
var updated = await collection.findAndModify(
var updated = await (collection.findAndModify(
query: where.id(_makeId(id)),
update: result,
returnNew: true,
upsert: true);
upsert: true) as FutureOr<Map<String, dynamic>>);
result = _jsonify(updated, params);
result['id'] = _makeId(id).toHexString();
return result;
@ -210,8 +213,8 @@ class MongoService extends Service<String, Map<String, dynamic>> {
@override
Future<Map<String, dynamic>> remove(String id,
[Map<String, dynamic> params]) async {
if (id == null || id == 'null') {
[Map<String, dynamic>? params]) async {
if (id == 'null') {
// Remove everything...
if (!(allowRemoveAll == true ||
params?.containsKey('provider') != true)) {
@ -226,8 +229,9 @@ class MongoService extends Service<String, Map<String, dynamic>> {
// var result = await read(id, params);
try {
var result = await collection.findAndModify(
query: where.id(_makeId(id)), remove: true);
var result = await (collection.findAndModify(
query: where.id(_makeId(id)),
remove: true) as FutureOr<Map<String, dynamic>>);
return _jsonify(result);
} catch (e, st) {
//printDebug(e, st, 'REMOVE');

View file

@ -1,14 +1,14 @@
library angel_mongo.services;
library angel3_mongo.services;
import 'dart:async';
import 'package:angel_framework/angel_framework.dart';
import 'package:merge_map/merge_map.dart';
import 'package:angel3_framework/angel3_framework.dart';
import 'package:angel3_merge_map/angel3_merge_map.dart';
import 'package:mongo_dart/mongo_dart.dart';
part 'mongo_service.dart';
Map<String, dynamic> _transformId(Map<String, dynamic> doc) {
var result = new Map<String, dynamic>.from(doc);
var result = Map<String, dynamic>.from(doc);
result
..['id'] = doc['_id']
..remove('_id');
@ -18,13 +18,13 @@ Map<String, dynamic> _transformId(Map<String, dynamic> doc) {
ObjectId _makeId(id) {
try {
return (id is ObjectId) ? id : new ObjectId.fromHexString(id.toString());
return (id is ObjectId) ? id : ObjectId.fromHexString(id.toString());
} catch (e) {
throw new AngelHttpException.badRequest();
throw AngelHttpException.badRequest();
}
}
const List<String> _sensitiveFieldNames = const [
const List<String> _sensitiveFieldNames = [
'id',
'_id',
'createdAt',
@ -37,7 +37,7 @@ Map<String, dynamic> _removeSensitive(Map<String, dynamic> data) {
.fold({}, (map, key) => map..[key] = data[key]);
}
const List<String> _NO_QUERY = const ['__requestctx', '__responsectx'];
const List<String> _NO_QUERY = ['__requestctx', '__responsectx'];
Map<String, dynamic> _filterNoQuery(Map<String, dynamic> data) {
return data.keys.fold({}, (map, key) {

View file

@ -1,28 +1,15 @@
name: angel_mongo
name: angel3_mongo
version: 3.0.0
description: MongoDB-enabled services for the Angel framework. Well-tested.
homepage: https://github.com/angel-dart/angel_mongo
publish_to: none
homepage: https://github.com/dukefirehawk/angel/tree/angel3/packages/mongo
environment:
sdk: '>=2.10.0 <3.0.0'
sdk: '>=2.12.0 <3.0.0'
dependencies:
angel_framework:
git:
url: https://github.com/dukefirehawk/angel.git
ref: sdk-2.12.x_nnbd
path: packages/framework
json_god:
git:
url: https://github.com/dukefirehawk/angel.git
ref: sdk-2.12.x_nnbd
path: packages/json_god
merge_map:
git:
url: https://github.com/dukefirehawk/angel.git
ref: sdk-2.12.x_nnbd
path: packages/merge_map
angel3_framework: ^4.0.0
angel3_json_god: ^4.0.0
angel3_merge_map: ^2.0.0
mongo_dart: ^0.7.0
dev_dependencies:
http: ^0.13.0
pedantic: ^1.0.0
test: ^1.15.7
pedantic: ^1.11.0
test: ^1.17.0

View file

@ -1,8 +1,8 @@
import 'package:angel_framework/angel_framework.dart';
import 'package:angel_framework/http.dart';
import 'package:angel_mongo/angel_mongo.dart';
import 'package:angel3_framework/angel3_framework.dart';
import 'package:angel3_framework/http.dart';
import 'package:angel3_mongo/angel3_mongo.dart';
import 'package:http/http.dart' as http;
import 'package:json_god/json_god.dart' as god;
import 'package:angel3_json_god/angel3_json_god.dart' as god;
import 'package:mongo_dart/mongo_dart.dart';
import 'package:test/test.dart';
@ -23,12 +23,12 @@ void wireHooked(HookedService hooked) {
void main() {
group('Generic Tests', () {
Angel app;
AngelHttp transport;
http.Client client;
late AngelHttp transport;
http.Client? client;
var db = Db('mongodb://localhost:27017/angel_mongo');
DbCollection testData;
String url;
HookedService<String, Map<String, dynamic>, MongoService> greetingService;
late DbCollection testData;
String? url;
HookedService<String, Map<String, dynamic>, MongoService>? greetingService;
setUp(() async {
app = Angel();
@ -41,9 +41,9 @@ void main() {
var service = MongoService(testData, debug: true);
greetingService = HookedService(service);
wireHooked(greetingService);
wireHooked(greetingService!);
app.use('/api', greetingService);
app.use('/api', greetingService as Service);
await transport.startServer('127.0.0.1', 0);
url = transport.uri.toString();
@ -60,25 +60,25 @@ void main() {
});
test('query fields mapped to filters', () async {
await greetingService.create({'foo': 'bar'});
await greetingService!.create({'foo': 'bar'});
expect(
await greetingService.index({
await greetingService!.index({
'query': {'foo': 'not bar'}
}),
isEmpty,
);
expect(
await greetingService.index(),
await greetingService!.index(),
isNotEmpty,
);
});
test('insert items', () async {
var response = await client.post(Uri.parse('$url/api'),
var response = await client!.post(Uri.parse('$url/api'),
body: god.serialize(testGreeting), headers: headers);
expect(response.statusCode, isIn([200, 201]));
response = await client.get(Uri.parse('$url/api'));
response = await client!.get(Uri.parse('$url/api'));
expect(response.statusCode, isIn([200, 201]));
var users = god.deserialize(response.body,
outputType: <Map>[].runtimeType) as List<Map>;
@ -86,12 +86,12 @@ void main() {
});
test('read item', () async {
var response = await client.post(Uri.parse('$url/api'),
var response = await client!.post(Uri.parse('$url/api'),
body: god.serialize(testGreeting), headers: headers);
expect(response.statusCode, isIn([200, 201]));
var created = god.deserialize(response.body) as Map;
response = await client.get(Uri.parse("$url/api/${created['id']}"));
response = await client!.get(Uri.parse("$url/api/${created['id']}"));
expect(response.statusCode, isIn([200, 201]));
var read = god.deserialize(response.body) as Map;
expect(read['id'], equals(created['id']));
@ -100,37 +100,37 @@ void main() {
});
test('findOne', () async {
var response = await client.post(Uri.parse('$url/api'),
var response = await client!.post(Uri.parse('$url/api'),
body: god.serialize(testGreeting), headers: headers);
expect(response.statusCode, isIn([200, 201]));
var created = god.deserialize(response.body) as Map;
var id = ObjectId.fromHexString(created['id'] as String);
var read = await greetingService.findOne({'query': where.id(id)});
var read = await greetingService!.findOne({'query': where.id(id)});
expect(read['id'], equals(created['id']));
expect(read['to'], equals('world'));
//expect(read['createdAt'], isNot(null));
});
test('readMany', () async {
var response = await client.post(Uri.parse('$url/api'),
var response = await client!.post(Uri.parse('$url/api'),
body: god.serialize(testGreeting), headers: headers);
expect(response.statusCode, isIn([200, 201]));
var created = god.deserialize(response.body) as Map;
var id = ObjectId.fromHexString(created['id'] as String);
var read = await greetingService.readMany([id.toHexString()]);
var read = await greetingService!.readMany([id.toHexString()]);
expect(read, [created]);
//expect(read['createdAt'], isNot(null));
});
test('modify item', () async {
var response = await client.post(Uri.parse('$url/api'),
var response = await client!.post(Uri.parse('$url/api'),
body: god.serialize(testGreeting), headers: headers);
expect(response.statusCode, isIn([200, 201]));
var created = god.deserialize(response.body) as Map;
response = await client.patch(Uri.parse("$url/api/${created['id']}"),
response = await client!.patch(Uri.parse("$url/api/${created['id']}"),
body: god.serialize({'to': 'Mom'}), headers: headers);
var modified = god.deserialize(response.body) as Map;
expect(response.statusCode, isIn([200, 201]));
@ -140,12 +140,12 @@ void main() {
});
test('update item', () async {
var response = await client.post(Uri.parse('$url/api'),
var response = await client!.post(Uri.parse('$url/api'),
body: god.serialize(testGreeting), headers: headers);
expect(response.statusCode, isIn([200, 201]));
var created = god.deserialize(response.body) as Map;
response = await client.post(Uri.parse("$url/api/${created['id']}"),
response = await client!.post(Uri.parse("$url/api/${created['id']}"),
body: god.serialize({'to': 'Updated'}), headers: headers);
var modified = god.deserialize(response.body) as Map;
expect(response.statusCode, isIn([200, 201]));
@ -155,28 +155,28 @@ void main() {
});
test('remove item', () async {
var response = await client.post(Uri.parse('$url/api'),
var response = await client!.post(Uri.parse('$url/api'),
body: god.serialize(testGreeting), headers: headers);
var created = god.deserialize(response.body) as Map;
var lastCount = (await greetingService.index()).length;
var lastCount = (await greetingService!.index()).length;
await client.delete(Uri.parse("$url/api/${created['id']}"));
expect((await greetingService.index()).length, equals(lastCount - 1));
await client!.delete(Uri.parse("$url/api/${created['id']}"));
expect((await greetingService!.index()).length, equals(lastCount - 1));
});
test('cannot remove all unless explicitly set', () async {
var response = await client.delete(Uri.parse('$url/api/null'));
var response = await client!.delete(Uri.parse('$url/api/null'));
expect(response.statusCode, 403);
});
test('\$sort and query parameters', () async {
// Search by where.eq
Map world = await greetingService.create({'to': 'world'});
await greetingService.create({'to': 'Mom'});
await greetingService.create({'to': 'Updated'});
Map world = await greetingService!.create({'to': 'world'});
await greetingService!.create({'to': 'Mom'});
await greetingService!.create({'to': 'Updated'});
var response = await client.get(Uri.parse('$url/api?to=world'));
var response = await client!.get(Uri.parse('$url/api?to=world'));
print(response.body);
var queried = god.deserialize(response.body,
outputType: <Map>[].runtimeType) as List<Map>;
@ -193,7 +193,7 @@ void main() {
expect(queried[1]["id"], equals(Mom["id"]));
expect(queried[2]["id"], equals(world["id"]));*/
queried = await greetingService.index({
queried = await greetingService!.index({
'\$query': {
'_id': where.id(ObjectId.fromHexString(world['id'] as String))
}