very-express 0.6.21 → 0.7.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.
@@ -0,0 +1,31 @@
1
+ // {{headerComment}}
2
+ import { AsyncLocalStorage } from "async_hooks";
3
+ import { Request, Response, NextFunction } from "express";
4
+
5
+ export interface DataIsolationStore {
6
+ userId: string;
7
+ }
8
+
9
+ const als = new AsyncLocalStorage<DataIsolationStore>();
10
+
11
+ class DataIsolationContext {
12
+ /**
13
+ * Express middleware — creates ALS context with authenticated user's _id.
14
+ * Must run AFTER Authentication.middleware (which sets req.user).
15
+ */
16
+ middleware(req: Request, _res: Response, next: NextFunction): void {
17
+ const user = (req as any).user;
18
+ if (user?._id) {
19
+ als.run({ userId: user._id }, () => next());
20
+ } else {
21
+ next();
22
+ }
23
+ }
24
+
25
+ /** Get current store from per-request ALS context. */
26
+ getStore(): DataIsolationStore | undefined {
27
+ return als.getStore();
28
+ }
29
+ }
30
+
31
+ export default new DataIsolationContext();
@@ -1,6 +1,6 @@
1
1
  // {{headerComment}}
2
2
  import { Model, Document } from "mongoose";
3
- import { VexRepository, Select, Filter, Join } from "../_types/vex";
3
+ import { VexRepository, Select, Filter, Join, VexPagination } from "../_types/vex";
4
4
  import utils from "../_utils";
5
5
 
6
6
  export class MongooseRepositoryAdapter<T extends Document> implements VexRepository<T> {
@@ -10,11 +10,16 @@ export class MongooseRepositoryAdapter<T extends Document> implements VexReposit
10
10
  return this.model;
11
11
  }
12
12
 
