Skip to content

Commit a50fcf7

Browse files
authored
Add function BSON.ObjectId.get_timestamp/1 and BSON.ObjectId.get_timestamp!/1 (#264)
Thank you!
1 parent c90199b commit a50fcf7

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

lib/bson/types.ex

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,29 @@ defmodule BSON.ObjectId do
142142
defimpl String.Chars do
143143
def to_string(id), do: BSON.ObjectId.encode!(id)
144144
end
145+
146+
@doc """
147+
Extracts timestamp from BSON.ObjectId
148+
"""
149+
def get_timestamp!(%BSON.ObjectId{value: value}), do: do_get_timestamp(value)
150+
151+
def do_get_timestamp(<<ts::32, _::binary>>) do
152+
DateTime.from_unix!(ts)
153+
end
154+
155+
@doc """
156+
Extracts timestamp from BSON.ObjectId
157+
158+
## Examples
159+
{:ok, timestamp} <- BSON.ObjectId.get_timestamp(id)
160+
"""
161+
def get_timestamp(object_id) do
162+
try do
163+
{:ok, get_timestamp!(object_id)}
164+
rescue
165+
_ -> :error
166+
end
167+
end
145168
end
146169

147170
defmodule BSON.Regex do

test/bson/types_test.exs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ defmodule BSON.TypesTest do
1111

1212
@objectid %BSON.ObjectId{value: <<29, 32, 69, 244, 101, 119, 228, 28, 61, 24, 21, 215>>}
1313
@string "1d2045f46577e41c3d1815d7"
14+
@timestamp DateTime.from_unix!(488_654_324)
1415

1516
test "inspect BSON.ObjectId" do
1617
assert inspect(@objectid) == "#BSON.ObjectId<#{@string}>"
@@ -46,6 +47,21 @@ defmodule BSON.TypesTest do
4647
assert to_string(@objectid) == @string
4748
end
4849

50+
test "BSON.ObjectId.get_timestamp!/1" do
51+
value = BSON.ObjectId.get_timestamp!(@objectid)
52+
assert DateTime.compare(value, @timestamp) == :eq
53+
54+
assert_raise FunctionClauseError, fn ->
55+
BSON.ObjectId.get_timestamp!("")
56+
end
57+
end
58+
59+
test "BSON.ObjectId.get_timestamp/1" do
60+
assert {:ok, value} = BSON.ObjectId.get_timestamp(@objectid)
61+
assert DateTime.compare(value, @timestamp) == :eq
62+
assert BSON.ObjectId.get_timestamp("") == :error
63+
end
64+
4965
test "inspect BSON.Regex" do
5066
value = %BSON.Regex{pattern: "abc"}
5167
assert inspect(value) == "#BSON.Regex<\"abc\", \"\">"

0 commit comments

Comments
 (0)