From 3adf9d62bc3b1782497bb5253177855f7e5db72d Mon Sep 17 00:00:00 2001 From: thomashii Date: Fri, 18 Jun 2021 19:10:38 +0800 Subject: [PATCH] Published mongo --- packages/mongo/README.md | 18 ++--- packages/mongo/example/example.dart | 4 +- .../{angel_mongo.dart => angel3_mongo.dart} | 2 +- packages/mongo/lib/model.dart | 8 +-- packages/mongo/lib/mongo_service.dart | 54 +++++++------- packages/mongo/lib/services.dart | 16 ++--- packages/mongo/pubspec.yaml | 29 +++----- packages/mongo/test/generic_test.dart | 72 +++++++++---------- 8 files changed, 98 insertions(+), 105 deletions(-) rename packages/mongo/lib/{angel_mongo.dart => angel3_mongo.dart} (53%) diff --git a/packages/mongo/README.md b/packages/mongo/README.md index de3dd1c5..8938e30b 100644 --- a/packages/mongo/README.md +++ b/packages/mongo/README.md @@ -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}"); diff --git a/packages/mongo/example/example.dart b/packages/mongo/example/example.dart index e474e0aa..e888c666 100644 --- a/packages/mongo/example/example.dart +++ b/packages/mongo/example/example.dart @@ -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 { diff --git a/packages/mongo/lib/angel_mongo.dart b/packages/mongo/lib/angel3_mongo.dart similarity index 53% rename from packages/mongo/lib/angel_mongo.dart rename to packages/mongo/lib/angel3_mongo.dart index 56747813..0b0b620a 100644 --- a/packages/mongo/lib/angel_mongo.dart +++ b/packages/mongo/lib/angel3_mongo.dart @@ -1,3 +1,3 @@ -library angel_mongo; +library angel3_mongo; export 'services.dart'; diff --git a/packages/mongo/lib/model.dart b/packages/mongo/lib/model.dart index 1c8c8ed4..4891925d 100644 --- a/packages/mongo/lib/model.dart +++ b/packages/mongo/lib/model.dart @@ -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; } diff --git a/packages/mongo/lib/mongo_service.dart b/packages/mongo/lib/mongo_service.dart index bc0418d9..0a57adb3 100644 --- a/packages/mongo/lib/mongo_service.dart +++ b/packages/mongo/lib/mongo_service.dart @@ -1,4 +1,4 @@ -part of angel_mongo.services; +part of angel3_mongo.services; /// Manipulates data from MongoDB as Maps. class MongoService extends Service> { @@ -20,14 +20,14 @@ class MongoService extends Service> { {this.allowRemoveAll = false, this.allowQuery = true, this.debug = true}) : super(); - SelectorBuilder _makeQuery([Map params_]) { + SelectorBuilder? _makeQuery([Map? 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> { } } 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 ? _filterNoQuery(v) : v; @@ -71,7 +71,7 @@ class MongoService extends Service> { } Map _jsonify(Map doc, - [Map params]) { + [Map? params]) { var result = {}; for (var key in doc.keys) { @@ -88,7 +88,7 @@ class MongoService extends Service> { @override Future>> index( - [Map params]) async { + [Map? params]) async { return await (collection.find(_makeQuery(params))) .map((x) => _jsonify(x, params)) .toList(); @@ -98,16 +98,16 @@ class MongoService extends Service> { @override Future> create(Map data, - [Map params]) async { + [Map? 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>); return _jsonify(result); } catch (e, st) { throw AngelHttpException(e, stackTrace: st); @@ -116,7 +116,7 @@ class MongoService extends Service> { @override Future> findOne( - [Map params, + [Map? 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> { @override Future> read(String id, - [Map params]) async { + [Map? 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> { @override Future>> readMany(List ids, - [Map params]) async { + [Map? 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> modify(String id, data, - [Map params]) async { + [Map? params]) async { Map target; try { @@ -169,8 +170,10 @@ class MongoService extends Service> { //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>); result = _jsonify(modified, params); result['id'] = _makeId(id).toHexString(); return result; @@ -182,7 +185,7 @@ class MongoService extends Service> { @override Future> update(String id, Map data, - [Map params]) async { + [Map? params]) async { var result = _removeSensitive(data); result['_id'] = _makeId(id); /*result['createdAt'] = @@ -194,11 +197,11 @@ class MongoService extends Service> { 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>); result = _jsonify(updated, params); result['id'] = _makeId(id).toHexString(); return result; @@ -210,8 +213,8 @@ class MongoService extends Service> { @override Future> remove(String id, - [Map params]) async { - if (id == null || id == 'null') { + [Map? params]) async { + if (id == 'null') { // Remove everything... if (!(allowRemoveAll == true || params?.containsKey('provider') != true)) { @@ -226,8 +229,9 @@ class MongoService extends Service> { // 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>); return _jsonify(result); } catch (e, st) { //printDebug(e, st, 'REMOVE'); diff --git a/packages/mongo/lib/services.dart b/packages/mongo/lib/services.dart index a44dedd4..bd18a1c6 100644 --- a/packages/mongo/lib/services.dart +++ b/packages/mongo/lib/services.dart @@ -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 _transformId(Map doc) { - var result = new Map.from(doc); + var result = Map.from(doc); result ..['id'] = doc['_id'] ..remove('_id'); @@ -18,13 +18,13 @@ Map _transformId(Map 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 _sensitiveFieldNames = const [ +const List _sensitiveFieldNames = [ 'id', '_id', 'createdAt', @@ -37,7 +37,7 @@ Map _removeSensitive(Map data) { .fold({}, (map, key) => map..[key] = data[key]); } -const List _NO_QUERY = const ['__requestctx', '__responsectx']; +const List _NO_QUERY = ['__requestctx', '__responsectx']; Map _filterNoQuery(Map data) { return data.keys.fold({}, (map, key) { diff --git a/packages/mongo/pubspec.yaml b/packages/mongo/pubspec.yaml index 5e065a7d..138a6e75 100644 --- a/packages/mongo/pubspec.yaml +++ b/packages/mongo/pubspec.yaml @@ -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 diff --git a/packages/mongo/test/generic_test.dart b/packages/mongo/test/generic_test.dart index 9fa97d3d..0bd816a2 100644 --- a/packages/mongo/test/generic_test.dart +++ b/packages/mongo/test/generic_test.dart @@ -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, MongoService> greetingService; + late DbCollection testData; + String? url; + HookedService, 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: [].runtimeType) as List; @@ -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: [].runtimeType) as List; @@ -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)) }