13
- find(filter: Filter, join?: Join, select?: Select): Promise<T[]> {
14
- // TODO: complete mongoose support, handle join and select
13
+ find(filter: Filter, join?: Join, select?: Select, pagination?: VexPagination): Promise<T[]> {
14
+ // TODO: complete mongoose support, handle join, select, and pagination
15
15
  return this.model.find((filter || {}) as any).exec();
16
16
  }
17
17
 
18
+ async count(filter: Filter): Promise<number> {
19
+ // TODO: complete mongoose support, handle filter
20
+ return 0;
21
+ }
22
+
18
23
  findOne(filter: Filter, join?: Join, select?: Select): Promise<T | null> {
19
24
  // TODO: complete mongoose support, handle join and select
20
25
  return this.model.findOne(filter as any).exec();
@@ -1,11 +1,34 @@
1
1
  // {{headerComment}}
2
2
  import { Repository, ObjectLiteral, FindOptionsWhere, DeepPartial, In, Not, Like, MoreThan, LessThan, MoreThanOrEqual, LessThanOrEqual, FindManyOptions } from "typeorm";
3
- import { VexRepository, Select, Filter, Join, FieldOperators } from "../_types/vex";
3
+ import { VexRepository, Select, Filter, Join, FieldOperators, VexPagination } from "../_types/vex";
4
+ import DataIsolationContext from "../_middlewares/DataIsolationContext.gen";
5
+ import { entityIsolation } from "../_middlewares/DataIsolationRegistry.gen";
4
6
  import utils from "../_utils";
5
7
 
6
8
  export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRepository<T> {
7
9
  constructor(private repo: Repository<T>) {}
8
10
 
11
+ /** Build ownership filter from current request context, or null. */
12
+ private getOwnershipFilter(): Record<string, unknown> | null {
13
+ const store = DataIsolationContext.getStore();
14
+ if (!store?.userId) return null;
15
+
16
+ const entityName = this.repo.metadata.target instanceof Function
17
+ ? this.repo.metadata.target.name
18
+ : "";
19
+ const config = entityIsolation[entityName];
20
+ if (!config) return null;
21
+
22
+ return { [config.field]: store.userId };
23
+ }
24
+
25
+ /** Merge caller filter with ownership filter. Ownership always wins. */
26
+ private mergeFilter(callerFilter: Filter<T>): Record<string, unknown> {
27
+ const mapped = this.mapOperators(callerFilter) as Record<string, unknown>;
28
+ const ownership = this.getOwnershipFilter();
29
+ return ownership ? { ...mapped, ...ownership } : mapped;
30
+ }
31
+
9
32
  private mapOperators(filter: Filter<T>): Record<string, unknown> {
10
33
  if (!filter || typeof filter !== "object") return {};
11
34
  // if (Array.isArray(filter)) return filter.map(f => this.mapOperators(f));
@@ -69,29 +92,41 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
69
92
  return this.repo;
70
93
  }
71
94
 
72
- find(filter: Filter<T>, join?: Join, select?: Select, options?: FindManyOptions<T>): Promise<T[]> {
73
- const where = this.mapOperators(filter) as FindOptionsWhere<T>;
74
- return this.repo.find({
75
- select,
95
+ find(filter: Filter<T>, join?: Join, select?: Select, pagination?: VexPagination): Promise<T[]> {
96
+ const where = this.mergeFilter(filter) as FindOptionsWhere<T>;
97
+ const options: FindManyOptions<T> = {
98
+ select: select as any,
76
99
  where,
77
100
  relations: join,
78
- take: options?.take || 500,
79
- ...options
80
- });
101
+ take: 500,
102
+ };
103
+ if (pagination) {
104
+ const page = pagination.page || 1;
105
+ const perPage = Math.min(pagination.perPage || 20, 9999);
106
+ options.take = Math.min(perPage, 9999);
107
+ options.skip = (page - 1) * perPage;
108
+ if (pagination.sort) options.order = pagination.sort as any;
109
+ }
110
+ return this.repo.find(options);
111
+ }
112
+
113
+ async count(filter: Filter<T>): Promise<number> {
114
+ const where = this.mergeFilter(filter) as FindOptionsWhere<T>;
115
+ return this.repo.count({ where });
81
116
  }
82
117
 
83
118
  findOne(filter: Filter<T>, join?: Join, select?: Select): Promise<T | null> {
84
- const where = this.mapOperators(filter) as FindOptionsWhere<T>;
85
- return this.repo.findOne({
86
- select,
119
+ const where = this.mergeFilter(filter) as FindOptionsWhere<T>;
120
+ return this.repo.findOne({
121
+ select,
87
122
  where,
88
- relations: join
123
+ relations: join
89
124
  });
90
125
  }
91
126
 
92
127
  findOneWhere(filter: Filter<T>, join?: Join, select?: Select): Promise<T | null> {
93
- const where = this.mapOperators(filter) as FindOptionsWhere<T>;
94
- return this.repo.findOne({
128
+ const where = this.mergeFilter(filter) as FindOptionsWhere<T>;
129
+ return this.repo.findOne({
95
130
  select,
96
131
  where,
97
132
  relations: join
@@ -99,7 +134,18 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
99
134
  }
100
135
 
101
136
  async create(data: Partial<T>): Promise<T> {
102
- return this.repo.save(this.repo.create(data as DeepPartial<T>));
137
+ const enriched = { ...data };
138
+ const store = DataIsolationContext.getStore();
139
+ if (store?.userId) {
140
+ const entityName = this.repo.metadata.target instanceof Function
141
+ ? this.repo.metadata.target.name
142
+ : "";
143
+ const config = entityIsolation[entityName];
144
+ if (config && config.field !== "_id") {
145
+ (enriched as any)[config.field] = store.userId;
146
+ }
147
+ }
148
+ return this.repo.save(this.repo.create(enriched as DeepPartial<T>));
103
149
  }
104
150
 
105
151
  async replace(id: string | undefined, data: Partial<T>): Promise<T | null> {
@@ -117,7 +163,8 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
117
163
  utils.log.error("TypeOrmRepositoryAdapter.update called without id — refuse update entity");
118
164
  return null;
119
165
  }
120
- await this.repo.update({ _id: id } as unknown as FindOptionsWhere<T>, data);
166
+ const where = this.mergeFilter({ _id: id } as unknown as Filter<T>);
167
+ await this.repo.update(where as FindOptionsWhere<T>, data);
121
168
  return this.findOne({ _id: id } as unknown as Filter<T>);
122
169
  }
123
170
 
@@ -126,10 +173,12 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
126
173
  utils.log.error("TypeOrmRepositoryAdapter.delete called without id — refuse delete entity");
127
174
  return;
128
175
  }
129
- await this.repo.delete({ _id: id } as unknown as FindOptionsWhere<T>);
176
+ const where = this.mergeFilter({ _id: id } as unknown as Filter<T>);
177
+ await this.repo.delete(where as FindOptionsWhere<T>);
130
178
  }
131
179
 
132
180
  async deleteWhere(filter: Record<string, unknown>): Promise<void> {
133
- await this.repo.delete(filter as FindOptionsWhere<T>);
181
+ const where = this.mergeFilter(filter as unknown as Filter<T>);
182
+ await this.repo.delete(where as FindOptionsWhere<T>);
134
183
  }
135
184
  }
@@ -4,14 +4,15 @@
4
4
  */
5
5
 
6
6
 
7
- import { Select, Filter, Join } from "./VexRequest.gen";
7
+ import { Select, Filter, Join, VexPagination } from "./VexRequest.gen";
8
8
 
9
9
  /**
10
10
  * DB-agnostic repository interface.
11
11
  * Controllers and services talk only to this — the adapter layer (TypeORM/Mongoose) absorbs DB specifics.
12
12
  */
13
13
  export interface VexRepository<T> {
14
- find(filter: Filter<T>, join?: Join, select?: Select): Promise<T[]>;
14
+ find(filter: Filter<T>, join?: Join, select?: Select, pagination?: VexPagination): Promise<T[]>;
15
+ count(filter: Filter<T>): Promise<number>;
15
16
  findOne(filter: Filter<T>, join?: Join, select?: Select): Promise<T | null>;
16
17
  findOneWhere(filter: Filter<T>, join?: Join, select?: Select): Promise<T | null>;
17
18
  create(data: Partial<T>): Promise<T>;
@@ -27,6 +27,21 @@ export type Filter<T = any> = {
27
27
 
28
28
  export type Join = string[];
29
29
 
30
+ export type SortOrder = "ASC" | "DESC";
31
+
32
+ export type VexPagination = {
33
+ page?: number;
34
+ perPage?: number;
35
+ sort?: Record<string, SortOrder>;
36
+ };
37
+
38
+ export type PaginatedResult<T> = {
39
+ data: T[];
40
+ total: number;
41
+ page: number;
42
+ perPage: number;
43
+ };
44
+
30
45
  export interface VexRequest<T = any> {
31
46
  select?: Select;
32
47
  filter?: Filter<T>;
@@ -2,6 +2,9 @@
2
2
  "type": "object",
3
3
  "x-documentConfig": {
4
4
  "documentName": "User",
5
+ "dataIsolation": {
6
+ "field": "_id"
7
+ },
5
8
  "restApi": {
6
9
  "methods": [
7
10
  "get",
@@ -10,6 +13,9 @@
10
13
  "noRelations": true,
11
14
  "joinWhitelist": []
12
15
  },
16
+ "isolate":{
17
+ "user": false
18
+ },
13
19
  "uniqueIndex": [
14
20
  [
15
21
  "email"
@@ -0,0 +1,60 @@
1
+ # API Usage Guide
2
+
3
+ ## Pagination
4
+
5
+ `POST /{resource}/search` Endpoint supportable selection number.
6
+
7
+ ### Request
8
+
9
+ ```json
10
+ POST /api/job/search
11
+ {
12
+ "filter": { "status": "active" },
13
+ "pagination": {
14
+ "page": 1,
15
+ "perPage": 20,
16
+ "sort": { "createdAt": "DESC" }
17
+ }
18
+ }
19
+ ```
20
+
21
+ | Character | Category | Required | Explanation |
22
+ |------|------|------|------|
23
+ | `pagination.page` | number | no |
24
+ | `pagination.perPage` | number | no | number per page, default 20 |
25
+ | `pagination.sort` | object | no | `{ fieldName: "ASC" \| "DESC" }` |
26
+
27
+ ### Response
28
+
29
+ **with `pagination`**
30
+
31
+ ```json
32
+ {
33
+ "ret_code": 200,
34
+ "result": {
35
+ "data": [
36
+ { "id": "abc", "status": "active", ... }
37
+ ],
38
+ "total": 142,
39
+ "page": 1,
40
+ "perPage": 20
41
+ }
42
+ }
43
+ ```
44
+
45
+ **without `pagination`**
46
+
47
+ ```json
48
+ {
49
+ "ret_code": 200,
50
+ "result": [
51
+ { "id": "abc", "status": "active", ... },
52
+ {...}
53
+ ]
54
+ }
55
+ ````
56
+
57
+ ### Default Limits
58
+
59
+ without pagination, search api set row limit 500 as safety upper limit.
60
+ with pagination row limit will follow `perPage`, cap at 9999.
@@ -0,0 +1,49 @@
1
+ # Data Isolation (Row-Level Ownership)
2
+
3
+ Available from v0.6.x. Provides transparent per-entity ownership: all queries are automatically scoped to the authenticated user.
4
+
5
+ ## How it works
6
+
7
+ 1. Declare `dataIsolation` in `x-documentConfig.restApi` of your JSON Schema
8
+ 2. Generator produces `DataIsolationRegistry.gen.ts` mapping entity → ownership field
9
+ 3. `DataIsolationContext` middleware runs before request handlers, storing current user ID in `AsyncLocalStorage`
10
+ 4. `TypeOrmRepositoryAdapter` reads the registry and injects `{ [field]: userId }` into every query
11
+
12
+ ## Configuration
13
+
14
+ ```jsonc
15
+ {
16
+ "x-documentConfig": {
17
+ "documentName": "Project",
18
+ "restApi": {
19
+ "methods": ["get", "getList", "post", "put", "patch", "delete"],
20
+ "dataIsolation": {
21
+ "field": "ownerId"
22
+ }
23
+ }
24
+ },
25
+ "properties": {
26
+ "ownerId": {
27
+ "type": "string",
28
+ "required": true
29
+ },
30
+ "title": {
31
+ "type": "string"
32
+ }
33
+ }
34
+ }
35
+ ```
36
+
37
+ The `field` value references a property on the same document that stores the owner's user ID.
38
+
39
+ ## Behavior
40
+
41
+ - **All queries** — `find`, `findOne`, `update`, `delete` — get an `AND` filter: `{ [field]: currentUserId }`
42
+ - **Create** — the middleware does NOT auto-set the field; the controller must set it from the authenticated user
43
+ - **No userId in context** — if `Authentication` middleware hasn't set a user (e.g., public routes), the ownership filter is skipped
44
+ - **Only affects SQL/TypeORM target** — Mongoose adapter doesn't implement data isolation yet
45
+
46
+ ## Dependencies
47
+
48
+ - Requires authentication (`auth.localAuth: true` or OAuth) to establish request context
49
+ - Works with RBAC — both filters compose (ownership AND role check)
@@ -0,0 +1,59 @@
1
+ # Filter Query Operators
2
+
3
+ The `/search` endpoint accepts a `filter` object with MongoDB-like operators. Supported for both SQL (TypeORM adapter) and planned for Mongo (Mongoose adapter).
4
+
5
+ ## Operators
6
+
7
+ | Operator | Type | Description | SQL Translation |
8
+ |----------|------|-------------|-----------------|
9
+ | `$in` | `string[] \| number[]` | Value in list | `IN (...)` |
10
+ | `$nin` | `string[] \| number[]` | Value not in list | `NOT IN (...)` |
11
+ | `$gt` | `number \| string` | Greater than | `> ` |
12
+ | `$gte` | `number \| string` | Greater than or equal | `>=` |
13
+ | `$lt` | `number \| string` | Less than | `<` |
14
+ | `$lte` | `number \| string` | Less than or equal | `<=` |
15
+ | `$like` | `string` | Pattern match | `LIKE` |
16
+ | `$raw` | `string` | Raw SQL expression | Passed through verbatim |
17
+
18
+ ## Logical operators
19
+
20
+ | Operator | Type | Description |
21
+ |----------|------|-------------|
22
+ | `$and` | `Filter[]` | All conditions must match |
23
+ | `$or` | `Filter[]` | Any condition must match |
24
+
25
+ ## Examples
26
+
27
+ ```jsonc
28
+ // Equality
29
+ { "filter": { "status": "active" } }
30
+
31
+ // Comparison
32
+ { "filter": { "age": { "$gte": 18, "$lte": 65 } } }
33
+
34
+ // Pattern match
35
+ { "filter": { "email": { "$like": "%@example.com" } } }
36
+
37
+ // List membership
38
+ { "filter": { "role": { "$in": ["admin", "moderator"] } } }
39
+
40
+ // Combined
41
+ {
42
+ "filter": {
43
+ "$and": [
44
+ { "status": "active" },
45
+ { "age": { "$gte": 18 } }
46
+ ],
47
+ "$or": [
48
+ { "role": "admin" },
49
+ { "permissions": { "$like": "%manage%" } }
50
+ ]
51
+ }
52
+ }
53
+ ```
54
+
55
+ ## TypeORM safety
56
+
57
+ - `$raw` is passed directly as a TypeORM `FindOptions` raw where — use with caution (SQL injection risk if user-supplied)
58
+ - `$like` value is passed as-is; caller must escape `%` and `_` if needed
59
+ - All other operators are parameterized via TypeORM's `FindOptionsWhere`
@@ -0,0 +1,39 @@
1
+ # Join Whitelist
2
+
3
+ Available from v0.6.x. Controls which relation joins are allowed at the API level.
4
+
5
+ ## Why
6
+
7
+ Foreign-key relations (`x-foreignKey`) generate TypeScript types that include all possible joins. Without a whitelist, any client could request expensive or unintended joins. The whitelist restricts `join` query parameters to an explicit allowlist.
8
+
9
+ ## Configuration
10
+
11
+ ```jsonc
12
+ {
13
+ "x-documentConfig": {
14
+ "documentName": "User",
15
+ "restApi": {
16
+ "methods": ["get", "getList"],
17
+ "joinWhitelist": ["contact", "address"]
18
+ }
19
+ }
20
+ }
21
+ ```
22
+
23
+ If `joinWhitelist` is not set, the preprocessor auto-populates it with ALL detected relations (local FK + reverse FK). To disable all joins, set `joinWhitelist: []`.
24
+
25
+ ## Generated artifacts
26
+
27
+ - `JoinWhitelistRegistry.gen.ts` — Static map of `documentName → { relationName → relatedDocumentName }`
28
+ - `JoinWhitelistMiddleware` — Reads the `join` query param, validates each entry against the registry, strips invalid entries
29
+
30
+ ## Behavior
31
+
32
+ - `GET /{resource}?join=["contact"]` — allowed if "contact" is in whitelist
33
+ - `GET /{resource}?join=["secretRelation"]` — silently removed if not whitelisted
34
+ - The `{DocName}ApiRelations` type only includes whitelisted relations; `{DocName}WithRelations` includes all (for internal use)
35
+ - `noRelations: true` on schema config disables relation types entirely (no `WithRelations` or `WithApiRelations` types)
36
+
37
+ ## To see all available relations
38
+
39
+ The whitelist is written back to your JSON schema file during preprocessing. Check the `x-documentConfig.restApi.joinWhitelist` array in the source `.json` file.
@@ -0,0 +1,62 @@
1
+ # Role-Based Access Control (RBAC)
2
+
3
+ Available from v0.5.x. Document-level permission control per role.
4
+
5
+ ## Configuration
6
+
7
+ Enable RBAC in `vex.config.json`:
8
+
9
+ ```jsonc
10
+ {
11
+ "useRBAC": {
12
+ "roles": ["visitor", "member", "admin"],
13
+ "default": "member"
14
+ }
15
+ }
16
+ ```
17
+
18
+ ## Role files
19
+
20
+ On first generation, `src/roles/{roleName}.json` files are created with default CRUD permissions per document:
21
+
22
+ ```json
23
+ {
24
+ "User": ["create", "read", "update", "delete", "search"],
25
+ "Project": ["create", "read", "update", "delete", "search"]
26
+ }
27
+ ```
28
+
29
+ Edit these files to customize what each role can access. The generator reads them on every run and preserves manual edits.
30
+
31
+ ## User role assignment
32
+
33
+ Mark a field in your user schema with `"x-vexData": "role"`:
34
+
35
+ ```jsonc
36
+ {
37
+ "role": {
38
+ "type": "string",
39
+ "x-vexData": "role",
40
+ "required": true
41
+ }
42
+ }
43
+ ```
44
+
45
+ For SQL/TypeORM target, the preprocessor syncs the role enum values from `useRBAC.roles` in `vex.config.json` into `UserRole.json`.
46
+
47
+ ## Generated artifacts
48
+
49
+ - `src/system/_roles/{roleName}.gen.ts` — Per-role class with permission checking methods
50
+ - `src/system/_roles/index.ts` — Aggregated exports
51
+ - `src/system/_middlewares/RoleBaseAccessControl.gen.ts` — Express middleware that extracts the user's role from the request and validates against the document's allowed methods
52
+
53
+ ## Custom actions
54
+
55
+ Beyond default CRUD, roles can define custom action strings. These are captured in the generated role class and available at runtime.
56
+
57
+ ## Request flow
58
+
59
+ 1. Authentication middleware identifies and attaches user + role to request
60
+ 2. `RoleBaseAccessControl.middleware(documentName)` checks if the user's role has permission for the current HTTP method
61
+ 3. If not authorized, returns 403
62
+ 4. If authorized, request proceeds to the controller
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "very-express",
3
- "version": "0.6.21",
3
+ "version": "0.7.0",
4
4
  "description": "based on json schema and openapi, generate Express RestApi server with mongoDb ",
5
5
  "author": "Justin26l",
6
6
  "license": "MIT",