From a50fcf7e3507f005667f3f77916ac548761189ca Mon Sep 17 00:00:00 2001 From: Haohan Yang <37651510+haohanyang@users.noreply.github.com> Date: Thu, 16 Jan 2025 20:24:40 +0100 Subject: [PATCH] Add function BSON.ObjectId.get_timestamp/1 and BSON.ObjectId.get_timestamp!/1 (#264) Thank you! --- lib/bson/types.ex | 23 +++++++++++++++++++++++ test/bson/types_test.exs | 16 ++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/lib/bson/types.ex b/lib/bson/types.ex index b5c919f3..4062a209 100644 --- a/lib/bson/types.ex +++ b/lib/bson/types.ex @@ -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(<>) 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 diff --git a/test/bson/types_test.exs b/test/bson/types_test.exs index 4112c6d5..8bc22c6c 100644 --- a/test/bson/types_test.exs +++ b/test/bson/types_test.exs @@ -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}>" @@ -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\", \"\">"