Skip to content

Commit

Permalink
feat: add fromJson constructor and toJson method
Browse files Browse the repository at this point in the history
  • Loading branch information
gonuit committed Sep 23, 2024
1 parent 4dd39e7 commit bf99e3d
Show file tree
Hide file tree
Showing 6 changed files with 87 additions and 19 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
## 3.1.0
- Added the _ObjectId.toJson()_ method to enable straightforward serialization of ObjectId instances. You can now serialize an ObjectId simply by calling _jsonEncode_ or using the built-in _JsonEncoder_.
- Added the _ObjectId.fromJson(String json)_ factory constructor. This serves as an alias to the existing _ObjectId.fromHexString_ constructor, clearly indicating the intention to deserialize from a JSON value.
## 3.0.0
- ⚠️ The strict runtime type checking in the equals operator has been removed. Now all classes that extend ObjectId and have the same value will be matched by this operator.
```dart
Expand Down
40 changes: 32 additions & 8 deletions example/pubspec.lock
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,26 @@ packages:
dependency: transitive
description:
name: collection
sha256: f092b211a4319e98e5ff58223576de6c2803db36221657b46c82574721240687
sha256: a1ace0a119f20aabc852d165077c036cd864315bd99b7eaa10a60100341941bf
url: "https://pub.dev"
source: hosted
version: "1.17.2"
version: "1.19.0"
crypto:
dependency: transitive
description:
name: crypto
sha256: ff625774173754681d66daaf4a448684fb04b78f902da9cb3d308c19cc5e8bab
sha256: ec30d999af904f33454ba22ed9a86162b35e52b44ac4807d1d93c288041d7d27
url: "https://pub.dev"
source: hosted
version: "3.0.3"
version: "3.0.5"
fixnum:
dependency: transitive
description:
name: fixnum
sha256: "25517a4deb0c03aa0f32fd12db525856438902d9c16536311e76cdc57b31d7d1"
url: "https://pub.dev"
source: hosted
version: "1.1.0"
lints:
dependency: "direct dev"
description:
Expand All @@ -33,13 +41,29 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.1.1"
meta:
dependency: transitive
description:
name: meta
sha256: e3641ec5d63ebf0d9b41bd43201a66e3fc79a65db5f61fc181f04cd27aab950c
url: "https://pub.dev"
source: hosted
version: "1.16.0"
objectid:
dependency: "direct main"
description:
path: ".."
relative: true
source: path
version: "3.0.0"
version: "3.1.0"
sprintf:
dependency: transitive
description:
name: sprintf
sha256: "1fc9ffe69d4df602376b52949af107d8f5703b77cda567c4d7d86a0693120f23"
url: "https://pub.dev"
source: hosted
version: "7.0.0"
typed_data:
dependency: transitive
description:
Expand All @@ -52,9 +76,9 @@ packages:
dependency: "direct main"
description:
name: uuid
sha256: "648e103079f7c64a36dc7d39369cabb358d377078a051d6ae2ad3aa539519313"
sha256: f33d6bb662f0e4f79dcd7ada2e6170f3b3a2530c28fc41f49a411ddedd576a77
url: "https://pub.dev"
source: hosted
version: "3.0.7"
version: "4.5.0"
sdks:
dart: ">=3.0.0 <4.0.0"
dart: ">=3.4.0 <4.0.0"
34 changes: 28 additions & 6 deletions lib/src/objectid/objectid.dart
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,10 @@ class ObjectId {
/// ObjectId bytes.
Uint8List get bytes => _bytes;

/// ### Creates ObjectId.
/// Creates ObjectId instance.
///
/// {@template objectid.structure}
/// #### ObjectId structure:
/// ObjectId structure:
/// ```
/// 4 byte timestamp 5 byte process unique 3 byte counter
/// |<----------------->|<---------------------->|<------------>|
Expand All @@ -63,7 +63,7 @@ class ObjectId {
);
}

