Hi friends, I have an ETS table to store my user token, so I need to send request to all record and reject the token which are expired.
Example
[
{:"fa7e1d90-beee-4058-9a3e-c78eda344e71",
"e17705be-ef53-4755-9a43-01b2f5c3aa89",
%{
access_expires_in: 1661548398,
create_time: ~U[2022-06-26 21:13:57Z],
last_used: ~U[2022-06-26 21:13:57Z],
os: "linux",
rel: nil,
token: "USER_TOKEN",
token_id: "fa7e1d90-beee-4058-9a3e-c78eda344e71",
type: "refresh"
}}
]
The first thing comes to my mind is to load all records and compare their expiry time, I do not think it is a good way.
Another way I could not be able to use it is using ETS.Set.match_delete
I can use something like this:
ETS.Set.match_delete(table(), {:_, user_id, %{rel: user_token.token_id}})
But how can get the record access_expires_in
and compare in match_delete
pattern
something like this which I can not use
ETS.Set.match_object(table(), {:"$1", user_id, :"$3".access_expires_in < DateTime.utc_now()})
I tried to use something like this:
ms = :ets.fun2ms(fn({key, user_id, token_info}) when token_info.access_expires_in < DateTime.utc_now() -> t end)
But I can not use DateTime.utc_now()
in elixir guard
It should be noted I tested like this:
def delete_expire_token() do
time = DateTime.utc_now() |> DateTime.to_unix()
pattern = {{:"$1", :"$2", :"$3"}, [{:>, {:map_get, :access_expires_in, :"$3"}, time}],[:"$3"]}
ETS.Set.match_object(table(), pattern)
end
But always I get {:ok, []}
Thank you in advance
Update
It works for
def delete_expire_token() do
time = DateTime.utc_now() |> DateTime.to_unix()
pattern = [{{:"$1", :"$2", :"$3"}, [{:<, {:map_get, :access_expires_in, :"$3"}, time}],[:"$3"]}]
ETS.Set.select(table(), pattern)
end
And for ETS.Set.select_delete(table(), pattern)
it should be like this:
def delete_expire_token() do
time = DateTime.utc_now() |> DateTime.to_unix()
pattern = [{{:"$1", :"$2", :"$3"}, [{:>, {:map_get, :access_expires_in, :"$3"}, time}],[true]}]
ETS.Set.select_delete(table(), pattern)
end