@gzl10/nexus-sdk 0.1.9 → 0.1.11
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 +45 -5
- package/dist/index.d.ts +23 -8
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -17,7 +17,7 @@ pnpm add @gzl10/nexus-sdk
|
|
|
17
17
|
### Define a module
|
|
18
18
|
|
|
19
19
|
```typescript
|
|
20
|
-
import type { ModuleManifest } from '@gzl10/nexus-sdk'
|
|
20
|
+
import type { ModuleManifest, PluginAuthRequest } from '@gzl10/nexus-sdk'
|
|
21
21
|
|
|
22
22
|
export const tasksModule: ModuleManifest = {
|
|
23
23
|
name: 'tasks',
|
|
@@ -37,6 +37,7 @@ export const tasksModule: ModuleManifest = {
|
|
|
37
37
|
table.string('title').notNullable()
|
|
38
38
|
table.text('description')
|
|
39
39
|
table.boolean('completed').defaultTo(false)
|
|
40
|
+
table.string('created_by').references('id').inTable('users')
|
|
40
41
|
helpers.addTimestamps(table, db)
|
|
41
42
|
})
|
|
42
43
|
}
|
|
@@ -44,10 +45,19 @@ export const tasksModule: ModuleManifest = {
|
|
|
44
45
|
|
|
45
46
|
routes: (ctx) => {
|
|
46
47
|
const router = ctx.createRouter()
|
|
48
|
+
const { abilities, services } = ctx
|
|
49
|
+
|
|
50
|
+
router.get('/', async (req: PluginAuthRequest, res) => {
|
|
51
|
+
// Check permissions with CASL
|
|
52
|
+
abilities.ForbiddenError.from(req.ability).throwUnlessCan('read', 'tasks')
|
|
47
53
|
|
|
48
|
-
router.get('/', async (req, res) => {
|
|
49
54
|
const tasks = await ctx.db('tasks').select('*')
|
|
50
|
-
|
|
55
|
+
|
|
56
|
+
// Resolve user relations
|
|
57
|
+
const userIds = [...new Set(tasks.map(t => t.created_by).filter(Boolean))]
|
|
58
|
+
const users = await services.users?.findByIds(userIds) ?? []
|
|
59
|
+
|
|
60
|
+
res.json({ tasks, users })
|
|
51
61
|
})
|
|
52
62
|
|
|
53
63
|
return router
|
|
@@ -90,14 +100,35 @@ export const projectPlugin: PluginManifest = {
|
|
|
90
100
|
|
|
91
101
|
## Main Types
|
|
92
102
|
|
|
103
|
+
### Manifests & Context
|
|
104
|
+
|
|
93
105
|
| Type | Description |
|
|
94
106
|
|------|-------------|
|
|
95
107
|
| `ModuleManifest` | Defines a module: routes, migrations, seeds, CRUD entities |
|
|
96
108
|
| `PluginManifest` | Groups modules under a plugin with shared metadata |
|
|
97
|
-
| `ModuleContext` | Context injected by Nexus: `db`, `logger`, `helpers`, `
|
|
109
|
+
| `ModuleContext` | Context injected by Nexus: `db`, `logger`, `helpers`, `services`, `abilities` |
|
|
98
110
|
| `ModuleEntity` | Declarative entity configuration for CRUD UI |
|
|
99
111
|
| `FormField` | Form field configuration with validation |
|
|
100
112
|
|
|
113
|
+
### Request & Auth
|
|
114
|
+
|
|
115
|
+
| Type | Description |
|
|
116
|
+
|------|-------------|
|
|
117
|
+
| `AuthRequest<TUser, TAbility>` | Generic authenticated request |
|
|
118
|
+
| `PluginAuthRequest` | Pre-typed `AuthRequest<BaseUser, AbilityLike>` for plugins |
|
|
119
|
+
| `BaseUser` | User without password for relations |
|
|
120
|
+
| `AbilityLike` | Generic CASL ability interface (`can`, `cannot`) |
|
|
121
|
+
|
|
122
|
+
### Services & Utilities
|
|
123
|
+
|
|
124
|
+
| Type | Description |
|
|
125
|
+
|------|-------------|
|
|
126
|
+
| `CoreServices` | Core services container (`users`, etc.) |
|
|
127
|
+
| `UsersResolver` | User lookup service (`findById`, `findByIds`) |
|
|
128
|
+
| `PaginationParams` | Pagination input (`page`, `limit`) |
|
|
129
|
+
| `PaginatedResult<T>` | Paginated response with metadata |
|
|
130
|
+
| `ValidationSchema` | Generic Zod-compatible schema interface |
|
|
131
|
+
|
|
101
132
|
### ModuleContext
|
|
102
133
|
|
|
103
134
|
The context provides access to:
|
|
@@ -106,11 +137,20 @@ The context provides access to:
|
|
|
106
137
|
- `logger` - Pino logger
|
|
107
138
|
- `helpers` - Migration utilities (`addTimestamps`, `addColumnIfMissing`)
|
|
108
139
|
- `createRouter()` - Express Router factory
|
|
109
|
-
- `middleware` -
|
|
140
|
+
- `middleware.validate()` - Request validation with Zod schemas
|
|
110
141
|
- `errors` - Error classes (`AppError`, `NotFoundError`, `UnauthorizedError`, etc.)
|
|
142
|
+
- `abilities` - CASL helpers (`subject`, `ForbiddenError`)
|
|
143
|
+
- `services` - Core services (`users.findById`, `users.findByIds`)
|
|
111
144
|
- `events` - EventEmitter for inter-module communication
|
|
112
145
|
- `mail` - Email sending service
|
|
113
146
|
|
|
147
|
+
### Re-exported Types
|
|
148
|
+
|
|
149
|
+
For convenience, the SDK re-exports commonly used types:
|
|
150
|
+
|
|
151
|
+
- **Express:** `Request`, `Response`, `NextFunction`, `RequestHandler`, `Router`, `CookieOptions`
|
|
152
|
+
- **Knex:** `Knex`, `KnexCreateTableBuilder`, `KnexAlterTableBuilder`, `KnexTransaction`
|
|
153
|
+
|
|
114
154
|
## License
|
|
115
155
|
|
|
116
156
|
MIT © [Gonzalo Díez](https://www.gzl10.com)
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Knex } from 'knex';
|
|
2
|
+
export { Knex } from 'knex';
|
|
2
3
|
import { Request, RequestHandler, Router } from 'express';
|
|
3
4
|
export { CookieOptions, NextFunction, Request, RequestHandler, Response, Router } from 'express';
|
|
4
5
|
import { Logger } from 'pino';
|
|
@@ -11,6 +12,9 @@ import { Logger } from 'pino';
|
|
|
11
12
|
* depending on the full @gzl10/nexus-backend package.
|
|
12
13
|
*/
|
|
13
14
|
|
|
15
|
+
type KnexCreateTableBuilder = Knex.CreateTableBuilder;
|
|
16
|
+
type KnexAlterTableBuilder = Knex.AlterTableBuilder;
|
|
17
|
+
type KnexTransaction = Knex.Transaction;
|
|
14
18
|
/**
|
|
15
19
|
* Request autenticado con usuario y abilities CASL
|
|
16
20
|
* El backend especializa TUser y TAbility con tipos concretos
|
|
@@ -168,16 +172,27 @@ interface MigrationHelpers {
|
|
|
168
172
|
addAuditFieldsIfMissing: (db: Knex, tableName: string) => Promise<void>;
|
|
169
173
|
addColumnIfMissing: (db: Knex, tableName: string, columnName: string, columnBuilder: (table: Knex.AlterTableBuilder) => void) => Promise<boolean>;
|
|
170
174
|
}
|
|
175
|
+
/**
|
|
176
|
+
* Schema de validación genérico (compatible con Zod sin depender de él)
|
|
177
|
+
* Cualquier objeto con método parse() es válido
|
|
178
|
+
*/
|
|
179
|
+
interface ValidationSchema {
|
|
180
|
+
parse: (data: unknown) => unknown;
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Opciones para el middleware de validación
|
|
184
|
+
*/
|
|
185
|
+
interface ValidateSchemas {
|
|
186
|
+
body?: ValidationSchema;
|
|
187
|
+
query?: ValidationSchema;
|
|
188
|
+
params?: ValidationSchema;
|
|
189
|
+
}
|
|
171
190
|
/**
|
|
172
191
|
* Middlewares disponibles en el contexto
|
|
173
192
|
*/
|
|
174
193
|
interface ModuleMiddlewares {
|
|
175
|
-
validate: (schemas:
|
|
176
|
-
|
|
177
|
-
query?: unknown;
|
|
178
|
-
params?: unknown;
|
|
179
|
-
}) => RequestHandler;
|
|
180
|
-
[key: string]: RequestHandler | ((...args: unknown[]) => RequestHandler) | undefined;
|
|
194
|
+
validate: (schemas: ValidateSchemas) => RequestHandler;
|
|
195
|
+
[key: string]: RequestHandler | ((...args: any[]) => RequestHandler) | undefined;
|
|
181
196
|
}
|
|
182
197
|
/**
|
|
183
198
|
* Contexto inyectado a los módulos
|
|
@@ -191,7 +206,7 @@ interface ModuleContext {
|
|
|
191
206
|
createRouter: () => Router;
|
|
192
207
|
middleware: ModuleMiddlewares;
|
|
193
208
|
registerMiddleware: (name: string, handler: RequestHandler) => void;
|
|
194
|
-
config:
|
|
209
|
+
config: {};
|
|
195
210
|
errors: {
|
|
196
211
|
AppError: new (message: string, statusCode?: number) => Error;
|
|
197
212
|
NotFoundError: new (message?: string) => Error;
|
|
@@ -278,4 +293,4 @@ interface PluginManifest {
|
|
|
278
293
|
modules: ModuleManifest[];
|
|
279
294
|
}
|
|
280
295
|
|
|
281
|
-
export type { AbilityLike, AuthRequest, BaseUser, CoreServices, FieldValidation, ForbiddenErrorConstructor, ForbiddenErrorInstance, FormField, FormFieldType, ListType, MigrationHelpers, ModuleAbilities, ModuleContext, ModuleEntity, ModuleManifest, ModuleMiddlewares, ModuleRequirements, PaginatedResult, PaginationParams, PluginAuthRequest, PluginCategory, PluginManifest, UsersResolver };
|
|
296
|
+
export type { AbilityLike, AuthRequest, BaseUser, CoreServices, FieldValidation, ForbiddenErrorConstructor, ForbiddenErrorInstance, FormField, FormFieldType, KnexAlterTableBuilder, KnexCreateTableBuilder, KnexTransaction, ListType, MigrationHelpers, ModuleAbilities, ModuleContext, ModuleEntity, ModuleManifest, ModuleMiddlewares, ModuleRequirements, PaginatedResult, PaginationParams, PluginAuthRequest, PluginCategory, PluginManifest, UsersResolver, ValidateSchemas, ValidationSchema };
|