/// ### Creates ObjectId from provided values.
/// Creates ObjectId from provided values.
///
/// {@macro objectid.structure}
ObjectId.fromValues(
Expand All @@ -78,7 +78,8 @@ class ObjectId {
_initialize(millisecondsSinceEpoch, processUnique, counter);
}

/// ### Creates ObjectId from provided timestamp.
/// Creates ObjectId from provided timestamp.
///
/// Only timestamp segment is set while the rest of the ObjectId is
/// zeroed out.
///
Expand All @@ -99,9 +100,10 @@ class ObjectId {
_bytes[0] = (secondsSinceEpoch >> 24) & 0xff;
}

/// ### Creates ObjectId from hex string.
/// Creates ObjectId from hex string.
///
/// Can be helpful for mapping hex strings returned from
/// API / mongodb to ObjectId instances.
/// API / MongoDB to ObjectId instances.
///
/// Example usage:
/// ```dart
Expand Down Expand Up @@ -129,6 +131,24 @@ class ObjectId {
_initialize(millisecondsSinceEpoch, processUnique, counter);
}

/// Creates ObjectId from a JSON string.
///
/// This is a factory constructor that maps JSON data
/// to an ObjectId instance.
///
/// Example usage:
/// ```dart
/// final jsonString = '{"_id": "507f1f77bcf86cd799439011"}';
/// final json = jsonDecode(jsonString);
/// final ObjectId objectId = ObjectId.fromJson(json['_id']);
/// print(objectId.hexString); // Output: 507f1f77bcf86cd799439011
/// ```
///
/// **Note:** This method is functionally equivalent to
/// [ObjectId.fromHexString]. It serves as an alias to clearly indicate
/// the intention to deserialize from a JSON value.
factory ObjectId.fromJson(String json) = ObjectId.fromHexString;

/// Internally initialize ObjectId instance by filling
/// bytes array with provided data.
void _initialize(int millisecondsSinceEpoch, int processUnique, int counter) {
Expand Down Expand Up @@ -238,6 +258,8 @@ class ObjectId {
@override
int get hashCode => _hashCode ??= murmurHash2(bytes);

dynamic toJson() => hexString;

@override
String toString() => hexString;
}
2 changes: 1 addition & 1 deletion lib/src/process_unique/process_unique.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import './process_unique_fallback.dart'
if (dart.library.html) './process_unique_web.dart'
if (dart.library.io) './process_unique_io.dart';

/// Process unique astract class
/// Process unique abstract class
abstract class ProcessUnique {
/// Get process unique random value
int getValue();
Expand Down
7 changes: 3 additions & 4 deletions pubspec.yaml
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
name: objectid
description: Blazing fast, cross-platform ObjectId implementation for the dart language.
version: 3.0.0
version: 3.1.0
homepage: https://github.com/gonuit/dart_objectid
repository: https://github.com/gonuit/dart_objectid

environment:
sdk: ">=2.12.0 <4.0.0"

dev_dependencies:
lints: ^2.1.0
test: ^1.24.3
matcher: ^0.12.16
lints: ^4.0.0
test: ^1.25.8
20 changes: 20 additions & 0 deletions test/objectid_test.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import 'dart:convert';
import 'dart:typed_data';

import 'package:objectid/objectid.dart';
Expand Down Expand Up @@ -161,5 +162,24 @@ void main() {

expect(id.toString(), equals('5f52f0b42b5bb4c3adef2044'));
});

test('toJson works correctly for a single element', () {
final object = ObjectId();
expect(object.toJson(), equals(object.hexString));
expect(jsonEncode(object), equals('"${object.hexString}"'));
});

test('toJson works correctly for nested elements', () {
final list = List.generate(10, (index) => ObjectId());
expect(
jsonEncode(list),
equals("[${list.map((o) => '"${o.hexString}"').join(',')}]"),
);
});

test('fromJson works correctly', () {
final object = ObjectId();
expect(ObjectId.fromJson(object.toJson()), equals(object));
});
});
}

0 comments on commit bf99e3d

Please sign in to comment.