Skip to content

Add function BSON.ObjectId.get_timestamp/1 and BSON.ObjectId.get_timestamp!/1 #264

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 16, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading