Skip to content

Commit

Permalink
feat: upgrade litestar-vite
Browse files Browse the repository at this point in the history
  • Loading branch information
cofin committed Dec 10, 2023
1 parent 43db2c4 commit b49a96a
Show file tree
Hide file tree
Showing 13 changed files with 991 additions and 645 deletions.
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ repos:
- id: mixed-line-ending
- id: trailing-whitespace
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: "v0.1.6"
rev: "v0.1.7"
hooks:
- id: ruff
args: ["--fix"]
Expand All @@ -25,7 +25,7 @@ repos:
hooks:
- id: blacken-docs
- repo: https://github.com/pre-commit/mirrors-prettier
rev: "v3.1.0"
rev: "v4.0.0-alpha.4"
hooks:
- id: prettier
exclude: "_templates"
Expand Down
8 changes: 4 additions & 4 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.codeActionsOnSave": {
"source.fixAll": true,
"source.fixAll.eslint": true
"source.fixAll": "explicit",
"source.fixAll.eslint": "explicit"
},
"python.defaultInterpreterPath": ".venv/bin/python",
"python.linting.banditEnabled": false,
Expand All @@ -48,8 +48,8 @@
"editor.formatOnSave": true,
"editor.defaultFormatter": "ms-python.black-formatter",
"editor.codeActionsOnSave": {
"source.organizeImports": false,
"source.fixAll": true
"source.organizeImports": "never",
"source.fixAll": "explicit"
}
},
"eslint.alwaysShowStatus": true,
Expand Down
778 changes: 558 additions & 220 deletions package-lock.json

Large diffs are not rendered by default.

16 changes: 8 additions & 8 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
{
"name": "litestar-fullstack",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vue-tsc && vite build",
"preview": "vite preview"
},
"dependencies": {
"vue": "^3.2.45"
},
"dependencies": {},
"devDependencies": {
"@types/node": "^18.14.0",
"@vitejs/plugin-vue": "^4.0.0",
"typescript": "^4.9.3",
"vite": "^4.1.0",
"vue-tsc": "^1.0.24"
"litestar-vite-plugin": "^0.3.0",
"typescript": "^5.3.3",
"vite": "^5.0.6",
"vue": "^3.3.11",
"vue-tsc": "^1.8.25",
"axios": "^1.6.2",
"@types/node": "^20.10.3"
}
}
620 changes: 388 additions & 232 deletions pdm.lock

Large diffs are not rendered by default.

7 changes: 2 additions & 5 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,13 @@ classifiers = [
"Typing :: Typed",
]
dependencies = [
"litestar[cli,jinja,jwt,pydantic,redis,structlog]",
"litestar[cli,jinja,jwt,pydantic,redis,structlog,sqlalchemy,standard]",
"pydantic-settings>=2.0.3",
"advanced-alchemy>=0.4.0",
"asyncpg>=0.28.0",
"python-dotenv>=1.0.0",
"uvicorn[standard]>=0.23.2",
"passlib[argon2]>=1.7.4",
"greenlet; sys_platform == \"darwin\"",
"litestar-saq>=0.1.3",
"litestar-vite>=0.1.2",
"litestar-vite>=0.1.4",
"litestar-aiosql>=0.1.1",
]
description = "Opinionated template for a Litestar application."
Expand Down
34 changes: 6 additions & 28 deletions src/app/cli.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
from __future__ import annotations

import multiprocessing
import subprocess
import sys
from typing import Any
from typing import TYPE_CHECKING, Any

import anyio
import click
from anyio import open_process
from anyio.streams.text import TextReceiveStream
from litestar import Litestar
from pydantic import EmailStr
from rich import get_console

from app.domain import plugins
from app.domain.accounts.dtos import UserCreate, UserUpdate
from app.domain.accounts.services import UserService
from app.lib import log, settings

if TYPE_CHECKING:
from litestar import Litestar

