Sure, here is an example of a boilerplate_riverpod.service file that defines a service for a Task object, along with the corresponding json_serializable classes for the Task object's attributes:
# boilerplate_riverpod/service.py
from riverpod import service
from riverpod.json import json_serializable
class TaskService:
@service.service
class Task:
name: str
description: str
deadline: datetime
assignees: list[str]
urgency: int
@json_serializable
def to_json(self):
return {
"name": self.name,
"description": self.description,
"deadline": self.deadline.isoformat(),
"assignees": self.assignees,
"urgency": self.urgency
}
Here's a breakdown of the code:
- The
boilerplate_riverpod.service file defines a service class called TaskService.
- The
Task class within the TaskService class is defined using the @service.service decorator, which indicates that this class represents a Riverpod service.
- The
Task class has five attributes: name, description, deadline, assignees, and urgency. These attributes are defined using the json_serializable decorator, which indicates that they can be serialized to JSON.
- The
to_json() method is defined within the Task class, which takes a self parameter and returns a JSON-serializable dictionary containing the values of the name, description, deadline, assignees, and urgency attributes.
- The
TaskService class defines a Task instance, which can be used to create and manage tasks.
- The
TaskService class also defines a tasks attribute, which is a Riverpod state that stores a list of Task instances.
With this code in place, you can use the TaskService class to create, read, update, and delete tasks, and the Task instances will be automatically serialized to JSON when they are saved to the Riverpod state.
Here's an example of how you might use the TaskService class:
# boilerplate_riverpod/example.py
from boilerplate_riverpod import TaskService
# Create a new task
task = TaskService.Task(name="Write a blog post", description="Write a blog post about Riverpod", deadline=datetime.now() + timedelta(days=7), assignees=["user1"], urgency=5)
# Save the task to the Riverpod state
TaskService.save(task)
# Read the task from the Riverpod state
task2 = TaskService.Task.get()
print(task2.name) # Output: "Write a blog post"
print(task2.description) # Output: "Write a blog post about Riverpod"
print(task2.deadline) # Output: "2023-03-07 12:30:00"
print(task2.assignees) # Output: ["user1"]
print(task2.urgency) # Output: 5
I hope this helps! Let me know if you have any questions.