@apso/cli 0.48.0 → 0.49.1
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/README.md +28 -1
- package/dist/commands/dev.d.ts +2 -0
- package/dist/commands/dev.js +20 -3
- package/dist/commands/generate.js +49 -13
- package/dist/commands/mcp/serve.js +24 -41
- package/dist/commands/schema/diff.js +3 -4
- package/dist/commands/schema/pull.js +13 -11
- package/dist/commands/schema/push.js +6 -5
- package/dist/commands/schema/validate.d.ts +10 -0
- package/dist/commands/schema/validate.js +54 -0
- package/dist/commands/test/access.d.ts +11 -0
- package/dist/commands/test/access.js +65 -0
- package/dist/lib/access/cases.d.ts +120 -0
- package/dist/lib/access/cases.js +1163 -0
- package/dist/lib/access/index.d.ts +4 -0
- package/dist/lib/access/index.js +7 -0
- package/dist/lib/access/report.d.ts +75 -0
- package/dist/lib/access/report.js +118 -0
- package/dist/lib/access/rules.json +207 -0
- package/dist/lib/access/run.d.ts +38 -0
- package/dist/lib/access/run.js +111 -0
- package/dist/lib/access/tokens.d.ts +46 -0
- package/dist/lib/access/tokens.js +139 -0
- package/dist/lib/api/services.d.ts +10 -7
- package/dist/lib/api/services.js +19 -32
- package/dist/lib/apsorc-parser.d.ts +1 -1
- package/dist/lib/apsorc-parser.js +2 -0
- package/dist/lib/deploy/server-push.js +3 -1
- package/dist/lib/generators/go.d.ts +13 -1
- package/dist/lib/generators/go.js +144 -33
- package/dist/lib/generators/python.d.ts +3 -3
- package/dist/lib/generators/python.js +48 -24
- package/dist/lib/generators/typescript.d.ts +3 -5
- package/dist/lib/generators/typescript.js +78 -64
- package/dist/lib/guards.d.ts +111 -13
- package/dist/lib/guards.js +287 -23
- package/dist/lib/templates/go/handlers/handler.eta +8 -8
- package/dist/lib/templates/go/handlers/scope.eta +3 -2
- package/dist/lib/templates/go/index-module.eta +8 -5
- package/dist/lib/templates/go/mcp.eta +307 -0
- package/dist/lib/templates/go/middleware/auth.eta +587 -166
- package/dist/lib/templates/go/middleware/permission.eta +174 -0
- package/dist/lib/templates/go/services/service.eta +37 -16
- package/dist/lib/templates/go/utils/query.eta +37 -2
- package/dist/lib/templates/guards/guards.module.eta +37 -29
- package/dist/lib/templates/guards/index.eta +4 -0
- package/dist/lib/templates/guards/jwt-auth.guard.eta +114 -29
- package/dist/lib/templates/guards/key.guard.eta +280 -0
- package/dist/lib/templates/guards/permission.guard.eta +168 -0
- package/dist/lib/templates/guards/relations.interceptor.eta +124 -0
- package/dist/lib/templates/guards/scope.guard.eta +189 -41
- package/dist/lib/templates/python/auth.eta +354 -95
- package/dist/lib/templates/python/index-module.eta +7 -7
- package/dist/lib/templates/python/mcp.eta +284 -0
- package/dist/lib/templates/python/models/model.eta +6 -5
- package/dist/lib/templates/python/permissions.eta +121 -0
- package/dist/lib/templates/python/routers/router.eta +39 -1
- package/dist/lib/templates/python/schemas/schema.eta +18 -5
- package/dist/lib/templates/python/services/service.eta +38 -15
- package/dist/lib/templates/python/utils/query.eta +52 -25
- package/dist/lib/templates/rest/controller-rest.eta +43 -23
- package/dist/lib/templates/rest/index-module-rest.eta +0 -4
- package/dist/lib/templates/rest/service-rest.eta +3 -44
- package/dist/lib/types/auth.d.ts +84 -80
- package/dist/lib/types/auth.js +77 -60
- package/dist/lib/types/entity.d.ts +17 -9
- package/dist/lib/types/entity.js +3 -0
- package/dist/lib/types/index.d.ts +2 -2
- package/dist/lib/types/index.js +6 -5
- package/dist/lib/utils/crud-deps.d.ts +77 -6
- package/dist/lib/utils/crud-deps.js +197 -14
- package/dist/lib/utils/schema-convert.d.ts +20 -43
- package/dist/lib/utils/schema-convert.js +28 -78
- package/dist/lib/utils/template.d.ts +11 -0
- package/dist/lib/utils/template.js +36 -1
- package/dist/lib/verify/index.d.ts +6 -1
- package/dist/lib/verify/index.js +30 -13
- package/npm-shrinkwrap.json +2 -2
- package/oclif.manifest.json +36 -1
- package/package.json +1 -1
- package/dist/lib/templates/guards/api-key-auth.guard.eta +0 -145
- package/dist/lib/templates/guards/auth.guard.eta +0 -233
|
@@ -8,6 +8,9 @@ from fastapi import HTTPException, status
|
|
|
8
8
|
from sqlalchemy import String, cast
|
|
9
9
|
<% } %>
|
|
10
10
|
|
|
11
|
+
<% if (it.references.length) { %>
|
|
12
|
+
from ..auth import check_references
|
|
13
|
+
<% } %>
|
|
11
14
|
from ..models.<%= it.entityName.toLowerCase() %> import <%= it.entityName %>
|
|
12
15
|
from ..schemas.<%= it.entityName.toLowerCase() %> import <%= it.entityName %>Create, <%= it.entityName %>Update
|
|
13
16
|
from ..utils.query import QueryBuilder, QueryOptions, PaginatedResult
|
|
@@ -26,15 +29,15 @@ class <%= it.entityName %>Service:
|
|
|
26
29
|
|
|
27
30
|
def _scope_values(self, op: str) -> dict:
|
|
28
31
|
"""
|
|
29
|
-
The caller's value for each scopeBy field for
|
|
30
|
-
|
|
31
|
-
caller holds a bypass role. 403 when the caller has no tenant.
|
|
32
|
+
The caller's value for each scopeBy field, for every operation; empty
|
|
33
|
+
for a service caller or a bypass role. 403 when the caller has no tenant.
|
|
32
34
|
"""
|
|
33
|
-
if op not in <%~ JSON.stringify(it.scope.enforceOn) %>:
|
|
34
|
-
return {}
|
|
35
35
|
a = self.auth
|
|
36
36
|
if a is None:
|
|
37
37
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="No tenant in the auth context")
|
|
38
|
+
# A service caller (valid API key) is not tenant-scoped.
|
|
39
|
+
if a.service_id:
|
|
40
|
+
return {}
|
|
38
41
|
<% if (it.scope.bypassRoles.length > 0) { %>
|
|
39
42
|
if set(a.roles) & set(<%~ JSON.stringify(it.scope.bypassRoles) %>):
|
|
40
43
|
return {}
|
|
@@ -54,25 +57,33 @@ class <%= it.entityName %>Service:
|
|
|
54
57
|
cast(getattr(<%= it.entityName %>, field), String) == str(value)
|
|
55
58
|
for field, value in self._scope_values(op).items()
|
|
56
59
|
]
|
|
57
|
-
return QueryBuilder(<%= it.entityName %>, self.db, scope=scope)
|
|
60
|
+
return QueryBuilder(<%= it.entityName %>, self.db, auth=self.auth, scope=scope)
|
|
58
61
|
|
|
59
62
|
def _with_tenant(self, payload: dict) -> dict:
|
|
60
63
|
"""Set every scopeBy field to the caller's value, converted to the column's type."""
|
|
61
|
-
<% if (it.scope.injectOnCreate) { %>
|
|
62
64
|
for field, value in self._scope_values("create").items():
|
|
63
65
|
try:
|
|
64
66
|
value = getattr(<%= it.entityName %>, field).type.python_type(value)
|
|
65
67
|
except (NotImplementedError, TypeError, ValueError):
|
|
66
68
|
pass
|
|
67
69
|
payload[field] = value
|
|
68
|
-
<% } %>
|
|
69
70
|
return payload
|
|
70
71
|
<% } else { %>
|
|
71
72
|
|
|
72
73
|
def _qb(self, op: str) -> QueryBuilder:
|
|
73
|
-
return QueryBuilder(<%= it.entityName %>, self.db)
|
|
74
|
+
return QueryBuilder(<%= it.entityName %>, self.db, auth=self.auth)
|
|
74
75
|
<% } %>
|
|
75
76
|
|
|
77
|
+
<% if (it.references.length) { %>
|
|
78
|
+
async def _check_references(self, rows: List[dict]) -> None:
|
|
79
|
+
"""Foreign keys to tenant-scoped entities must name rows the caller can read."""
|
|
80
|
+
await check_references(self.auth, self.db, {
|
|
81
|
+
<% it.references.forEach((r) => { %>
|
|
82
|
+
<%~ JSON.stringify(r.target) %>: [row.get(<%~ JSON.stringify(r.field) %>) for row in rows],
|
|
83
|
+
<% }) %>
|
|
84
|
+
})
|
|
85
|
+
|
|
86
|
+
<% } %>
|
|
76
87
|
async def get_many(self, options: QueryOptions) -> PaginatedResult:
|
|
77
88
|
"""
|
|
78
89
|
Retrieve a paginated list of <%= it.pluralEntityName %> with filtering, sorting, and joins.
|
|
@@ -101,11 +112,14 @@ class <%= it.entityName %>Service:
|
|
|
101
112
|
"""
|
|
102
113
|
Create a new <%= it.entityName %>.
|
|
103
114
|
"""
|
|
115
|
+
payload = data.model_dump(exclude_unset=True)
|
|
104
116
|
<% if (it.scope) { %>
|
|
105
|
-
|
|
106
|
-
<% }
|
|
107
|
-
|
|
117
|
+
payload = self._with_tenant(payload)
|
|
118
|
+
<% } %>
|
|
119
|
+
<% if (it.references.length) { %>
|
|
120
|
+
await self._check_references([payload])
|
|
108
121
|
<% } %>
|
|
122
|
+
item = <%= it.entityName %>(**payload)
|
|
109
123
|
self.db.add(item)
|
|
110
124
|
await self.db.commit()
|
|
111
125
|
await self.db.refresh(item)
|
|
@@ -115,11 +129,14 @@ class <%= it.entityName %>Service:
|
|
|
115
129
|
"""
|
|
116
130
|
Create multiple <%= it.pluralEntityName %>.
|
|
117
131
|
"""
|
|
132
|
+
payloads = [item.model_dump(exclude_unset=True) for item in data]
|
|
118
133
|
<% if (it.scope) { %>
|
|
119
|
-
|
|
120
|
-
<% } else { %>
|
|
121
|
-
items = [<%= it.entityName %>(**item.model_dump(exclude_unset=True)) for item in data]
|
|
134
|
+
payloads = [self._with_tenant(payload) for payload in payloads]
|
|
122
135
|
<% } %>
|
|
136
|
+
<% if (it.references.length) { %>
|
|
137
|
+
await self._check_references(payloads)
|
|
138
|
+
<% } %>
|
|
139
|
+
items = [<%= it.entityName %>(**payload) for payload in payloads]
|
|
123
140
|
self.db.add_all(items)
|
|
124
141
|
await self.db.commit()
|
|
125
142
|
for item in items:
|
|
@@ -143,6 +160,9 @@ class <%= it.entityName %>Service:
|
|
|
143
160
|
# A scoped row cannot move to another tenant.
|
|
144
161
|
for field in self._scope_values("update"):
|
|
145
162
|
update_data.pop(field, None)
|
|
163
|
+
<% } %>
|
|
164
|
+
<% if (it.references.length) { %>
|
|
165
|
+
await self._check_references([update_data])
|
|
146
166
|
<% } %>
|
|
147
167
|
for field, value in update_data.items():
|
|
148
168
|
setattr(item, field, value)
|
|
@@ -167,6 +187,9 @@ class <%= it.entityName %>Service:
|
|
|
167
187
|
<% if (it.scope) { %>
|
|
168
188
|
for field in self._scope_values("update"):
|
|
169
189
|
replace_data.pop(field, None)
|
|
190
|
+
<% } %>
|
|
191
|
+
<% if (it.references.length) { %>
|
|
192
|
+
await self._check_references([replace_data])
|
|
170
193
|
<% } %>
|
|
171
194
|
for field, value in replace_data.items():
|
|
172
195
|
setattr(item, field, value)
|
|
@@ -11,6 +11,8 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
11
11
|
from sqlalchemy.orm import selectinload
|
|
12
12
|
from sqlalchemy.sql import Select, select
|
|
13
13
|
|
|
14
|
+
from ..auth import check_relation, relation_conditions
|
|
15
|
+
|
|
14
16
|
T = TypeVar("T")
|
|
15
17
|
|
|
16
18
|
MAX_LIMIT = 200
|
|
@@ -251,6 +253,8 @@ def parse_nestjsx_params(params: Any) -> QueryOptions:
|
|
|
251
253
|
opts.limit = min(int(limit_raw), MAX_LIMIT)
|
|
252
254
|
except (ValueError, TypeError):
|
|
253
255
|
pass
|
|
256
|
+
if opts.limit < 0:
|
|
257
|
+
raise QueryParseError("limit must not be negative")
|
|
254
258
|
|
|
255
259
|
page_raw = params.get("page")
|
|
256
260
|
if page_raw is not None:
|
|
@@ -664,6 +668,8 @@ def parse_postgrest_params(params: Any) -> QueryOptions:
|
|
|
664
668
|
opts.offset_present = True
|
|
665
669
|
except (ValueError, TypeError):
|
|
666
670
|
raise QueryParseError("Invalid offset")
|
|
671
|
+
if opts.limit < 0 or (opts.offset or 0) < 0:
|
|
672
|
+
raise QueryParseError("limit and offset must not be negative")
|
|
667
673
|
|
|
668
674
|
return opts
|
|
669
675
|
|
|
@@ -701,9 +707,11 @@ def parse_query_params(params: Any, dialect_header: Optional[str] = None) -> Que
|
|
|
701
707
|
class QueryBuilder:
|
|
702
708
|
"""Build and execute filtered/sorted/paginated SQLAlchemy queries."""
|
|
703
709
|
|
|
704
|
-
def __init__(self, model: Type[T], db: AsyncSession, scope: Optional[List[Any]] = None):
|
|
710
|
+
def __init__(self, model: Type[T], db: AsyncSession, scope: Optional[List[Any]] = None, auth: Any = None):
|
|
705
711
|
self.model = model
|
|
706
712
|
self.db = db
|
|
713
|
+
# The caller, checked for every relation a request loads.
|
|
714
|
+
self.auth = auth
|
|
707
715
|
# Conditions every query must meet (the caller's tenant, .apsorc scopeBy).
|
|
708
716
|
self.scope = list(scope or [])
|
|
709
717
|
|
|
@@ -774,32 +782,55 @@ class QueryBuilder:
|
|
|
774
782
|
query = query.order_by(self.model.id)
|
|
775
783
|
return query
|
|
776
784
|
|
|
785
|
+
def _projection(self, options: QueryOptions) -> List[Any]:
|
|
786
|
+
"""
|
|
787
|
+
The columns a fields=/select= list names. Empty means whole rows.
|
|
788
|
+
A column list cannot be combined with a relation: a relation loads
|
|
789
|
+
onto a whole row.
|
|
790
|
+
"""
|
|
791
|
+
cols: List[Any] = []
|
|
792
|
+
for name in options.fields or []:
|
|
793
|
+
col = getattr(self.model, name, None)
|
|
794
|
+
if col is None and self._postgrest_mode:
|
|
795
|
+
raise QueryParseError(f"Unknown column '{name}' in query")
|
|
796
|
+
if col is not None and name in self.model.__table__.columns:
|
|
797
|
+
cols.append(col)
|
|
798
|
+
if not cols:
|
|
799
|
+
return []
|
|
800
|
+
if options.joins:
|
|
801
|
+
raise QueryParseError("A column list cannot be combined with a relation; leave out the column list")
|
|
802
|
+
# nestjsx always returns the id with the chosen fields.
|
|
803
|
+
if not self._postgrest_mode and "id" not in (options.fields or []):
|
|
804
|
+
cols.insert(0, self.model.id)
|
|
805
|
+
return cols
|
|
806
|
+
|
|
807
|
+
def _rows(self, result: Any, options: QueryOptions) -> List[Any]:
|
|
808
|
+
"""Whole rows as ORM objects; a column list as one dict per row."""
|
|
809
|
+
if self._projection(options):
|
|
810
|
+
return [dict(row._mapping) for row in result.all()]
|
|
811
|
+
return list(result.scalars().all())
|
|
812
|
+
|
|
777
813
|
def _base_query(self, options: QueryOptions) -> Select:
|
|
778
814
|
# Field selection replaces the column list; otherwise select the model.
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
for name in options.fields:
|
|
782
|
-
col = getattr(self.model, name, None)
|
|
783
|
-
if col is None and self._postgrest_mode:
|
|
784
|
-
raise QueryParseError(f"Unknown column '{name}' in query")
|
|
785
|
-
if col is not None:
|
|
786
|
-
cols.append(col)
|
|
787
|
-
if cols:
|
|
788
|
-
query: Select = select(*cols).select_from(self.model)
|
|
789
|
-
else:
|
|
790
|
-
query = select(self.model)
|
|
791
|
-
else:
|
|
792
|
-
query = select(self.model)
|
|
815
|
+
cols = self._projection(options)
|
|
816
|
+
query: Select = select(*cols).select_from(self.model) if cols else select(self.model)
|
|
793
817
|
|
|
794
818
|
for clause in self._where_clauses(options):
|
|
795
819
|
query = query.where(clause)
|
|
796
820
|
|
|
797
821
|
query = self._apply_sorts(query, options)
|
|
798
822
|
|
|
799
|
-
for j in options.joins
|
|
800
|
-
|
|
823
|
+
return self._load(query, [j.relation for j in options.joins])
|
|
824
|
+
|
|
825
|
+
def _load(self, query: Select, relations: Sequence[str]) -> Select:
|
|
826
|
+
"""Load the relations a request names (join or select embed), each checked for the caller."""
|
|
827
|
+
for name in relations:
|
|
828
|
+
check_relation(self.auth, self.model.__name__, name)
|
|
829
|
+
rel = getattr(self.model, name, None)
|
|
801
830
|
if rel is not None:
|
|
802
|
-
|
|
831
|
+
# Rows of a tenant-scoped target are loaded for the caller's tenant only.
|
|
832
|
+
conditions = relation_conditions(self.auth, self.model.__name__, name, rel.property.mapper.class_)
|
|
833
|
+
query = query.options(selectinload(rel.and_(*conditions)) if conditions else selectinload(rel))
|
|
803
834
|
return query
|
|
804
835
|
|
|
805
836
|
def _count_query(self, options: QueryOptions) -> Select:
|
|
@@ -826,7 +857,7 @@ class QueryBuilder:
|
|
|
826
857
|
query = query.offset(offset).limit(options.limit)
|
|
827
858
|
|
|
828
859
|
result = await self.db.execute(query)
|
|
829
|
-
items =
|
|
860
|
+
items = self._rows(result, options)
|
|
830
861
|
|
|
831
862
|
page_count = math.ceil(total / options.limit) if options.limit > 0 else 1
|
|
832
863
|
|
|
@@ -855,7 +886,7 @@ class QueryBuilder:
|
|
|
855
886
|
query = query.limit(options.limit)
|
|
856
887
|
|
|
857
888
|
result = await self.db.execute(query)
|
|
858
|
-
items =
|
|
889
|
+
items = self._rows(result, options)
|
|
859
890
|
return self._apply_field_aliases(items, options)
|
|
860
891
|
finally:
|
|
861
892
|
self._postgrest_mode = False
|
|
@@ -893,11 +924,7 @@ class QueryBuilder:
|
|
|
893
924
|
) -> Optional[Any]:
|
|
894
925
|
query = select(self.model).where(self.model.id == id, *self.scope)
|
|
895
926
|
|
|
896
|
-
|
|
897
|
-
for join_name in joins:
|
|
898
|
-
rel = getattr(self.model, join_name, None)
|
|
899
|
-
if rel is not None:
|
|
900
|
-
query = query.options(selectinload(rel))
|
|
927
|
+
query = self._load(query, joins or [])
|
|
901
928
|
|
|
902
929
|
result = await self.db.execute(query)
|
|
903
930
|
return result.scalar_one_or_none()
|
|
@@ -1,10 +1,19 @@
|
|
|
1
1
|
<%~ includeFile('./header.eta') %>
|
|
2
2
|
|
|
3
|
-
import { Controller, Body } from "@nestjs/common";
|
|
3
|
+
import { Controller, Body<% if (it.relationAccess) { %>, UseInterceptors<% } %> } from "@nestjs/common";
|
|
4
4
|
import { Crud, <% if (it.crudAuth.length || it.crudAuthNested.length) { %>CrudAuth, <% } %>CrudController, Override, ParsedRequest, CrudRequest, ParsedBody, CreateManyDto } from '@apso/crud';
|
|
5
5
|
import { ApiTags, ApiResponse, ApiOperation, ApiBody } from '@nestjs/swagger';
|
|
6
|
-
|
|
6
|
+
<% if (it.mcp.length) { %>
|
|
7
|
+
import { McpTool } from '@apso/mcp';
|
|
8
|
+
<% } %>
|
|
9
|
+
import {<%= it.entityName %>Create, <%= it.entityName %>Update} from './dtos/<%= it.entityName%>.dto'
|
|
10
|
+
// The entity, not the response DTO: the documented filter parameters (one per
|
|
11
|
+
// column, which is also what an MCP list tool accepts) come from its columns.
|
|
12
|
+
import { <%= it.entityName %> } from './<%= it.entityName %>.entity';
|
|
7
13
|
import {<%= it.svcName %>} from './<%= it.entityName %>.service';
|
|
14
|
+
<% if (it.relationAccess) { %>
|
|
15
|
+
import { RelationAccess, RelationRoot } from '../guards/relations.interceptor';
|
|
16
|
+
<% } %>
|
|
8
17
|
|
|
9
18
|
<% if (it.crudAuthNested.length) { %>
|
|
10
19
|
// A nested scopeBy path (task.workspaceId) limits rows to the parents ScopeGuard
|
|
@@ -16,25 +25,20 @@ const nestedScope = (req: any, fk: string) => {
|
|
|
16
25
|
};
|
|
17
26
|
<% } %>
|
|
18
27
|
<% if (it.scopeOptions && (it.crudAuth.length || it.crudAuthNested.length)) { %>
|
|
19
|
-
//
|
|
20
|
-
// roles skip it.
|
|
21
|
-
const ENFORCE_ON = [<%~ it.scopeOptions.enforceOn.map((op) => `'${op}'`).join(', ') %>];
|
|
28
|
+
// The callers that skip the tenant filter (.apsorc scopeOptions.bypassRoles).
|
|
22
29
|
const BYPASS_ROLES: string[] = [<%~ it.scopeOptions.bypassRoles.map((r) => `'${r}'`).join(', ') %>];
|
|
23
|
-
const scopeOperation = (req: any) => {
|
|
24
|
-
switch (req.method) {
|
|
25
|
-
case 'GET': return req.params?.id ? 'get' : 'find';
|
|
26
|
-
case 'POST': return 'create';
|
|
27
|
-
case 'PUT':
|
|
28
|
-
case 'PATCH': return 'update';
|
|
29
|
-
case 'DELETE': return 'delete';
|
|
30
|
-
default: return 'find';
|
|
31
|
-
}
|
|
32
|
-
};
|
|
33
30
|
const skipScope = (req: any) => {
|
|
31
|
+
// A service caller (valid API key) is not tenant-scoped.
|
|
32
|
+
if (req.auth?.serviceId) return true;
|
|
34
33
|
const roles: string[] = req.auth?.roles ?? req.user?.roles ?? [];
|
|
35
|
-
return roles.some((r) => BYPASS_ROLES.includes(r))
|
|
34
|
+
return roles.some((r) => BYPASS_ROLES.includes(r));
|
|
36
35
|
};
|
|
37
36
|
<% } %>
|
|
37
|
+
<% if (it.relationAccess) { %>
|
|
38
|
+
// Above @Crud, so it runs after @Crud's interceptor has parsed the request.
|
|
39
|
+
@UseInterceptors(RelationAccess)
|
|
40
|
+
@RelationRoot('<%= it.entityName %>')
|
|
41
|
+
<% } %>
|
|
38
42
|
@Crud({
|
|
39
43
|
model: {
|
|
40
44
|
type: <%= it.entityName %>
|
|
@@ -45,6 +49,9 @@ const skipScope = (req: any) => {
|
|
|
45
49
|
replace: <%= it.entityName %>Update,
|
|
46
50
|
},
|
|
47
51
|
validation: false,
|
|
52
|
+
// List queries are PostgREST syntax only (?status=eq.open&select=id,name&order=id.desc).
|
|
53
|
+
// A nestjsx parameter (filter, join, sort, s, fields, page, per_page, cache) gets a 400.
|
|
54
|
+
dialects: ['postgrest'],
|
|
48
55
|
params: {
|
|
49
56
|
id: {
|
|
50
57
|
field: 'id',
|
|
@@ -53,12 +60,10 @@ const skipScope = (req: any) => {
|
|
|
53
60
|
},
|
|
54
61
|
},
|
|
55
62
|
query: {
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
limit: 5,
|
|
61
|
-
alwaysPaginate: true,
|
|
63
|
+
// The default page: a list with no limit returns at most this many
|
|
64
|
+
// rows. When more exist the answer is a 206 and its Content-Range
|
|
65
|
+
// header has the total (0-24/42). The largest limit is 100.
|
|
66
|
+
limit: 25,
|
|
62
67
|
<% if (it.associations.length) { %>
|
|
63
68
|
join: {
|
|
64
69
|
<% it.associations.forEach((assoc) => { %>
|
|
@@ -91,7 +96,7 @@ const skipScope = (req: any) => {
|
|
|
91
96
|
...nestedScope(req, '<%= s.fkField %>'),
|
|
92
97
|
<% }) %>
|
|
93
98
|
}),
|
|
94
|
-
persist: (req: any) => <% if (it.scopeOptions) { %>skipScope(req)
|
|
99
|
+
persist: (req: any) => <% if (it.scopeOptions) { %>skipScope(req) ? {} : <% } %>({
|
|
95
100
|
<% it.crudAuth.forEach((s) => { %>
|
|
96
101
|
<%= s.field %>: req.<%= s.contextKey %> ?? req.user?.<%= s.contextKey %> ?? req.auth?.<%= s.contextKey %> ?? req.auth?.workspaceId,
|
|
97
102
|
<% }) %>
|
|
@@ -146,6 +151,9 @@ export class <%= it.ctrlName %> implements CrudController<<%= it.entityName %>>{
|
|
|
146
151
|
|
|
147
152
|
@Override('getManyBase')
|
|
148
153
|
@ApiOperation({ summary: 'Retrieve multiple <%= it.pluralEntityName %>' })
|
|
154
|
+
<% if (it.mcp.includes('read')) { %>
|
|
155
|
+
@McpTool({ name: 'list_<%= it.mcpPluralName %>' })
|
|
156
|
+
<% } %>
|
|
149
157
|
getMany(
|
|
150
158
|
@ParsedRequest() req: CrudRequest,
|
|
151
159
|
) {
|
|
@@ -154,6 +162,9 @@ export class <%= it.ctrlName %> implements CrudController<<%= it.entityName %>>{
|
|
|
154
162
|
|
|
155
163
|
@Override('getOneBase')
|
|
156
164
|
@ApiOperation({ summary: 'Retrieve a single <%= it.entityName %>' })
|
|
165
|
+
<% if (it.mcp.includes('read')) { %>
|
|
166
|
+
@McpTool({ name: 'get_<%= it.mcpName %>', description: 'Get one <%= it.entityName %> by id.' })
|
|
167
|
+
<% } %>
|
|
157
168
|
get(
|
|
158
169
|
@ParsedRequest() req: CrudRequest,
|
|
159
170
|
) {
|
|
@@ -180,6 +191,9 @@ export class <%= it.ctrlName %> implements CrudController<<%= it.entityName %>>{
|
|
|
180
191
|
} */ %>
|
|
181
192
|
|
|
182
193
|
})
|
|
194
|
+
<% if (it.mcp.includes('create')) { %>
|
|
195
|
+
@McpTool({ name: 'create_<%= it.mcpName %>', description: 'Create a <%= it.entityName %>.' })
|
|
196
|
+
<% } %>
|
|
183
197
|
create(
|
|
184
198
|
@ParsedRequest() req: CrudRequest,
|
|
185
199
|
@Body() dto: <%= it.entityName %>Create,
|
|
@@ -198,6 +212,9 @@ export class <%= it.ctrlName %> implements CrudController<<%= it.entityName %>>{
|
|
|
198
212
|
|
|
199
213
|
@Override('updateOneBase')
|
|
200
214
|
@ApiOperation({ summary: 'Update a single <%= it.entityName %>' })
|
|
215
|
+
<% if (it.mcp.includes('update')) { %>
|
|
216
|
+
@McpTool({ name: 'update_<%= it.mcpName %>', description: 'Update fields of one <%= it.entityName %> by id.' })
|
|
217
|
+
<% } %>
|
|
201
218
|
update(
|
|
202
219
|
@ParsedRequest() req: CrudRequest,
|
|
203
220
|
@Body() dto: <%= it.entityName %>Update,
|
|
@@ -216,6 +233,9 @@ export class <%= it.ctrlName %> implements CrudController<<%= it.entityName %>>{
|
|
|
216
233
|
|
|
217
234
|
@Override('deleteOneBase')
|
|
218
235
|
@ApiOperation({ summary: 'Delete a single <%= it.entityName %>' })
|
|
236
|
+
<% if (it.mcp.includes('delete')) { %>
|
|
237
|
+
@McpTool({ name: 'delete_<%= it.mcpName %>', description: 'Delete one <%= it.entityName %> by id. This cannot be undone.' })
|
|
238
|
+
<% } %>
|
|
219
239
|
delete(
|
|
220
240
|
@ParsedRequest() req: CrudRequest,
|
|
221
241
|
) {
|
|
@@ -3,15 +3,11 @@
|
|
|
3
3
|
<% it.entities.forEach((entity) => { %>
|
|
4
4
|
import {<%= entity.name %>Module} from './<%= entity.name %>/<%= entity.name %>.module'
|
|
5
5
|
<%}) %>
|
|
6
|
-
<% if (it.hasGuards) { %>
|
|
7
6
|
import { GuardsModule } from './guards/guards.module'
|
|
8
|
-
<% } %>
|
|
9
7
|
|
|
10
8
|
export default [
|
|
11
9
|
<% it.entities.forEach((entity) => { %>
|
|
12
10
|
<%= entity.name %>Module,
|
|
13
11
|
<%}) %>
|
|
14
|
-
<% if (it.hasGuards) { %>
|
|
15
12
|
GuardsModule,
|
|
16
|
-
<% } %>
|
|
17
13
|
]
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
<%~ includeFile('./header.eta') %>
|
|
2
2
|
|
|
3
|
-
import { Injectable
|
|
3
|
+
import { Injectable } from "@nestjs/common";
|
|
4
4
|
import { InjectRepository } from "@nestjs/typeorm";
|
|
5
5
|
import { TypeOrmCrudService } from "@apso/crud-typeorm";
|
|
6
|
-
import { QueryOptions
|
|
6
|
+
import { QueryOptions } from '@apso/crud';
|
|
7
7
|
import { ParsedRequestParams } from '@apso/crud-request';
|
|
8
|
-
import { Repository
|
|
8
|
+
import { Repository } from 'typeorm';
|
|
9
9
|
|
|
10
10
|
import {<%= it.entityName %>} from './<%= it.entityName%>.entity'
|
|
11
11
|
|
|
@@ -21,45 +21,4 @@ export class <%= it.svcName %> extends TypeOrmCrudService<<%= it.entityName %>>
|
|
|
21
21
|
getSelect(query: ParsedRequestParams, options: QueryOptions) {
|
|
22
22
|
return [...new Set(super.getSelect(query, options))]
|
|
23
23
|
}
|
|
24
|
-
|
|
25
|
-
/**
|
|
26
|
-
* Override updateOne to fix NestJS CRUD bug where PATCH causes INSERT instead of UPDATE.
|
|
27
|
-
* This properly fetches the existing entity, merges with the DTO, then saves.
|
|
28
|
-
*/
|
|
29
|
-
async updateOne(req: CrudRequest, dto: DeepPartial<<%= it.entityName %>>): Promise<<%= it.entityName %>> {
|
|
30
|
-
const id = req.parsed.paramsFilter?.find(f => f.field === 'id')?.value;
|
|
31
|
-
if (!id) {
|
|
32
|
-
throw new NotFoundException('<%= it.entityName %> ID not provided');
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
const existing = await this.repo.findOne({ where: { id } as any });
|
|
36
|
-
if (!existing) {
|
|
37
|
-
throw new NotFoundException('<%= it.entityName %> not found');
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
// Merge existing entity with DTO and save
|
|
41
|
-
const merged = this.repo.merge(existing, dto as any);
|
|
42
|
-
return this.repo.save(merged);
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
/**
|
|
46
|
-
* Override replaceOne to fix NestJS CRUD bug where PUT causes INSERT instead of UPDATE.
|
|
47
|
-
* This properly fetches the existing entity, replaces it with the DTO, then saves.
|
|
48
|
-
*/
|
|
49
|
-
async replaceOne(req: CrudRequest, dto: DeepPartial<<%= it.entityName %>>): Promise<<%= it.entityName %>> {
|
|
50
|
-
const id = req.parsed.paramsFilter?.find(f => f.field === 'id')?.value;
|
|
51
|
-
if (!id) {
|
|
52
|
-
throw new NotFoundException('<%= it.entityName %> ID not provided');
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
const existing = await this.repo.findOne({ where: { id } as any });
|
|
56
|
-
if (!existing) {
|
|
57
|
-
throw new NotFoundException('<%= it.entityName %> not found');
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
// Replace with DTO (keeping the ID) and save
|
|
61
|
-
const replaced = { ...dto, id: existing.id } as <%= it.entityName %>;
|
|
62
|
-
return this.repo.save(replaced);
|
|
63
|
-
}
|
|
64
24
|
}
|
|
65
|
-
|