django-cfg 1.4.108__py3-none-any.whl → 1.4.110__py3-none-any.whl
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.
- django_cfg/__init__.py +1 -1
- django_cfg/modules/django_admin/__init__.py +6 -0
- django_cfg/modules/django_admin/base/pydantic_admin.py +91 -0
- django_cfg/modules/django_admin/config/__init__.py +5 -0
- django_cfg/modules/django_admin/config/admin_config.py +7 -0
- django_cfg/modules/django_admin/config/documentation_config.py +406 -0
- django_cfg/modules/django_admin/config/field_config.py +87 -0
- django_cfg/modules/django_admin/templates/django_admin/change_form_docs.html +23 -0
- django_cfg/modules/django_admin/templates/django_admin/change_list_docs.html +23 -0
- django_cfg/modules/django_admin/templates/django_admin/documentation_block.html +297 -0
- django_cfg/modules/django_admin/templates/django_admin/markdown_docs_block.html +37 -0
- django_cfg/modules/django_admin/utils/__init__.py +3 -0
- django_cfg/modules/django_admin/utils/html_builder.py +94 -1
- django_cfg/modules/django_admin/utils/markdown_renderer.py +344 -0
- django_cfg/pyproject.toml +2 -2
- django_cfg/static/frontend/admin.zip +0 -0
- {django_cfg-1.4.108.dist-info → django_cfg-1.4.110.dist-info}/METADATA +2 -1
- {django_cfg-1.4.108.dist-info → django_cfg-1.4.110.dist-info}/RECORD +21 -28
- django_cfg/modules/django_admin/CHANGELOG_CODE_METHODS.md +0 -153
- django_cfg/modules/django_admin/IMPORT_EXPORT_FIX.md +0 -72
- django_cfg/modules/django_admin/RESOURCE_CONFIG_ENHANCEMENT.md +0 -350
- django_cfg/modules/django_client/system/__init__.py +0 -24
- django_cfg/modules/django_client/system/base_generator.py +0 -123
- django_cfg/modules/django_client/system/generate_mjs_clients.py +0 -176
- django_cfg/modules/django_client/system/mjs_generator.py +0 -219
- django_cfg/modules/django_client/system/schema_parser.py +0 -199
- django_cfg/modules/django_client/system/templates/api_client.js.j2 +0 -87
- django_cfg/modules/django_client/system/templates/app_index.js.j2 +0 -13
- django_cfg/modules/django_client/system/templates/base_client.js.j2 +0 -166
- django_cfg/modules/django_client/system/templates/main_index.js.j2 +0 -80
- django_cfg/modules/django_client/system/templates/types.js.j2 +0 -24
- {django_cfg-1.4.108.dist-info → django_cfg-1.4.110.dist-info}/WHEEL +0 -0
- {django_cfg-1.4.108.dist-info → django_cfg-1.4.110.dist-info}/entry_points.txt +0 -0
- {django_cfg-1.4.108.dist-info → django_cfg-1.4.110.dist-info}/licenses/LICENSE +0 -0
|
@@ -1,176 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env python3
|
|
2
|
-
"""
|
|
3
|
-
Script to generate lightweight MJS (ES Module) clients for django-cfg project.
|
|
4
|
-
|
|
5
|
-
This script generates JavaScript ES modules with JSDoc type annotations
|
|
6
|
-
organized by Django apps for use in Django HTML templates.
|
|
7
|
-
|
|
8
|
-
Usage:
|
|
9
|
-
poetry run python src/django_cfg/modules/django_client/system/generate_mjs_clients.py
|
|
10
|
-
poetry run python src/django_cfg/modules/django_client/system/generate_mjs_clients.py --clean
|
|
11
|
-
"""
|
|
12
|
-
|
|
13
|
-
import argparse
|
|
14
|
-
import os
|
|
15
|
-
import shutil
|
|
16
|
-
import subprocess
|
|
17
|
-
import sys
|
|
18
|
-
from pathlib import Path
|
|
19
|
-
|
|
20
|
-
# Add current directory to path for imports
|
|
21
|
-
sys.path.insert(0, str(Path(__file__).parent))
|
|
22
|
-
|
|
23
|
-
from mjs_generator import MJSGenerator
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
def main():
|
|
27
|
-
"""Main function to generate MJS clients."""
|
|
28
|
-
|
|
29
|
-
parser = argparse.ArgumentParser(
|
|
30
|
-
description='Generate MJS API clients with JSDoc types for django-cfg project'
|
|
31
|
-
)
|
|
32
|
-
parser.add_argument(
|
|
33
|
-
'--clean',
|
|
34
|
-
action='store_true',
|
|
35
|
-
help='Clean existing files before generation'
|
|
36
|
-
)
|
|
37
|
-
parser.add_argument(
|
|
38
|
-
'--schema',
|
|
39
|
-
type=str,
|
|
40
|
-
help='Path to OpenAPI schema file (YAML or JSON)'
|
|
41
|
-
)
|
|
42
|
-
parser.add_argument(
|
|
43
|
-
'--output',
|
|
44
|
-
type=str,
|
|
45
|
-
help='Output directory for generated clients'
|
|
46
|
-
)
|
|
47
|
-
|
|
48
|
-
args = parser.parse_args()
|
|
49
|
-
|
|
50
|
-
# Determine paths
|
|
51
|
-
script_dir = Path(__file__).parent
|
|
52
|
-
django_client_dir = script_dir.parent # django_client module
|
|
53
|
-
modules_dir = django_client_dir.parent # modules
|
|
54
|
-
django_cfg_dir = modules_dir.parent # django_cfg
|
|
55
|
-
src_dir = django_cfg_dir.parent # src
|
|
56
|
-
dev_dir = src_dir.parent # django-cfg-dev
|
|
57
|
-
projects_dir = dev_dir.parent # projects
|
|
58
|
-
root_dir = projects_dir.parent # root (django-cfg)
|
|
59
|
-
example_django_dir = root_dir / "solution" / "projects" / "django"
|
|
60
|
-
|
|
61
|
-
# Output directory for MJS clients
|
|
62
|
-
if args.output:
|
|
63
|
-
mjs_output_dir = Path(args.output)
|
|
64
|
-
else:
|
|
65
|
-
mjs_output_dir = django_cfg_dir / "static" / "js" / "api"
|
|
66
|
-
|
|
67
|
-
# Schema location
|
|
68
|
-
if args.schema:
|
|
69
|
-
schema_path = Path(args.schema)
|
|
70
|
-
else:
|
|
71
|
-
schema_path = example_django_dir / "openapi" / "schemas" / "cfg.yaml"
|
|
72
|
-
|
|
73
|
-
print("🚀 Generating MJS API clients with JSDoc type annotations...")
|
|
74
|
-
print(f"📁 Schema: {schema_path}")
|
|
75
|
-
print(f"📁 Output: {mjs_output_dir}")
|
|
76
|
-
|
|
77
|
-
# Generate schema if it doesn't exist
|
|
78
|
-
if not schema_path.exists():
|
|
79
|
-
print("⚙️ Generating OpenAPI schema first...")
|
|
80
|
-
os.chdir(example_django_dir)
|
|
81
|
-
|
|
82
|
-
result = subprocess.run(
|
|
83
|
-
["poetry", "run", "python", "manage.py", "generate_client", "--typescript", "--no-python"],
|
|
84
|
-
capture_output=True,
|
|
85
|
-
text=True
|
|
86
|
-
)
|
|
87
|
-
|
|
88
|
-
if result.returncode != 0 or not schema_path.exists():
|
|
89
|
-
print("❌ Error: Could not generate schema")
|
|
90
|
-
print(result.stderr)
|
|
91
|
-
sys.exit(1)
|
|
92
|
-
|
|
93
|
-
# Check for dependencies
|
|
94
|
-
try:
|
|
95
|
-
import yaml
|
|
96
|
-
except ImportError:
|
|
97
|
-
print("❌ PyYAML is required. Install with: pip install pyyaml")
|
|
98
|
-
sys.exit(1)
|
|
99
|
-
|
|
100
|
-
try:
|
|
101
|
-
import jinja2
|
|
102
|
-
except ImportError:
|
|
103
|
-
print("❌ Jinja2 is required. Install with: pip install jinja2")
|
|
104
|
-
sys.exit(1)
|
|
105
|
-
|
|
106
|
-
# Generate MJS clients
|
|
107
|
-
try:
|
|
108
|
-
generator = MJSGenerator(schema_path, mjs_output_dir)
|
|
109
|
-
file_count = generator.generate()
|
|
110
|
-
|
|
111
|
-
print("\n✅ MJS clients generated successfully!")
|
|
112
|
-
print(f"📊 Generated {file_count} files in {mjs_output_dir}")
|
|
113
|
-
print("📂 Structure: Organized by Django apps with JSDoc types")
|
|
114
|
-
|
|
115
|
-
# Clean up openapi directory if it was created
|
|
116
|
-
openapi_dir = example_django_dir / "openapi"
|
|
117
|
-
if openapi_dir.exists():
|
|
118
|
-
print(f"🧹 Cleaning up example project openapi directory: {openapi_dir}")
|
|
119
|
-
shutil.rmtree(openapi_dir)
|
|
120
|
-
|
|
121
|
-
print("\n📝 Usage examples in Django template:")
|
|
122
|
-
print("""
|
|
123
|
-
<!-- Import from app folder with type support -->
|
|
124
|
-
<script type="module">
|
|
125
|
-
// Your IDE will provide autocomplete and type hints!
|
|
126
|
-
import { tasksAPI } from '{% static "api/tasks/index.mjs" %}';
|
|
127
|
-
|
|
128
|
-
async function loadTaskStats() {
|
|
129
|
-
try {
|
|
130
|
-
// IDE knows the return type from JSDoc annotations
|
|
131
|
-
const stats = await tasksAPI.cfgTasksApiTasksStatsRetrieve();
|
|
132
|
-
console.log('Task Stats:', stats);
|
|
133
|
-
} catch (error) {
|
|
134
|
-
// APIError type is documented
|
|
135
|
-
console.error('Error:', error);
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
loadTaskStats();
|
|
140
|
-
</script>
|
|
141
|
-
|
|
142
|
-
<!-- Import multiple APIs from main index -->
|
|
143
|
-
<script type="module">
|
|
144
|
-
import { tasksAPI, paymentsAPI } from '{% static "api/index.mjs" %}';
|
|
145
|
-
|
|
146
|
-
// Both APIs have full JSDoc documentation
|
|
147
|
-
const tasks = await tasksAPI.cfgTasksApiTasksStatsRetrieve();
|
|
148
|
-
const webhooks = await paymentsAPI.cfgPaymentsWebhooksHealthRetrieve();
|
|
149
|
-
</script>
|
|
150
|
-
|
|
151
|
-
<!-- Use with custom base URL -->
|
|
152
|
-
<script type="module">
|
|
153
|
-
import { TasksAPI } from '{% static "api/tasks/index.mjs" %}';
|
|
154
|
-
|
|
155
|
-
// Constructor is documented with JSDoc
|
|
156
|
-
const api = new TasksAPI('https://api.example.com');
|
|
157
|
-
const stats = await api.cfgTasksApiTasksStatsRetrieve();
|
|
158
|
-
</script>
|
|
159
|
-
""")
|
|
160
|
-
|
|
161
|
-
print("\n🎯 Benefits of JSDoc types:")
|
|
162
|
-
print(" • IDE autocomplete and IntelliSense")
|
|
163
|
-
print(" • Type checking in VS Code and other editors")
|
|
164
|
-
print(" • Inline documentation in your editor")
|
|
165
|
-
print(" • Works with TypeScript if needed")
|
|
166
|
-
print(" • No build step required!")
|
|
167
|
-
|
|
168
|
-
except Exception as e:
|
|
169
|
-
print(f"❌ Error: {e}")
|
|
170
|
-
import traceback
|
|
171
|
-
traceback.print_exc()
|
|
172
|
-
sys.exit(1)
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
if __name__ == '__main__':
|
|
176
|
-
main()
|
|
@@ -1,219 +0,0 @@
|
|
|
1
|
-
"""
|
|
2
|
-
MJS (ES Module) client generator for Django CFG.
|
|
3
|
-
Generates JavaScript modules with JSDoc type annotations.
|
|
4
|
-
"""
|
|
5
|
-
|
|
6
|
-
import shutil
|
|
7
|
-
from pathlib import Path
|
|
8
|
-
from typing import Any, Dict, List
|
|
9
|
-
|
|
10
|
-
from base_generator import BaseGenerator
|
|
11
|
-
from schema_parser import SchemaParser
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
class MJSGenerator(BaseGenerator):
|
|
15
|
-
"""Generate MJS API clients with JSDoc type annotations."""
|
|
16
|
-
|
|
17
|
-
def __init__(self, schema_path: Path, output_dir: Path):
|
|
18
|
-
"""Initialize the MJS generator."""
|
|
19
|
-
super().__init__(schema_path, output_dir)
|
|
20
|
-
self.parser = SchemaParser(self.schema)
|
|
21
|
-
|
|
22
|
-
def generate(self) -> int:
|
|
23
|
-
"""Generate all MJS client files organized by apps."""
|
|
24
|
-
# Clean and create output directory
|
|
25
|
-
if self.output_dir.exists():
|
|
26
|
-
shutil.rmtree(self.output_dir)
|
|
27
|
-
self.output_dir.mkdir(parents=True, exist_ok=True)
|
|
28
|
-
|
|
29
|
-
# Generate base client
|
|
30
|
-
self._generate_base_client()
|
|
31
|
-
|
|
32
|
-
# Generate type definitions
|
|
33
|
-
self._generate_types()
|
|
34
|
-
|
|
35
|
-
# Group operations by app
|
|
36
|
-
operations_by_app = self.parser.group_operations_by_app()
|
|
37
|
-
|
|
38
|
-
# Generate client for each app
|
|
39
|
-
generated_apps = []
|
|
40
|
-
for app_name, operations in sorted(operations_by_app.items()):
|
|
41
|
-
# Skip certain apps
|
|
42
|
-
if app_name in ['default', 'endpoints', 'health']:
|
|
43
|
-
continue
|
|
44
|
-
|
|
45
|
-
self._generate_app_client(app_name, operations)
|
|
46
|
-
generated_apps.append(app_name)
|
|
47
|
-
|
|
48
|
-
# Generate main index file
|
|
49
|
-
self._generate_main_index(generated_apps)
|
|
50
|
-
|
|
51
|
-
# Count generated files
|
|
52
|
-
file_count = len(generated_apps) * 2 + 3 # apps * (client + index) + base + types + main index
|
|
53
|
-
return file_count
|
|
54
|
-
|
|
55
|
-
def _generate_base_client(self):
|
|
56
|
-
"""Generate the base API client class."""
|
|
57
|
-
content = self.render_template('base_client.js.j2')
|
|
58
|
-
|
|
59
|
-
base_file = self.output_dir / 'base.mjs'
|
|
60
|
-
base_file.write_text(content)
|
|
61
|
-
print(f" ✅ Generated: {base_file}")
|
|
62
|
-
|
|
63
|
-
def _generate_types(self):
|
|
64
|
-
"""Generate type definitions from schema components."""
|
|
65
|
-
# Extract all schema definitions
|
|
66
|
-
schemas = self.schema.get('components', {}).get('schemas', {})
|
|
67
|
-
|
|
68
|
-
# Convert schemas to JSDoc typedef format
|
|
69
|
-
typedefs = []
|
|
70
|
-
for schema_name, schema_def in schemas.items():
|
|
71
|
-
typedef = self._schema_to_typedef(schema_name, schema_def)
|
|
72
|
-
if typedef:
|
|
73
|
-
typedefs.append(typedef)
|
|
74
|
-
|
|
75
|
-
content = self.render_template('types.js.j2', typedefs=typedefs)
|
|
76
|
-
|
|
77
|
-
types_file = self.output_dir / 'types.mjs'
|
|
78
|
-
types_file.write_text(content)
|
|
79
|
-
print(f" ✅ Generated: {types_file}")
|
|
80
|
-
|
|
81
|
-
def _schema_to_typedef(self, name: str, schema: Dict[str, Any]) -> Dict[str, Any]:
|
|
82
|
-
"""Convert an OpenAPI schema to a JSDoc typedef."""
|
|
83
|
-
if schema.get('type') != 'object':
|
|
84
|
-
return None
|
|
85
|
-
|
|
86
|
-
properties = []
|
|
87
|
-
required_props = schema.get('required', [])
|
|
88
|
-
|
|
89
|
-
for prop_name, prop_schema in schema.get('properties', {}).items():
|
|
90
|
-
prop_type = self.parser.get_js_type(prop_schema)
|
|
91
|
-
is_required = prop_name in required_props
|
|
92
|
-
|
|
93
|
-
properties.append({
|
|
94
|
-
'name': prop_name,
|
|
95
|
-
'type': prop_type,
|
|
96
|
-
'required': is_required,
|
|
97
|
-
'description': prop_schema.get('description', '')
|
|
98
|
-
})
|
|
99
|
-
|
|
100
|
-
return {
|
|
101
|
-
'name': name,
|
|
102
|
-
'description': schema.get('description', ''),
|
|
103
|
-
'properties': properties
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
def _generate_app_client(self, app_name: str, operations: List[Dict]):
|
|
107
|
-
"""Generate client files for a specific app."""
|
|
108
|
-
# Create app directory
|
|
109
|
-
app_dir = self.output_dir / app_name
|
|
110
|
-
app_dir.mkdir(parents=True, exist_ok=True)
|
|
111
|
-
|
|
112
|
-
# Prepare operations data
|
|
113
|
-
methods = []
|
|
114
|
-
for op in operations:
|
|
115
|
-
method_data = self._prepare_method_data(op)
|
|
116
|
-
if method_data:
|
|
117
|
-
methods.append(method_data)
|
|
118
|
-
|
|
119
|
-
# Generate client file
|
|
120
|
-
class_name = self.to_pascal_case(app_name) + 'API'
|
|
121
|
-
instance_name = self.to_camel_case(app_name) + 'API'
|
|
122
|
-
|
|
123
|
-
content = self.render_template(
|
|
124
|
-
'api_client.js.j2',
|
|
125
|
-
app_name=app_name,
|
|
126
|
-
class_name=class_name,
|
|
127
|
-
instance_name=instance_name,
|
|
128
|
-
methods=methods
|
|
129
|
-
)
|
|
130
|
-
|
|
131
|
-
client_file = app_dir / 'client.mjs'
|
|
132
|
-
client_file.write_text(content)
|
|
133
|
-
print(f" ✅ Generated: {client_file}")
|
|
134
|
-
|
|
135
|
-
# Generate app index
|
|
136
|
-
index_content = self.render_template(
|
|
137
|
-
'app_index.js.j2',
|
|
138
|
-
app_name=app_name,
|
|
139
|
-
class_name=class_name,
|
|
140
|
-
instance_name=instance_name
|
|
141
|
-
)
|
|
142
|
-
|
|
143
|
-
index_file = app_dir / 'index.mjs'
|
|
144
|
-
index_file.write_text(index_content)
|
|
145
|
-
print(f" ✅ Generated: {index_file}")
|
|
146
|
-
|
|
147
|
-
def _prepare_method_data(self, operation: Dict[str, Any]) -> Dict[str, Any]:
|
|
148
|
-
"""Prepare method data for template rendering."""
|
|
149
|
-
operation_id = operation.get('operationId', '')
|
|
150
|
-
if not operation_id:
|
|
151
|
-
return None
|
|
152
|
-
|
|
153
|
-
method_name = self.parser.extract_method_name(operation_id)
|
|
154
|
-
method_name = self.to_camel_case(method_name)
|
|
155
|
-
|
|
156
|
-
# Extract parameters
|
|
157
|
-
path_params = []
|
|
158
|
-
query_params = []
|
|
159
|
-
|
|
160
|
-
for param in operation.get('parameters', []):
|
|
161
|
-
param_info = self.parser.extract_parameter_info(param)
|
|
162
|
-
|
|
163
|
-
if param_info['in'] == 'path':
|
|
164
|
-
path_params.append(param_info)
|
|
165
|
-
elif param_info['in'] == 'query':
|
|
166
|
-
query_params.append(param_info)
|
|
167
|
-
|
|
168
|
-
# Extract request body
|
|
169
|
-
request_body = self.parser.extract_request_body_info(
|
|
170
|
-
operation.get('requestBody')
|
|
171
|
-
)
|
|
172
|
-
|
|
173
|
-
# Extract response type
|
|
174
|
-
response_type = self.parser.get_response_type(
|
|
175
|
-
operation.get('responses', {})
|
|
176
|
-
)
|
|
177
|
-
|
|
178
|
-
# Build path with template literals
|
|
179
|
-
api_path = operation['path']
|
|
180
|
-
for param in path_params:
|
|
181
|
-
api_path = api_path.replace(
|
|
182
|
-
f"{{{param['name']}}}",
|
|
183
|
-
f"${{{param['name']}}}"
|
|
184
|
-
)
|
|
185
|
-
|
|
186
|
-
return {
|
|
187
|
-
'name': method_name,
|
|
188
|
-
'http_method': operation['method'].upper(),
|
|
189
|
-
'path': api_path,
|
|
190
|
-
'summary': operation.get('summary', ''),
|
|
191
|
-
'description': operation.get('description', ''),
|
|
192
|
-
'path_params': path_params,
|
|
193
|
-
'query_params': query_params,
|
|
194
|
-
'request_body': request_body,
|
|
195
|
-
'response_type': response_type
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
def _generate_main_index(self, apps: List[str]):
|
|
199
|
-
"""Generate the main index file."""
|
|
200
|
-
# Prepare app data for template
|
|
201
|
-
app_imports = []
|
|
202
|
-
for app_name in sorted(apps):
|
|
203
|
-
class_name = self.to_pascal_case(app_name) + 'API'
|
|
204
|
-
instance_name = self.to_camel_case(app_name) + 'API'
|
|
205
|
-
|
|
206
|
-
app_imports.append({
|
|
207
|
-
'app_name': app_name,
|
|
208
|
-
'class_name': class_name,
|
|
209
|
-
'instance_name': instance_name
|
|
210
|
-
})
|
|
211
|
-
|
|
212
|
-
content = self.render_template(
|
|
213
|
-
'main_index.js.j2',
|
|
214
|
-
apps=app_imports
|
|
215
|
-
)
|
|
216
|
-
|
|
217
|
-
index_file = self.output_dir / 'index.mjs'
|
|
218
|
-
index_file.write_text(content)
|
|
219
|
-
print(f" ✅ Generated: {index_file}")
|
|
@@ -1,199 +0,0 @@
|
|
|
1
|
-
"""
|
|
2
|
-
OpenAPI schema parser for extracting operation and type information.
|
|
3
|
-
"""
|
|
4
|
-
|
|
5
|
-
import re
|
|
6
|
-
from typing import Any, Dict, List, Optional
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
class SchemaParser:
|
|
10
|
-
"""Parse OpenAPI schema to extract operation and type information."""
|
|
11
|
-
|
|
12
|
-
def __init__(self, schema: Dict[str, Any]):
|
|
13
|
-
"""Initialize with OpenAPI schema."""
|
|
14
|
-
self.schema = schema
|
|
15
|
-
self.components = schema.get('components', {})
|
|
16
|
-
self.schemas = self.components.get('schemas', {})
|
|
17
|
-
|
|
18
|
-
def extract_app_from_path(self, path: str) -> str:
|
|
19
|
-
"""Extract app name from API path."""
|
|
20
|
-
# Pattern: /cfg/{app_name}/...
|
|
21
|
-
match = re.match(r'/cfg/([^/]+)/', path)
|
|
22
|
-
if match:
|
|
23
|
-
return match.group(1)
|
|
24
|
-
return 'core' # Default for paths without clear app
|
|
25
|
-
|
|
26
|
-
def extract_method_name(self, operation_id: str) -> str:
|
|
27
|
-
"""Extract clean method name from operation ID."""
|
|
28
|
-
# Remove common prefixes
|
|
29
|
-
for prefix in ['cfg__', 'api_', 'cfg_']:
|
|
30
|
-
if operation_id.startswith(prefix):
|
|
31
|
-
operation_id = operation_id[len(prefix):]
|
|
32
|
-
|
|
33
|
-
# Handle double underscores
|
|
34
|
-
operation_id = operation_id.replace('__', '_')
|
|
35
|
-
|
|
36
|
-
return operation_id
|
|
37
|
-
|
|
38
|
-
def group_operations_by_app(self) -> Dict[str, List[Dict]]:
|
|
39
|
-
"""Group API operations by Django app based on path patterns."""
|
|
40
|
-
grouped = {}
|
|
41
|
-
|
|
42
|
-
for path, path_item in self.schema.get('paths', {}).items():
|
|
43
|
-
for method, operation in path_item.items():
|
|
44
|
-
if method in ['get', 'post', 'put', 'patch', 'delete']:
|
|
45
|
-
# Extract app name from path
|
|
46
|
-
app_name = self.extract_app_from_path(path)
|
|
47
|
-
|
|
48
|
-
# Add operation info
|
|
49
|
-
op_info = {
|
|
50
|
-
'path': path,
|
|
51
|
-
'method': method,
|
|
52
|
-
'operationId': operation.get('operationId', ''),
|
|
53
|
-
'summary': operation.get('summary', ''),
|
|
54
|
-
'description': operation.get('description', ''),
|
|
55
|
-
'parameters': operation.get('parameters', []),
|
|
56
|
-
'requestBody': operation.get('requestBody'),
|
|
57
|
-
'responses': operation.get('responses', {}),
|
|
58
|
-
'tags': operation.get('tags', [])
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
if app_name not in grouped:
|
|
62
|
-
grouped[app_name] = []
|
|
63
|
-
grouped[app_name].append(op_info)
|
|
64
|
-
|
|
65
|
-
return grouped
|
|
66
|
-
|
|
67
|
-
def extract_parameter_info(self, parameter: Dict[str, Any]) -> Dict[str, Any]:
|
|
68
|
-
"""Extract detailed parameter information."""
|
|
69
|
-
param_info = {
|
|
70
|
-
'name': parameter.get('name'),
|
|
71
|
-
'in': parameter.get('in'),
|
|
72
|
-
'required': parameter.get('required', False),
|
|
73
|
-
'description': parameter.get('description', ''),
|
|
74
|
-
'schema': parameter.get('schema', {})
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
# Extract type information
|
|
78
|
-
schema = parameter.get('schema', {})
|
|
79
|
-
param_info['type'] = self.get_js_type(schema)
|
|
80
|
-
param_info['format'] = schema.get('format')
|
|
81
|
-
|
|
82
|
-
return param_info
|
|
83
|
-
|
|
84
|
-
def extract_request_body_info(self, request_body: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
|
85
|
-
"""Extract request body information."""
|
|
86
|
-
if not request_body:
|
|
87
|
-
return None
|
|
88
|
-
|
|
89
|
-
content = request_body.get('content', {})
|
|
90
|
-
json_content = content.get('application/json', {})
|
|
91
|
-
schema = json_content.get('schema', {})
|
|
92
|
-
|
|
93
|
-
return {
|
|
94
|
-
'required': request_body.get('required', False),
|
|
95
|
-
'description': request_body.get('description', ''),
|
|
96
|
-
'schema': schema,
|
|
97
|
-
'type': self.get_js_type(schema)
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
def get_js_type(self, schema: Dict[str, Any]) -> str:
|
|
101
|
-
"""Convert OpenAPI schema to JavaScript/TypeScript type."""
|
|
102
|
-
if not schema:
|
|
103
|
-
return 'any'
|
|
104
|
-
|
|
105
|
-
# Handle references
|
|
106
|
-
if '$ref' in schema:
|
|
107
|
-
ref_name = schema['$ref'].split('/')[-1]
|
|
108
|
-
return ref_name
|
|
109
|
-
|
|
110
|
-
# Handle arrays
|
|
111
|
-
if schema.get('type') == 'array':
|
|
112
|
-
items_type = self.get_js_type(schema.get('items', {}))
|
|
113
|
-
return f'{items_type}[]'
|
|
114
|
-
|
|
115
|
-
# Handle objects
|
|
116
|
-
if schema.get('type') == 'object':
|
|
117
|
-
# Check if it has specific properties
|
|
118
|
-
if 'properties' in schema:
|
|
119
|
-
# Could generate an interface here
|
|
120
|
-
return 'Object'
|
|
121
|
-
# Check for additionalProperties (dictionary-like)
|
|
122
|
-
if 'additionalProperties' in schema:
|
|
123
|
-
additional = schema['additionalProperties']
|
|
124
|
-
# additionalProperties can be bool or schema object
|
|
125
|
-
if isinstance(additional, bool):
|
|
126
|
-
return 'Record<string, any>' if additional else 'Object'
|
|
127
|
-
value_type = self.get_js_type(additional)
|
|
128
|
-
return f'Record<string, {value_type}>'
|
|
129
|
-
return 'Object'
|
|
130
|
-
|
|
131
|
-
# Handle enums
|
|
132
|
-
if 'enum' in schema:
|
|
133
|
-
# Create a union type from enum values
|
|
134
|
-
values = schema['enum']
|
|
135
|
-
if all(isinstance(v, str) for v in values):
|
|
136
|
-
return ' | '.join(f'"{v}"' for v in values)
|
|
137
|
-
return 'string'
|
|
138
|
-
|
|
139
|
-
# Handle primitive types
|
|
140
|
-
type_mapping = {
|
|
141
|
-
'string': 'string',
|
|
142
|
-
'integer': 'number',
|
|
143
|
-
'number': 'number',
|
|
144
|
-
'boolean': 'boolean',
|
|
145
|
-
'null': 'null'
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
openapi_type = schema.get('type', 'any')
|
|
149
|
-
|
|
150
|
-
# Handle special formats
|
|
151
|
-
format_type = schema.get('format')
|
|
152
|
-
if openapi_type == 'string' and format_type:
|
|
153
|
-
format_mapping = {
|
|
154
|
-
'date': 'string', # Could be Date
|
|
155
|
-
'date-time': 'string', # Could be Date
|
|
156
|
-
'uuid': 'string',
|
|
157
|
-
'email': 'string',
|
|
158
|
-
'uri': 'string',
|
|
159
|
-
'binary': 'Blob',
|
|
160
|
-
'byte': 'string'
|
|
161
|
-
}
|
|
162
|
-
return format_mapping.get(format_type, 'string')
|
|
163
|
-
|
|
164
|
-
return type_mapping.get(openapi_type, 'any')
|
|
165
|
-
|
|
166
|
-
def get_response_type(self, responses: Dict[str, Any]) -> str:
|
|
167
|
-
"""Extract the response type from operation responses."""
|
|
168
|
-
# Look for successful response (200, 201, etc.)
|
|
169
|
-
for status in ['200', '201', '202']:
|
|
170
|
-
if status in responses:
|
|
171
|
-
response = responses[status]
|
|
172
|
-
content = response.get('content', {})
|
|
173
|
-
|
|
174
|
-
if 'application/json' in content:
|
|
175
|
-
schema = content['application/json'].get('schema', {})
|
|
176
|
-
return self.get_js_type(schema)
|
|
177
|
-
|
|
178
|
-
# Check for 204 No Content
|
|
179
|
-
if '204' in responses:
|
|
180
|
-
return 'void'
|
|
181
|
-
|
|
182
|
-
# Default to any
|
|
183
|
-
return 'any'
|
|
184
|
-
|
|
185
|
-
def resolve_ref(self, ref: str) -> Optional[Dict[str, Any]]:
|
|
186
|
-
"""Resolve a $ref to its schema definition."""
|
|
187
|
-
if not ref.startswith('#/'):
|
|
188
|
-
return None
|
|
189
|
-
|
|
190
|
-
parts = ref[2:].split('/')
|
|
191
|
-
current = self.schema
|
|
192
|
-
|
|
193
|
-
for part in parts:
|
|
194
|
-
if isinstance(current, dict) and part in current:
|
|
195
|
-
current = current[part]
|
|
196
|
-
else:
|
|
197
|
-
return None
|
|
198
|
-
|
|
199
|
-
return current
|
|
@@ -1,87 +0,0 @@
|
|
|
1
|
-
import { BaseAPIClient } from '../base.mjs';
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* {{ app_name.replace('_', ' ').title() }} API Client
|
|
5
|
-
* Auto-generated from OpenAPI schema
|
|
6
|
-
* @module {{ app_name }}
|
|
7
|
-
* @extends BaseAPIClient
|
|
8
|
-
*/
|
|
9
|
-
export class {{ class_name }} extends BaseAPIClient {
|
|
10
|
-
/**
|
|
11
|
-
* Initialize {{ app_name }} API client
|
|
12
|
-
* @param {string} [baseURL] - Optional base URL
|
|
13
|
-
*/
|
|
14
|
-
constructor(baseURL) {
|
|
15
|
-
super(baseURL);
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
{% for method in methods %}
|
|
19
|
-
/**
|
|
20
|
-
* {{ method.summary or method.name }}
|
|
21
|
-
{%- if method.description %}
|
|
22
|
-
* {{ method.description }}
|
|
23
|
-
{%- endif %}
|
|
24
|
-
{%- for param in method.path_params %}
|
|
25
|
-
* @param {{ '{' }}{{ param.type }}{{ '}' }} {{ param.name }}{% if param.description %} - {{ param.description }}{% endif %}
|
|
26
|
-
{%- endfor %}
|
|
27
|
-
{%- if method.request_body %}
|
|
28
|
-
* @param {{ '{' }}{{ method.request_body.type }}{{ '}' }} data - Request body{% if method.request_body.description %} - {{ method.request_body.description }}{% endif %}
|
|
29
|
-
{%- endif %}
|
|
30
|
-
{%- if method.query_params %}
|
|
31
|
-
* @param {{ '{Object}' }} [params={}] - Query parameters
|
|
32
|
-
{%- for param in method.query_params %}
|
|
33
|
-
* @param {{ '{' }}{{ param.type }}{{ '}' }} [params.{{ param.name }}]{% if param.description %} - {{ param.description }}{% endif %}
|
|
34
|
-
{%- endfor %}
|
|
35
|
-
{%- endif %}
|
|
36
|
-
* @returns {{ '{Promise<' }}{{ method.response_type }}{{ '>}' }} {{ 'Response data' if method.response_type != 'void' else 'No content' }}
|
|
37
|
-
*/
|
|
38
|
-
async {{ method.name }}(
|
|
39
|
-
{%- set params = [] %}
|
|
40
|
-
{%- for param in method.path_params %}
|
|
41
|
-
{%- set _ = params.append(param.name) %}
|
|
42
|
-
{%- endfor %}
|
|
43
|
-
{%- if method.request_body %}
|
|
44
|
-
{%- set _ = params.append('data') %}
|
|
45
|
-
{%- endif %}
|
|
46
|
-
{%- if method.query_params %}
|
|
47
|
-
{%- set _ = params.append('params = {}') %}
|
|
48
|
-
{%- endif %}
|
|
49
|
-
{{- params | join(', ') -}}
|
|
50
|
-
) {
|
|
51
|
-
const path = `{{ method.path }}`;
|
|
52
|
-
{%- if method.http_method == 'GET' %}
|
|
53
|
-
{%- if method.query_params %}
|
|
54
|
-
return this.get(path, params);
|
|
55
|
-
{%- else %}
|
|
56
|
-
return this.get(path);
|
|
57
|
-
{%- endif %}
|
|
58
|
-
{%- elif method.http_method == 'POST' %}
|
|
59
|
-
{%- if method.request_body %}
|
|
60
|
-
return this.post(path, data);
|
|
61
|
-
{%- else %}
|
|
62
|
-
return this.post(path, {});
|
|
63
|
-
{%- endif %}
|
|
64
|
-
{%- elif method.http_method == 'PUT' %}
|
|
65
|
-
{%- if method.request_body %}
|
|
66
|
-
return this.put(path, data);
|
|
67
|
-
{%- else %}
|
|
68
|
-
return this.put(path, {});
|
|
69
|
-
{%- endif %}
|
|
70
|
-
{%- elif method.http_method == 'PATCH' %}
|
|
71
|
-
{%- if method.request_body %}
|
|
72
|
-
return this.patch(path, data);
|
|
73
|
-
{%- else %}
|
|
74
|
-
return this.patch(path, {});
|
|
75
|
-
{%- endif %}
|
|
76
|
-
{%- elif method.http_method == 'DELETE' %}
|
|
77
|
-
return this.delete(path);
|
|
78
|
-
{%- endif %}
|
|
79
|
-
}
|
|
80
|
-
{% endfor %}
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
// Default instance for convenience
|
|
84
|
-
export const {{ instance_name }} = new {{ class_name }}();
|
|
85
|
-
|
|
86
|
-
// Default export
|
|
87
|
-
export default {{ class_name }};
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* {{ app_name.replace('_', ' ').title() }} API Module
|
|
3
|
-
* Re-exports the API client for convenient importing
|
|
4
|
-
* @module {{ app_name }}
|
|
5
|
-
*/
|
|
6
|
-
|
|
7
|
-
import { {{ class_name }}, {{ instance_name }} } from './client.mjs';
|
|
8
|
-
|
|
9
|
-
// Re-export the class and instance
|
|
10
|
-
export { {{ class_name }}, {{ instance_name }} };
|
|
11
|
-
|
|
12
|
-
// Default export is the instance for convenience
|
|
13
|
-
export default {{ instance_name }};
|