Skip to content

Commit

Permalink
Add function BSON.ObjectId.get_timestamp/1 and BSON.ObjectId.get_time…
Browse files Browse the repository at this point in the history
…stamp!/1 (#264)

Thank you!
  • Loading branch information
haohanyang authored Jan 16, 2025
1 parent c90199b commit a50fcf7
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
23 changes: 23 additions & 0 deletions lib/bson/types.ex
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,29 @@ defmodule BSON.ObjectId do
defimpl String.Chars do
def to_string(id), do: BSON.ObjectId.encode!(id)
end

@doc """
Extracts timestamp from BSON.ObjectId
"""
def get_timestamp!(%BSON.ObjectId{value: value}), do: do_get_timestamp(value)

def do_get_timestamp(<<ts::32, _::binary>>) do
DateTime.from_unix!(ts)
end

@doc """
Extracts timestamp from BSON.ObjectId
## Examples
{:ok, timestamp} <- BSON.ObjectId.get_timestamp(id)
"""
def get_timestamp(object_id) do
try do
{:ok, get_timestamp!(object_id)}
rescue
_ -> :error
end
end
end

defmodule BSON.Regex do
Expand Down
16 changes: 16 additions & 0 deletions test/bson/types_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ defmodule BSON.TypesTest do

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

test "inspect BSON.ObjectId" do
assert inspect(@objectid) == "#BSON.ObjectId<#{@string}>"
Expand Down Expand Up @@ -46,6 +47,21 @@ defmodule BSON.TypesTest do
assert to_string(@objectid) == @string
end

test "BSON.ObjectId.get_timestamp!/1" do
value = BSON.ObjectId.get_timestamp!(@objectid)
assert DateTime.compare(value, @timestamp) == :eq

assert_raise FunctionClauseError, fn ->
BSON.ObjectId.get_timestamp!("")
end
end

test "BSON.ObjectId.get_timestamp/1" do
assert {:ok, value} = BSON.ObjectId.get_timestamp(@objectid)
assert DateTime.compare(value, @timestamp) == :eq
assert BSON.ObjectId.get_timestamp("") == :error
end

test "inspect BSON.Regex" do
value = %BSON.Regex{pattern: "abc"}
assert inspect(value) == "#BSON.Regex<\"abc\", \"\">"
Expand Down

0 comments on commit a50fcf7

Please sign in to comment.