sisyo 1.7.0 → 1.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +16 -16
- package/README.md +177 -166
- package/bin/known-hashes.json +8 -1
- package/bin/sisyo.js +285 -285
- package/package.json +30 -30
- package/templates/.claude/rules/agents-and-tests.md +32 -24
- package/templates/.claude/rules/docs.md +39 -19
- package/templates/.claude/skills/fastapi-best-practices/ASYNC-PATTERNS.md +121 -121
- package/templates/.claude/skills/fastapi-best-practices/DATABASE.md +153 -153
- package/templates/.claude/skills/fastapi-best-practices/DEPENDENCIES.md +140 -140
- package/templates/.claude/skills/fastapi-best-practices/PROJECT-STRUCTURE.md +90 -90
- package/templates/.claude/skills/fastapi-best-practices/PYDANTIC-GUIDE.md +155 -155
- package/templates/.claude/skills/fastapi-best-practices/SKILL.md +123 -123
- package/templates/.claude/skills/g6-style/SKILL.md +125 -125
- package/templates/.claude/skills/g6-style/references/checks.md +58 -58
- package/templates/.claude/skills/g6-style/references/imagery.md +103 -103
- package/templates/.claude/skills/g6-style/references/motion.md +121 -121
- package/templates/.claude/skills/g6-style/references/sections.md +263 -263
- package/templates/.claude/skills/g6-style/references/tokens.md +197 -197
- package/templates/.claude/skills/hindsight/SKILL.md +175 -175
- package/templates/.claude/skills/hoang-auth/SKILL.md +188 -0
- package/templates/.claude/skills/html-docs/SKILL.md +207 -207
- package/templates/.claude/skills/i18n-multilang/SKILL.md +153 -153
- package/templates/.claude/skills/i18n-multilang/assets/languages.json +47 -47
- package/templates/.claude/skills/i18n-multilang/assets/plural-vectors.json +46 -46
- package/templates/.claude/skills/i18n-multilang/assets/project/README.md +17 -17
- package/templates/.claude/skills/i18n-multilang/assets/project/gitattributes.txt +6 -6
- package/templates/.claude/skills/i18n-multilang/assets/project/gitignore.txt +4 -4
- package/templates/.claude/skills/i18n-multilang/assets/project/glossary.json +6 -6
- package/templates/.claude/skills/i18n-multilang/assets/project/i18n.config.json +22 -22
- package/templates/.claude/skills/i18n-multilang/assets/project/locales/__source__/common.json +10 -10
- package/templates/.claude/skills/i18n-multilang/assets/project/notes/common.json +5 -5
- package/templates/.claude/skills/i18n-multilang/assets/project/style.md +20 -20
- package/templates/.claude/skills/i18n-multilang/references/format.md +100 -100
- package/templates/.claude/skills/i18n-multilang/references/languages.md +97 -97
- package/templates/.claude/skills/i18n-multilang/references/layout-and-versioning.md +256 -256
- package/templates/.claude/skills/i18n-multilang/references/numbers.md +161 -161
- package/templates/.claude/skills/i18n-multilang/references/platform-unity.md +142 -142
- package/templates/.claude/skills/i18n-multilang/references/platform-web.md +107 -107
- package/templates/.claude/skills/i18n-multilang/references/translation.md +143 -143
- package/templates/.claude/skills/i18n-multilang/references/voice.md +271 -271
- package/templates/.claude/skills/i18n-multilang/scripts/i18n.py +1041 -1041
- package/templates/.claude/skills/i18n-multilang/scripts/numwords.py +1013 -1013
- package/templates/.claude/skills/i18n-multilang/scripts/voice.py +478 -478
- package/templates/.claude/skills/neon-game-ui-ux-skill/COMPONENTS.md +490 -490
- package/templates/.claude/skills/neon-game-ui-ux-skill/GAMIFICATION.md +246 -246
- package/templates/.claude/skills/neon-game-ui-ux-skill/ICONS.md +249 -249
- package/templates/.claude/skills/neon-game-ui-ux-skill/LAYOUT-NAV.md +362 -362
- package/templates/.claude/skills/neon-game-ui-ux-skill/MOTION-A11Y.md +168 -168
- package/templates/.claude/skills/neon-game-ui-ux-skill/SKILL.md +137 -137
- package/templates/.claude/skills/neon-game-ui-ux-skill/TOKENS.md +323 -323
- package/templates/.claude/skills/react-page-oriented/SKILL.md +407 -407
- package/templates/.claude/skills/react-page-oriented/triggers.md +12 -12
- package/templates/.claude/skills/terraform-best-practices/SKILL.md +341 -341
- package/templates/.claude/skills/typesafe-jev/SKILL.md +148 -148
- package/templates/.claude/skills/vibe-docs/SKILL.md +139 -242
- package/templates/SISYO.md +39 -37
- package/templates/docs/99_progress/features.md +7 -7
- package/templates/docs/99_progress/handoff.md +19 -19
- package/templates/docs/99_progress/todo.md +15 -15
- package/templates/docs/MAP.md +26 -26
|
@@ -1,153 +1,153 @@
|
|
|
1
|
-
# Database Patterns
|
|
2
|
-
|
|
3
|
-
## Naming Conventions
|
|
4
|
-
|
|
5
|
-
| Convention | Rule | Example |
|
|
6
|
-
|------------|------|---------|
|
|
7
|
-
| Tables | `lower_case_snake`, singular | `post`, `user_playlist` |
|
|
8
|
-
| Group by module | prefix with module | `payment_account`, `payment_bill` |
|
|
9
|
-
| Datetime columns | `_at` suffix | `created_at`, `updated_at` |
|
|
10
|
-
| Date columns | `_date` suffix | `birth_date`, `due_date` |
|
|
11
|
-
|
|
12
|
-
## SQLAlchemy Index Naming
|
|
13
|
-
|
|
14
|
-
```python
|
|
15
|
-
from sqlalchemy import MetaData
|
|
16
|
-
|
|
17
|
-
POSTGRES_INDEXES_NAMING_CONVENTION = {
|
|
18
|
-
"ix": "%(column_0_label)s_idx",
|
|
19
|
-
"uq": "%(table_name)s_%(column_0_name)s_key",
|
|
20
|
-
"ck": "%(table_name)s_%(constraint_name)s_check",
|
|
21
|
-
"fk": "%(table_name)s_%(column_0_name)s_fkey",
|
|
22
|
-
"pk": "%(table_name)s_pkey",
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
metadata = MetaData(naming_convention=POSTGRES_INDEXES_NAMING_CONVENTION)
|
|
26
|
-
```
|
|
27
|
-
|
|
28
|
-
## SQL-First Approach
|
|
29
|
-
|
|
30
|
-
Let database do the heavy lifting:
|
|
31
|
-
|
|
32
|
-
```python
|
|
33
|
-
from sqlalchemy import select, func, text, desc
|
|
34
|
-
|
|
35
|
-
async def get_posts_with_creator(
|
|
36
|
-
creator_id: UUID4,
|
|
37
|
-
limit: int = 10,
|
|
38
|
-
offset: int = 0
|
|
39
|
-
) -> list[dict]:
|
|
40
|
-
query = (
|
|
41
|
-
select(
|
|
42
|
-
posts.c.id,
|
|
43
|
-
posts.c.title,
|
|
44
|
-
posts.c.slug,
|
|
45
|
-
# Build JSON in database
|
|
46
|
-
func.json_build_object(
|
|
47
|
-
text("'id', profiles.id"),
|
|
48
|
-
text("'name', profiles.name"),
|
|
49
|
-
text("'username', profiles.username"),
|
|
50
|
-
).label("creator"),
|
|
51
|
-
)
|
|
52
|
-
.select_from(posts.join(profiles, posts.c.owner_id == profiles.c.id))
|
|
53
|
-
.where(posts.c.owner_id == creator_id)
|
|
54
|
-
.order_by(desc(posts.c.created_at))
|
|
55
|
-
.limit(limit)
|
|
56
|
-
.offset(offset)
|
|
57
|
-
)
|
|
58
|
-
return await database.fetch_all(query)
|
|
59
|
-
```
|
|
60
|
-
|
|
61
|
-
## Alembic Migrations
|
|
62
|
-
|
|
63
|
-
### Config
|
|
64
|
-
|
|
65
|
-
```ini
|
|
66
|
-
# alembic.ini
|
|
67
|
-
file_template = %%(year)d-%%(month).2d-%%(day).2d_%%(slug)s
|
|
68
|
-
```
|
|
69
|
-
|
|
70
|
-
Generates: `2024-01-15_add_user_email_index.py`
|
|
71
|
-
|
|
72
|
-
### Migration Best Practices
|
|
73
|
-
|
|
74
|
-
1. **Always reversible** - include `downgrade()` function
|
|
75
|
-
2. **Descriptive names** - `add_posts_title_idx`, not `update_1`
|
|
76
|
-
3. **Static structure** - only data can be dynamic, not schema
|
|
77
|
-
|
|
78
|
-
```python
|
|
79
|
-
# Good migration
|
|
80
|
-
def upgrade():
|
|
81
|
-
op.add_column('users', sa.Column('avatar_url', sa.String(500)))
|
|
82
|
-
op.create_index('users_email_idx', 'users', ['email'])
|
|
83
|
-
|
|
84
|
-
def downgrade():
|
|
85
|
-
op.drop_index('users_email_idx', 'users')
|
|
86
|
-
op.drop_column('users', 'avatar_url')
|
|
87
|
-
```
|
|
88
|
-
|
|
89
|
-
## Async Database Setup
|
|
90
|
-
|
|
91
|
-
```python
|
|
92
|
-
# src/database.py
|
|
93
|
-
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
|
|
94
|
-
from sqlalchemy.orm import sessionmaker
|
|
95
|
-
|
|
96
|
-
engine = create_async_engine(
|
|
97
|
-
settings.DATABASE_URL,
|
|
98
|
-
echo=settings.ENVIRONMENT == "local",
|
|
99
|
-
)
|
|
100
|
-
|
|
101
|
-
async_session = sessionmaker(
|
|
102
|
-
engine,
|
|
103
|
-
class_=AsyncSession,
|
|
104
|
-
expire_on_commit=False,
|
|
105
|
-
)
|
|
106
|
-
|
|
107
|
-
async def get_session() -> AsyncGenerator[AsyncSession, None]:
|
|
108
|
-
async with async_session() as session:
|
|
109
|
-
try:
|
|
110
|
-
yield session
|
|
111
|
-
await session.commit()
|
|
112
|
-
except Exception:
|
|
113
|
-
await session.rollback()
|
|
114
|
-
raise
|
|
115
|
-
```
|
|
116
|
-
|
|
117
|
-
## Query Patterns
|
|
118
|
-
|
|
119
|
-
### Pagination
|
|
120
|
-
|
|
121
|
-
```python
|
|
122
|
-
from pydantic import BaseModel
|
|
123
|
-
|
|
124
|
-
class PaginationParams(BaseModel):
|
|
125
|
-
limit: int = 10
|
|
126
|
-
offset: int = 0
|
|
127
|
-
|
|
128
|
-
async def get_paginated(
|
|
129
|
-
session: AsyncSession,
|
|
130
|
-
params: PaginationParams
|
|
131
|
-
) -> list[Post]:
|
|
132
|
-
result = await session.execute(
|
|
133
|
-
select(Post)
|
|
134
|
-
.order_by(Post.created_at.desc())
|
|
135
|
-
.limit(params.limit)
|
|
136
|
-
.offset(params.offset)
|
|
137
|
-
)
|
|
138
|
-
return result.scalars().all()
|
|
139
|
-
```
|
|
140
|
-
|
|
141
|
-
### Eager Loading
|
|
142
|
-
|
|
143
|
-
```python
|
|
144
|
-
from sqlalchemy.orm import selectinload
|
|
145
|
-
|
|
146
|
-
# Avoid N+1 queries
|
|
147
|
-
async def get_posts_with_comments(session: AsyncSession):
|
|
148
|
-
result = await session.execute(
|
|
149
|
-
select(Post)
|
|
150
|
-
.options(selectinload(Post.comments))
|
|
151
|
-
)
|
|
152
|
-
return result.scalars().all()
|
|
153
|
-
```
|
|
1
|
+
# Database Patterns
|
|
2
|
+
|
|
3
|
+
## Naming Conventions
|
|
4
|
+
|
|
5
|
+
| Convention | Rule | Example |
|
|
6
|
+
|------------|------|---------|
|
|
7
|
+
| Tables | `lower_case_snake`, singular | `post`, `user_playlist` |
|
|
8
|
+
| Group by module | prefix with module | `payment_account`, `payment_bill` |
|
|
9
|
+
| Datetime columns | `_at` suffix | `created_at`, `updated_at` |
|
|
10
|
+
| Date columns | `_date` suffix | `birth_date`, `due_date` |
|
|
11
|
+
|
|
12
|
+
## SQLAlchemy Index Naming
|
|
13
|
+
|
|
14
|
+
```python
|
|
15
|
+
from sqlalchemy import MetaData
|
|
16
|
+
|
|
17
|
+
POSTGRES_INDEXES_NAMING_CONVENTION = {
|
|
18
|
+
"ix": "%(column_0_label)s_idx",
|
|
19
|
+
"uq": "%(table_name)s_%(column_0_name)s_key",
|
|
20
|
+
"ck": "%(table_name)s_%(constraint_name)s_check",
|
|
21
|
+
"fk": "%(table_name)s_%(column_0_name)s_fkey",
|
|
22
|
+
"pk": "%(table_name)s_pkey",
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
metadata = MetaData(naming_convention=POSTGRES_INDEXES_NAMING_CONVENTION)
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## SQL-First Approach
|
|
29
|
+
|
|
30
|
+
Let database do the heavy lifting:
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
from sqlalchemy import select, func, text, desc
|
|
34
|
+
|
|
35
|
+
async def get_posts_with_creator(
|
|
36
|
+
creator_id: UUID4,
|
|
37
|
+
limit: int = 10,
|
|
38
|
+
offset: int = 0
|
|
39
|
+
) -> list[dict]:
|
|
40
|
+
query = (
|
|
41
|
+
select(
|
|
42
|
+
posts.c.id,
|
|
43
|
+
posts.c.title,
|
|
44
|
+
posts.c.slug,
|
|
45
|
+
# Build JSON in database
|
|
46
|
+
func.json_build_object(
|
|
47
|
+
text("'id', profiles.id"),
|
|
48
|
+
text("'name', profiles.name"),
|
|
49
|
+
text("'username', profiles.username"),
|
|
50
|
+
).label("creator"),
|
|
51
|
+
)
|
|
52
|
+
.select_from(posts.join(profiles, posts.c.owner_id == profiles.c.id))
|
|
53
|
+
.where(posts.c.owner_id == creator_id)
|
|
54
|
+
.order_by(desc(posts.c.created_at))
|
|
55
|
+
.limit(limit)
|
|
56
|
+
.offset(offset)
|
|
57
|
+
)
|
|
58
|
+
return await database.fetch_all(query)
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## Alembic Migrations
|
|
62
|
+
|
|
63
|
+
### Config
|
|
64
|
+
|
|
65
|
+
```ini
|
|
66
|
+
# alembic.ini
|
|
67
|
+
file_template = %%(year)d-%%(month).2d-%%(day).2d_%%(slug)s
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Generates: `2024-01-15_add_user_email_index.py`
|
|
71
|
+
|
|
72
|
+
### Migration Best Practices
|
|
73
|
+
|
|
74
|
+
1. **Always reversible** - include `downgrade()` function
|
|
75
|
+
2. **Descriptive names** - `add_posts_title_idx`, not `update_1`
|
|
76
|
+
3. **Static structure** - only data can be dynamic, not schema
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
# Good migration
|
|
80
|
+
def upgrade():
|
|
81
|
+
op.add_column('users', sa.Column('avatar_url', sa.String(500)))
|
|
82
|
+
op.create_index('users_email_idx', 'users', ['email'])
|
|
83
|
+
|
|
84
|
+
def downgrade():
|
|
85
|
+
op.drop_index('users_email_idx', 'users')
|
|
86
|
+
op.drop_column('users', 'avatar_url')
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
## Async Database Setup
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
# src/database.py
|
|
93
|
+
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
|
|
94
|
+
from sqlalchemy.orm import sessionmaker
|
|
95
|
+
|
|
96
|
+
engine = create_async_engine(
|
|
97
|
+
settings.DATABASE_URL,
|
|
98
|
+
echo=settings.ENVIRONMENT == "local",
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
async_session = sessionmaker(
|
|
102
|
+
engine,
|
|
103
|
+
class_=AsyncSession,
|
|
104
|
+
expire_on_commit=False,
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
async def get_session() -> AsyncGenerator[AsyncSession, None]:
|
|
108
|
+
async with async_session() as session:
|
|
109
|
+
try:
|
|
110
|
+
yield session
|
|
111
|
+
await session.commit()
|
|
112
|
+
except Exception:
|
|
113
|
+
await session.rollback()
|
|
114
|
+
raise
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
## Query Patterns
|
|
118
|
+
|
|
119
|
+
### Pagination
|
|
120
|
+
|
|
121
|
+
```python
|
|
122
|
+
from pydantic import BaseModel
|
|
123
|
+
|
|
124
|
+
class PaginationParams(BaseModel):
|
|
125
|
+
limit: int = 10
|
|
126
|
+
offset: int = 0
|
|
127
|
+
|
|
128
|
+
async def get_paginated(
|
|
129
|
+
session: AsyncSession,
|
|
130
|
+
params: PaginationParams
|
|
131
|
+
) -> list[Post]:
|
|
132
|
+
result = await session.execute(
|
|
133
|
+
select(Post)
|
|
134
|
+
.order_by(Post.created_at.desc())
|
|
135
|
+
.limit(params.limit)
|
|
136
|
+
.offset(params.offset)
|
|
137
|
+
)
|
|
138
|
+
return result.scalars().all()
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
### Eager Loading
|
|
142
|
+
|
|
143
|
+
```python
|
|
144
|
+
from sqlalchemy.orm import selectinload
|
|
145
|
+
|
|
146
|
+
# Avoid N+1 queries
|
|
147
|
+
async def get_posts_with_comments(session: AsyncSession):
|
|
148
|
+
result = await session.execute(
|
|
149
|
+
select(Post)
|
|
150
|
+
.options(selectinload(Post.comments))
|
|
151
|
+
)
|
|
152
|
+
return result.scalars().all()
|
|
153
|
+
```
|
|
@@ -1,140 +1,140 @@
|
|
|
1
|
-
# Dependencies
|
|
2
|
-
|
|
3
|
-
## Validation Dependencies
|
|
4
|
-
|
|
5
|
-
Use dependencies for database/service validations:
|
|
6
|
-
|
|
7
|
-
```python
|
|
8
|
-
# src/posts/dependencies.py
|
|
9
|
-
from fastapi import Depends, HTTPException, status
|
|
10
|
-
from pydantic import UUID4
|
|
11
|
-
|
|
12
|
-
async def valid_post_id(post_id: UUID4) -> dict:
|
|
13
|
-
"""Validate post exists and return it."""
|
|
14
|
-
post = await service.get_by_id(post_id)
|
|
15
|
-
if not post:
|
|
16
|
-
raise HTTPException(
|
|
17
|
-
status_code=status.HTTP_404_NOT_FOUND,
|
|
18
|
-
detail="Post not found"
|
|
19
|
-
)
|
|
20
|
-
return post
|
|
21
|
-
|
|
22
|
-
# src/posts/router.py
|
|
23
|
-
@router.get("/posts/{post_id}")
|
|
24
|
-
async def get_post(post: dict = Depends(valid_post_id)):
|
|
25
|
-
return post
|
|
26
|
-
|
|
27
|
-
@router.put("/posts/{post_id}")
|
|
28
|
-
async def update_post(
|
|
29
|
-
update_data: PostUpdate,
|
|
30
|
-
post: dict = Depends(valid_post_id),
|
|
31
|
-
):
|
|
32
|
-
return await service.update(post["id"], update_data)
|
|
33
|
-
```
|
|
34
|
-
|
|
35
|
-
## Chaining Dependencies
|
|
36
|
-
|
|
37
|
-
```python
|
|
38
|
-
# src/auth/dependencies.py
|
|
39
|
-
from fastapi.security import OAuth2PasswordBearer
|
|
40
|
-
|
|
41
|
-
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/token")
|
|
42
|
-
|
|
43
|
-
async def parse_jwt_data(
|
|
44
|
-
token: str = Depends(oauth2_scheme)
|
|
45
|
-
) -> dict:
|
|
46
|
-
try:
|
|
47
|
-
payload = jwt.decode(token, settings.JWT_SECRET, algorithms=[settings.JWT_ALG])
|
|
48
|
-
except JWTError:
|
|
49
|
-
raise HTTPException(status_code=401, detail="Invalid token")
|
|
50
|
-
return {"user_id": payload["sub"]}
|
|
51
|
-
|
|
52
|
-
async def get_current_user(
|
|
53
|
-
token_data: dict = Depends(parse_jwt_data)
|
|
54
|
-
) -> User:
|
|
55
|
-
user = await users_service.get_by_id(token_data["user_id"])
|
|
56
|
-
if not user:
|
|
57
|
-
raise HTTPException(status_code=401, detail="User not found")
|
|
58
|
-
return user
|
|
59
|
-
|
|
60
|
-
async def get_current_active_user(
|
|
61
|
-
user: User = Depends(get_current_user)
|
|
62
|
-
) -> User:
|
|
63
|
-
if not user.is_active:
|
|
64
|
-
raise HTTPException(status_code=403, detail="Inactive user")
|
|
65
|
-
return user
|
|
66
|
-
```
|
|
67
|
-
|
|
68
|
-
## Ownership Validation
|
|
69
|
-
|
|
70
|
-
```python
|
|
71
|
-
async def valid_owned_post(
|
|
72
|
-
post: dict = Depends(valid_post_id),
|
|
73
|
-
user: User = Depends(get_current_user),
|
|
74
|
-
) -> dict:
|
|
75
|
-
if post["creator_id"] != user.id:
|
|
76
|
-
raise HTTPException(status_code=403, detail="Not authorized")
|
|
77
|
-
return post
|
|
78
|
-
|
|
79
|
-
@router.delete("/posts/{post_id}")
|
|
80
|
-
async def delete_post(post: dict = Depends(valid_owned_post)):
|
|
81
|
-
await service.delete(post["id"])
|
|
82
|
-
return {"deleted": True}
|
|
83
|
-
```
|
|
84
|
-
|
|
85
|
-
## Caching Behavior
|
|
86
|
-
|
|
87
|
-
Dependencies are cached within a request. Same dependency = called once:
|
|
88
|
-
|
|
89
|
-
```python
|
|
90
|
-
# parse_jwt_data called only ONCE even though used in multiple deps
|
|
91
|
-
@router.get("/posts/{post_id}")
|
|
92
|
-
async def get_user_post(
|
|
93
|
-
post: dict = Depends(valid_owned_post), # uses parse_jwt_data
|
|
94
|
-
user: User = Depends(get_current_active_user), # also uses parse_jwt_data
|
|
95
|
-
):
|
|
96
|
-
return post
|
|
97
|
-
```
|
|
98
|
-
|
|
99
|
-
## REST Path Variable Consistency
|
|
100
|
-
|
|
101
|
-
Use same path variable names to enable dependency chaining:
|
|
102
|
-
|
|
103
|
-
```python
|
|
104
|
-
# src/profiles/dependencies.py
|
|
105
|
-
async def valid_profile_id(profile_id: UUID4) -> dict:
|
|
106
|
-
profile = await service.get_by_id(profile_id)
|
|
107
|
-
if not profile:
|
|
108
|
-
raise HTTPException(status_code=404, detail="Profile not found")
|
|
109
|
-
return profile
|
|
110
|
-
|
|
111
|
-
# src/creators/dependencies.py
|
|
112
|
-
async def valid_creator_id(
|
|
113
|
-
profile: dict = Depends(valid_profile_id) # chains from profile
|
|
114
|
-
) -> dict:
|
|
115
|
-
if not profile["is_creator"]:
|
|
116
|
-
raise HTTPException(status_code=403, detail="Not a creator")
|
|
117
|
-
return profile
|
|
118
|
-
|
|
119
|
-
# Both use profile_id in path
|
|
120
|
-
@router.get("/profiles/{profile_id}")
|
|
121
|
-
async def get_profile(profile: dict = Depends(valid_profile_id)):
|
|
122
|
-
return profile
|
|
123
|
-
|
|
124
|
-
@router.get("/creators/{profile_id}") # same path var name!
|
|
125
|
-
async def get_creator(creator: dict = Depends(valid_creator_id)):
|
|
126
|
-
return creator
|
|
127
|
-
```
|
|
128
|
-
|
|
129
|
-
## Prefer Async Dependencies
|
|
130
|
-
|
|
131
|
-
```python
|
|
132
|
-
# GOOD - async dependency
|
|
133
|
-
async def get_db_session() -> AsyncGenerator[AsyncSession, None]:
|
|
134
|
-
async with async_session() as session:
|
|
135
|
-
yield session
|
|
136
|
-
|
|
137
|
-
# OK but less efficient - runs in threadpool
|
|
138
|
-
def get_settings() -> Settings:
|
|
139
|
-
return Settings()
|
|
140
|
-
```
|
|
1
|
+
# Dependencies
|
|
2
|
+
|
|
3
|
+
## Validation Dependencies
|
|
4
|
+
|
|
5
|
+
Use dependencies for database/service validations:
|
|
6
|
+
|
|
7
|
+
```python
|
|
8
|
+
# src/posts/dependencies.py
|
|
9
|
+
from fastapi import Depends, HTTPException, status
|
|
10
|
+
from pydantic import UUID4
|
|
11
|
+
|
|
12
|
+
async def valid_post_id(post_id: UUID4) -> dict:
|
|
13
|
+
"""Validate post exists and return it."""
|
|
14
|
+
post = await service.get_by_id(post_id)
|
|
15
|
+
if not post:
|
|
16
|
+
raise HTTPException(
|
|
17
|
+
status_code=status.HTTP_404_NOT_FOUND,
|
|
18
|
+
detail="Post not found"
|
|
19
|
+
)
|
|
20
|
+
return post
|
|
21
|
+
|
|
22
|
+
# src/posts/router.py
|
|
23
|
+
@router.get("/posts/{post_id}")
|
|
24
|
+
async def get_post(post: dict = Depends(valid_post_id)):
|
|
25
|
+
return post
|
|
26
|
+
|
|
27
|
+
@router.put("/posts/{post_id}")
|
|
28
|
+
async def update_post(
|
|
29
|
+
update_data: PostUpdate,
|
|
30
|
+
post: dict = Depends(valid_post_id),
|
|
31
|
+
):
|
|
32
|
+
return await service.update(post["id"], update_data)
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Chaining Dependencies
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
# src/auth/dependencies.py
|
|
39
|
+
from fastapi.security import OAuth2PasswordBearer
|
|
40
|
+
|
|
41
|
+
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/token")
|
|
42
|
+
|
|
43
|
+
async def parse_jwt_data(
|
|
44
|
+
token: str = Depends(oauth2_scheme)
|
|
45
|
+
) -> dict:
|
|
46
|
+
try:
|
|
47
|
+
payload = jwt.decode(token, settings.JWT_SECRET, algorithms=[settings.JWT_ALG])
|
|
48
|
+
except JWTError:
|
|
49
|
+
raise HTTPException(status_code=401, detail="Invalid token")
|
|
50
|
+
return {"user_id": payload["sub"]}
|
|
51
|
+
|
|
52
|
+
async def get_current_user(
|
|
53
|
+
token_data: dict = Depends(parse_jwt_data)
|
|
54
|
+
) -> User:
|
|
55
|
+
user = await users_service.get_by_id(token_data["user_id"])
|
|
56
|
+
if not user:
|
|
57
|
+
raise HTTPException(status_code=401, detail="User not found")
|
|
58
|
+
return user
|
|
59
|
+
|
|
60
|
+
async def get_current_active_user(
|
|
61
|
+
user: User = Depends(get_current_user)
|
|
62
|
+
) -> User:
|
|
63
|
+
if not user.is_active:
|
|
64
|
+
raise HTTPException(status_code=403, detail="Inactive user")
|
|
65
|
+
return user
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## Ownership Validation
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
async def valid_owned_post(
|
|
72
|
+
post: dict = Depends(valid_post_id),
|
|
73
|
+
user: User = Depends(get_current_user),
|
|
74
|
+
) -> dict:
|
|
75
|
+
if post["creator_id"] != user.id:
|
|
76
|
+
raise HTTPException(status_code=403, detail="Not authorized")
|
|
77
|
+
return post
|
|
78
|
+
|
|
79
|
+
@router.delete("/posts/{post_id}")
|
|
80
|
+
async def delete_post(post: dict = Depends(valid_owned_post)):
|
|
81
|
+
await service.delete(post["id"])
|
|
82
|
+
return {"deleted": True}
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## Caching Behavior
|
|
86
|
+
|
|
87
|
+
Dependencies are cached within a request. Same dependency = called once:
|
|
88
|
+
|
|
89
|
+
```python
|
|
90
|
+
# parse_jwt_data called only ONCE even though used in multiple deps
|
|
91
|
+
@router.get("/posts/{post_id}")
|
|
92
|
+
async def get_user_post(
|
|
93
|
+
post: dict = Depends(valid_owned_post), # uses parse_jwt_data
|
|
94
|
+
user: User = Depends(get_current_active_user), # also uses parse_jwt_data
|
|
95
|
+
):
|
|
96
|
+
return post
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
## REST Path Variable Consistency
|
|
100
|
+
|
|
101
|
+
Use same path variable names to enable dependency chaining:
|
|
102
|
+
|
|
103
|
+
```python
|
|
104
|
+
# src/profiles/dependencies.py
|
|
105
|
+
async def valid_profile_id(profile_id: UUID4) -> dict:
|
|
106
|
+
profile = await service.get_by_id(profile_id)
|
|
107
|
+
if not profile:
|
|
108
|
+
raise HTTPException(status_code=404, detail="Profile not found")
|
|
109
|
+
return profile
|
|
110
|
+
|
|
111
|
+
# src/creators/dependencies.py
|
|
112
|
+
async def valid_creator_id(
|
|
113
|
+
profile: dict = Depends(valid_profile_id) # chains from profile
|
|
114
|
+
) -> dict:
|
|
115
|
+
if not profile["is_creator"]:
|
|
116
|
+
raise HTTPException(status_code=403, detail="Not a creator")
|
|
117
|
+
return profile
|
|
118
|
+
|
|
119
|
+
# Both use profile_id in path
|
|
120
|
+
@router.get("/profiles/{profile_id}")
|
|
121
|
+
async def get_profile(profile: dict = Depends(valid_profile_id)):
|
|
122
|
+
return profile
|
|
123
|
+
|
|
124
|
+
@router.get("/creators/{profile_id}") # same path var name!
|
|
125
|
+
async def get_creator(creator: dict = Depends(valid_creator_id)):
|
|
126
|
+
return creator
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
## Prefer Async Dependencies
|
|
130
|
+
|
|
131
|
+
```python
|
|
132
|
+
# GOOD - async dependency
|
|
133
|
+
async def get_db_session() -> AsyncGenerator[AsyncSession, None]:
|
|
134
|
+
async with async_session() as session:
|
|
135
|
+
yield session
|
|
136
|
+
|
|
137
|
+
# OK but less efficient - runs in threadpool
|
|
138
|
+
def get_settings() -> Settings:
|
|
139
|
+
return Settings()
|
|
140
|
+
```
|