__all__ = [
"create_user",
"run_all_app",
Expand Down Expand Up @@ -115,11 +116,6 @@ def run_all_app(
)
worker_process.start()

if settings.app.DEV_MODE:
logger.info("starting Vite")
vite_process = multiprocessing.Process(target=run_vite)
vite_process.start()

logger.info("Starting HTTP Server.")
reload_dirs = settings.server.RELOAD_DIRS if settings.server.RELOAD else None
process_args = {
Expand Down Expand Up @@ -258,21 +254,3 @@ def _convert_uvicorn_args(args: dict[str, Any]) -> list[str]:
process_args.append(f"--{arg}={value}")

return process_args


def run_vite() -> None:
"""Run Vite in a subprocess."""
try:
anyio.run(_run_vite, backend="asyncio", backend_options={"use_uvloop": True})
except KeyboardInterrupt:
logger.info("Stopping typescript development services.")
finally:
logger.info("Vite Service stopped.")


async def _run_vite() -> None:
"""Run Vite in a subprocess."""
log.config.configure()
async with await open_process(plugins.vite._config.run_command) as vite_process:
async for text in TextReceiveStream(vite_process.stdout): # type: ignore[arg-type]
await logger.ainfo("Vite", message=text.replace("\n", ""))
7 changes: 5 additions & 2 deletions src/app/domain/plugins.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from pathlib import Path

from litestar.contrib.pydantic import PydanticPlugin
from litestar_aiosql import AiosqlConfig, AiosqlPlugin
from litestar_saq import CronJob, QueueConfig, SAQConfig, SAQPlugin
Expand All @@ -9,10 +11,11 @@
aiosql = AiosqlPlugin(config=AiosqlConfig())
vite = VitePlugin(
config=ViteConfig(
static_dir=settings.STATIC_DIR,
bundle_dir=settings.STATIC_DIR,
resource_dir=settings.RESOURCES_DIR,
assets_dir=Path(settings.RESOURCES_DIR / "assets"),
templates_dir=settings.TEMPLATES_DIR,
hot_reload=settings.app.DEV_MODE,
port=3005,
),
)
saq = SAQPlugin(
Expand Down
5 changes: 1 addition & 4 deletions src/app/lib/db/__init__.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,18 @@
"""Core DB Package."""
from __future__ import annotations

from app.lib.db import orm, utils
from app.lib.db import orm
from app.lib.db.base import (
async_session_factory,
config,
engine,
plugin,
session,
)

__all__ = [
"utils",
"config",
"plugin",
"engine",
"session",
"async_session_factory",
"orm",
]
17 changes: 0 additions & 17 deletions src/app/lib/db/base.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from __future__ import annotations

from contextlib import asynccontextmanager
from typing import TYPE_CHECKING, Any

from advanced_alchemy.config import AlembicAsyncConfig
Expand All @@ -13,12 +12,7 @@

from app.lib import constants, serialization, settings

__all__ = ["session"]


if TYPE_CHECKING:
from collections.abc import AsyncIterator

from sqlalchemy.ext.asyncio import AsyncSession

engine = create_async_engine(
Expand Down Expand Up @@ -97,14 +91,3 @@ def decoder(bin_value: bytes) -> Any:


plugin = SQLAlchemyInitPlugin(config=config)


@asynccontextmanager
async def session() -> AsyncIterator[AsyncSession]:
"""Use this to get a database session where you can't in litestar.
Returns:
AsyncIterator[AsyncSession]
"""
async with async_session_factory() as session:
yield session
76 changes: 0 additions & 76 deletions src/app/lib/db/utils.py

This file was deleted.

1 change: 1 addition & 0 deletions src/app/lib/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@

DEFAULT_MODULE_NAME = "app"
BASE_DIR: Final = utils.module_to_os_path(DEFAULT_MODULE_NAME)
RESOURCES_DIR = Path(BASE_DIR / "domain" / "web" / "resources")
STATIC_DIR = Path(BASE_DIR / "domain" / "web" / "public")
TEMPLATES_DIR = Path(BASE_DIR / "domain" / "web" / "templates")
version = importlib.metadata.version(DEFAULT_MODULE_NAME)
Expand Down
63 changes: 16 additions & 47 deletions vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,59 +2,28 @@ import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import path from "path";

function getBackendUrl(path: string) {
return `${process.env.FRONTEND_URL || "http://localhost:8000"}${path}`;
}
const STATIC_URL = process.env.STATIC_URL || "/static/";
import litestar from "litestar-vite-plugin";

const ASSET_URL = process.env.STATIC_URL || "/static/";
export default defineConfig({
base: `${STATIC_URL}`,
root: path.join(__dirname, "src/app/domain/web/resources"),
optimizeDeps: {
force: true,
},
base: `${ASSET_URL}`,
root: "src/app/domain/web",
server: {
fs: {
allow: [".", path.join(__dirname, "node_modules")],
},
host: "0.0.0.0",
port: 3005,
cors: true,
strictPort: true,
watch: {
ignored: ["node_modules", ".venv", "**/__pycache__/**"],
},
proxy: {
"/api": {
target: getBackendUrl("/api"),
changeOrigin: true,
ws: true,
rewrite: (path) => path.replace(/^\/api/, ""),
},
},
},

plugins: [vue()],
build: {
target: "esnext",
outDir: "../public",
emptyOutDir: true,
assetsDir: "assets/",
manifest: true,
rollupOptions: {
input: path.join(__dirname, "src/app/domain/web/resources/main.ts"),
output: {
manualChunks(id) {
if (id.includes("node_modules")) {
return id
.toString()
.split("node_modules/")[1]
.split("/")[0]
.toString();
}
},
},
},
},
plugins: [
vue(),
litestar({
input: ["src/app/domain/web/resources/main.ts"],
assetUrl: `${ASSET_URL}`,
assetDirectory: "resources/assets",
bundleDirectory: "public",
resourceDirectory: "resources",
hotFile: "src/app/domain/web/public/hot",
}),
],
resolve: {
alias: {
"@": path.resolve(__dirname, "src/app/domain/web/resources"),
Expand Down

0 comments on commit b49a96a

Please sign in to comment.