~homeworkprod/byceps

ref: bcef32cd2dc329bcf81057794883008f5c040ac8 byceps/byceps/services/news/channel_service.py -rw-r--r-- 2.0 KiB
bcef32cd — Jochen Kupperschmidt Work around Jinja 3.0.0 bug with `for` inside of `set` block 8 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
"""
byceps.services.news.channel_service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""

from __future__ import annotations
from typing import Optional, Sequence

from ...database import db
from ...typing import BrandID

from ..brand import service as brand_service

from .dbmodels.channel import Channel as DbChannel
from .transfer.models import Channel, ChannelID


def create_channel(
    brand_id: BrandID, channel_id: ChannelID, url_prefix: str
) -> Channel:
    """Create a channel for that brand."""
    brand = brand_service.find_brand(brand_id)
    if brand is None:
        raise ValueError(f'Unknown brand ID "{brand_id}"')

    channel = DbChannel(channel_id, brand.id, url_prefix)

    db.session.add(channel)
    db.session.commit()

    return _db_entity_to_channel(channel)


def delete_channel(channel_id: ChannelID) -> None:
    """Delete a news channel."""
    db.session.query(DbChannel) \
        .filter_by(id=channel_id) \
        .delete()

    db.session.commit()


def find_channel(channel_id: ChannelID) -> Optional[Channel]:
    """Return the channel with that id, or `None` if not found."""
    channel = DbChannel.query.get(channel_id)

    if channel is None:
        return None

    return _db_entity_to_channel(channel)


def get_all_channels() -> list[Channel]:
    """Return all channels."""
    channels = DbChannel.query.all()

    return [_db_entity_to_channel(channel) for channel in channels]


def get_channels_for_brand(brand_id: BrandID) -> Sequence[Channel]:
    """Return all channels that belong to the brand."""
    channels = DbChannel.query \
        .filter_by(brand_id=brand_id) \
        .order_by(DbChannel.id) \
        .all()

    return [_db_entity_to_channel(channel) for channel in channels]


def _db_entity_to_channel(channel: DbChannel) -> Channel:
    return Channel(
        channel.id,
        channel.brand_id,
        channel.url_prefix,
    )