Skip to content

Commit

Permalink
Convert devices list into a dictionary keyed by device ID (#2)
Browse files Browse the repository at this point in the history
  • Loading branch information
frenck authored Nov 16, 2021
1 parent 9ef255d commit 0dba658
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 6 deletions.
3 changes: 2 additions & 1 deletion src/tailscale/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
"""Asynchronous client for the Tailscale API."""
from .models import ClientConnectivity, ClientSupports, Device
from .models import ClientConnectivity, ClientSupports, Device, Devices
from .tailscale import (
Tailscale,
TailscaleAuthenticationError,
Expand All @@ -11,6 +11,7 @@
"ClientConnectivity",
"ClientSupports",
"Device",
"Devices",
"Tailscale",
"TailscaleAuthenticationError",
"TailscaleConnectionError",
Expand Down
21 changes: 18 additions & 3 deletions src/tailscale/models.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
"""Asynchronous client for the Tailscale API."""
from __future__ import annotations

from datetime import datetime
from typing import Any, List, Optional
from typing import Any, Dict, List, Optional

from pydantic import BaseModel, Field
from pydantic import BaseModel, Field, validator


class ClientSupports(BaseModel):
Expand Down Expand Up @@ -56,4 +58,17 @@ class Device(BaseModel):
class Devices(BaseModel):
"""Object holding Tailscale device information."""

devices: List[Device]
devices: Dict[str, Device]

@validator("devices", pre=True)
@classmethod
def convert_to_dict(cls, data: list[dict]) -> dict[Any, dict]: # noqa: F841
"""Convert list into dict, keyed by device id.
Args:
data: List of dicts to convert.
Returns:
dict: Converted list of dicts.
"""
return {device["id"]: device for device in data}
4 changes: 2 additions & 2 deletions src/tailscale/tailscale.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,11 +105,11 @@ async def _request(

return await response.json(content_type=None)

async def devices(self) -> list[Device]:
async def devices(self) -> dict[str, Device]:
"""Get devices information from the Tailscale API.
Returns:
Returns a list of Tailscale devices.
Returns a dictionary of Tailscale devices.
"""
data = await self._request(f"tailnet/{self.tailnet}/devices")
return Devices.parse_obj(data).devices
Expand Down

0 comments on commit 0dba658

Please sign in to comment.