mirror of
https://github.com/ae-utbm/sith.git
synced 2025-07-11 04:19:25 +00:00
Add typescript support and automatic openapi client generation from ninja
This commit is contained in:
@ -1,6 +1,7 @@
|
||||
import logging
|
||||
import subprocess
|
||||
from dataclasses import dataclass
|
||||
from hashlib import sha1
|
||||
from pathlib import Path
|
||||
from typing import Iterable
|
||||
|
||||
@ -8,6 +9,7 @@ import rjsmin
|
||||
import sass
|
||||
from django.conf import settings
|
||||
|
||||
from sith.urls import api
|
||||
from staticfiles.apps import GENERATED_ROOT
|
||||
|
||||
|
||||
@ -71,3 +73,38 @@ class JS:
|
||||
minified = rjsmin.jsmin(p.read_text())
|
||||
p.write_text(minified)
|
||||
logging.getLogger("main").info(f"Minified {path}")
|
||||
|
||||
|
||||
class OpenApi:
|
||||
OPENAPI_DIR = GENERATED_ROOT / "openapi"
|
||||
|
||||
@classmethod
|
||||
def compile(cls):
|
||||
"""Compile a typescript client for the sith API. Only generates it if it changed"""
|
||||
logging.getLogger("django").info("Compiling open api typescript client")
|
||||
out = cls.OPENAPI_DIR / "schema.json"
|
||||
cls.OPENAPI_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
old_hash = ""
|
||||
if out.exists():
|
||||
with open(out, "rb") as f:
|
||||
old_hash = sha1(f.read()).hexdigest()
|
||||
|
||||
schema = api.get_openapi_schema()
|
||||
# Remove hash from operationIds
|
||||
# This is done for cache invalidation but this is too aggressive
|
||||
for path in schema["paths"].values():
|
||||
for action, desc in path.items():
|
||||
path[action]["operationId"] = "_".join(
|
||||
desc["operationId"].split("_")[:-1]
|
||||
)
|
||||
schema = str(schema)
|
||||
|
||||
if old_hash == sha1(schema.encode("utf-8")).hexdigest():
|
||||
logging.getLogger("django").info("✨ Api did not change, nothing to do ✨")
|
||||
return
|
||||
|
||||
with open(out, "w") as f:
|
||||
_ = f.write(schema)
|
||||
|
||||
subprocess.run(["npx", "openapi-ts"]).check_returncode()
|
||||
|
Reference in New Issue
Block a user