@telperion/nest-pack 1.0.0 → 1.1.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.
@@ -51,6 +51,36 @@
51
51
  "dcts": "index.d.cts"
52
52
  }
53
53
  },
54
+ {
55
+ "name": "pagination/index",
56
+ "sourcePath": "src/pagination/index.ts",
57
+ "outputs": {
58
+ "esm": "pagination/index.js",
59
+ "cjs": "pagination/index.cjs",
60
+ "dts": "pagination/index.d.ts",
61
+ "dcts": "pagination/index.d.cts"
62
+ }
63
+ },
64
+ {
65
+ "name": "pagination/page-query",
66
+ "sourcePath": "src/pagination/page-query.ts",
67
+ "outputs": {
68
+ "esm": "pagination/page-query.js",
69
+ "cjs": "pagination/page-query.cjs",
70
+ "dts": "pagination/page-query.d.ts",
71
+ "dcts": "pagination/page-query.d.cts"
72
+ }
73
+ },
74
+ {
75
+ "name": "pagination/page",
76
+ "sourcePath": "src/pagination/page.ts",
77
+ "outputs": {
78
+ "esm": "pagination/page.js",
79
+ "cjs": "pagination/page.cjs",
80
+ "dts": "pagination/page.d.ts",
81
+ "dcts": "pagination/page.d.cts"
82
+ }
83
+ },
54
84
  {
55
85
  "name": "validation/index",
56
86
  "sourcePath": "src/validation/index.ts",
@@ -72,5 +102,5 @@
72
102
  }
73
103
  }
74
104
  ],
75
- "generatedAt": "2026-11-30T09:36:10.845Z"
105
+ "generatedAt": "2026-12-01T11:22:52.238Z"
76
106
  }
package/README.md CHANGED
@@ -1,5 +1,5 @@
1
1
  # @telperion/nest-pack
2
- NestJS utilities: access guards and validation helpers
2
+ NestJS utilities: access guards, validation helpers and pagination
3
3
 
4
4
  [![npm](https://img.shields.io/npm/v/@telperion/nest-pack.svg)](https://www.npmjs.com/package/@telperion/nest-pack)
5
5
  [![npm](https://img.shields.io/npm/dm/@telperion/nest-pack.svg)](https://www.npmjs.com/package/@telperion/nest-pack)
@@ -22,8 +22,9 @@ Requires `@nestjs/common` and `@nestjs/core` (11 or 12).
22
22
  | `@telperion/nest-pack` | `createAccessGuard` | |
23
23
  | `@telperion/nest-pack/access` | `createAccessGuard` | |
24
24
  | `@telperion/nest-pack/validation` | `Trim` | `class-transformer` (optional peer dependency); usually with `class-validator` |
25
+ | `@telperion/nest-pack/pagination` | `PageQuery`, `Page` | `class-transformer` and `class-validator` (optional peer dependencies) |
25
26
 
26
- The root entry point does not include `validation`, so projects without class-transformer are not affected.
27
+ The root entry point does not include `validation` or `pagination`, so projects without class-transformer or class-validator are not affected.
27
28
 
28
29
  ## Access
29
30
 
@@ -73,7 +74,24 @@ Nest creates the guard in the module of the controller using it, so its `inject`
73
74
  export class ProjectAccessGuard extends createAccessGuard({ /* ... */ }) {}
74
75
  ```
75
76
 
76
- HTTP only: the guard reads `request.params`.
77
+ HTTP only: the guard reads `request.params`, or the body or query string (see below).
78
+
79
+ #### Reading the id from the body or query string
80
+
81
+ `from` picks where `param` is read: `'params'` (default), `'body'` or `'query'`. With a list, the first source holding a string value is used, e.g. for endpoints that take the id in the path or, without a route parameter, in the body:
82
+
83
+ ```typescript
84
+ export const ProjectMemberGuard = createAccessGuard({
85
+ param: 'projectId',
86
+ from: ['params', 'body'], // /projects/:projectId/..., or { "projectId": "..." } in the body
87
+ validate: isUUID,
88
+ inject: [ProjectsService],
89
+ resolve: (projectId, request: AuthenticatedRequest, projects) => projects.membershipOf(request.user, projectId),
90
+ allows: () => true,
91
+ });
92
+ ```
93
+
94
+ A missing or non-string value answers **404**, like a malformed one; this includes a repeated query parameter (`?projectId=a&projectId=b`), which arrives as an array. Hand-written guards often answer 400 for a missing id instead; the guard keeps 404 so every failed lookup looks the same. The body is read as parsed by Nest's body parser, before any `ValidationPipe` runs.
77
95
 
78
96
  #### Example: two guards, a few lines each
79
97
 
@@ -129,6 +147,62 @@ app.useGlobalPipes(new ValidationPipe({ transform: true }));
129
147
 
130
148
  `ValidationPipe` validates the transformed DTO either way; its `transform` option makes the handler receive the trimmed values too.
131
149
 
150
+ ## Pagination
151
+
152
+ ### Page Query
153
+ The query DTO of a paged list endpoint (`?page=2&pageSize=50&search=ada`), with class-validator and class-transformer decorators:
154
+
155
+ | Property | Rules | Default |
156
+ | --- | --- | --- |
157
+ | `page` | integer, at least 1 | `1` |
158
+ | `pageSize` | integer from 1 to 100 | `25` |
159
+ | `search` | optional string, at most 200 characters | |
160
+
161
+ Query values arrive as strings; `@Type(() => Number)` converts them, so use it with `ValidationPipe({ transform: true })`. Missing values keep their defaults.
162
+
163
+ Two static helpers go with it:
164
+ - `PageQuery.skipTake(query)`: `{ skip, take }` for the page, as TypeORM's and Prisma's options
165
+ - `PageQuery.likePattern(search)`: a `LIKE`/`ILIKE` pattern that contains the search text literally: `\`, `%` and `_` are escaped with `\`, and the text is wrapped in `%`
166
+
167
+ ### Page
168
+ The response of a paged list endpoint: `{ items, total, page, pageSize }`. `Page.of(items, total, query)` creates it.
169
+
170
+ ```typescript
171
+ import { Page, PageQuery } from '@telperion/nest-pack/pagination';
172
+
173
+ @Controller('users')
174
+ export class UsersController {
175
+ @Get()
176
+ async list(@Query() query: PageQuery): Promise<Page<User>> {
177
+ const [items, total] = await this.users.findAndCount({
178
+ where: query.search ? { name: ILike(PageQuery.likePattern(query.search)) } : {},
179
+ order: { name: 'ASC' },
180
+ ...PageQuery.skipTake(query),
181
+ });
182
+
183
+ return Page.of(items, total, query);
184
+ }
185
+ }
186
+ ```
187
+
188
+ Extend `PageQuery` to add filters, or to redeclare a property with other limits:
189
+
190
+ ```typescript
191
+ export class UserPageQuery extends PageQuery {
192
+ @IsOptional()
193
+ @IsIn(['active', 'invited'])
194
+ status?: 'active' | 'invited';
195
+ }
196
+ ```
197
+
198
+ #### Swagger
199
+
200
+ The package does not depend on `@nestjs/swagger`, so the properties carry no `@ApiProperty` decorators. Either:
201
+ - turn on the [Swagger CLI plugin](https://docs.nestjs.com/openapi/cli-plugin) for your DTOs; it reads the types and class-validator decorators, including those of `PageQuery` when your query class extends it (the plugin only annotates files matching its `dtoFileNameSuffix`, so extend it in such a file), or
202
+ - extend `PageQuery` and redeclare the properties with `@ApiPropertyOptional(...)` next to their validators.
203
+
204
+ For the response, declare a subclass per item type (e.g. `class UserPage extends Page<UserDto>` with `@ApiProperty({ type: [UserDto] }) declare readonly items: UserDto[]`) and use it in `@ApiOkResponse({ type: UserPage })`.
205
+
132
206
  ## License
133
207
 
134
208
  [MIT](./LICENSE)
@@ -1,10 +1,16 @@
1
1
  import { InjectionToken, Type, CanActivate } from '@nestjs/common';
2
2
 
3
3
  /**
4
- * The part of an HTTP request an access guard reads: the route parameters
4
+ * A part of an HTTP request an access guard can read the id from: the route parameters, the parsed body or the query string
5
+ */
6
+ type AccessGuardSource = 'params' | 'body' | 'query';
7
+ /**
8
+ * The parts of an HTTP request an access guard reads (see {@link AccessGuardOptions.from})
5
9
  */
6
10
  interface AccessGuardRequest {
7
11
  params?: Record<string, unknown>;
12
+ body?: unknown;
13
+ query?: unknown;
8
14
  }
9
15
  /**
10
16
  * The instances of the injection tokens in {@link AccessGuardOptions.inject}, in order:
@@ -18,9 +24,18 @@ type InjectedDependencies<Tokens extends readonly InjectionToken[]> = {
18
24
  */
19
25
  interface AccessGuardOptions<Access, Requirement, Request extends AccessGuardRequest, Tokens extends readonly InjectionToken[]> {
20
26
  /**
21
- * The route parameter holding the id of what is accessed, e.g. `'projectId'` for `/projects/:projectId/items`
27
+ * The parameter holding the id of what is accessed, e.g. `'projectId'` for `/projects/:projectId/items`.
28
+ * By default a route parameter; see `from` to read a body field or query parameter of that name.
22
29
  */
23
30
  param: string;
31
+ /**
32
+ * Where to read `param` from. With several sources, the first one holding a string value is used,
33
+ * e.g. `['params', 'body']` for routes that take the id in the path or, without a route parameter, in the body.
34
+ * A missing or non-string value (also a repeated query parameter, which arrives as an array) answers 404.
35
+ *
36
+ * @default 'params'
37
+ */
38
+ from?: AccessGuardSource | readonly AccessGuardSource[];
24
39
  /**
25
40
  * Checks the parameter's format before `resolve` runs, e.g. `isUUID` from class-validator.
26
41
  * Malformed values answer 404 without a lookup.
@@ -36,7 +51,7 @@ interface AccessGuardOptions<Access, Requirement, Request extends AccessGuardReq
36
51
  * Resolves the caller's access to what the parameter identifies; `null` or `undefined` when there is none
37
52
  * (no such entity, or the caller may not see it), which answers 404
38
53
  *
39
- * @param value The route parameter, after `validate`
54
+ * @param value The parameter, after `validate`
40
55
  * @param request The HTTP request, e.g. with the authenticated user
41
56
  * @param dependencies The instances of the `inject` tokens
42
57
  */
@@ -78,4 +93,4 @@ interface AccessGuardType<Access, Requirement> extends Type<CanActivate> {
78
93
  accessOf(request: object): Access | undefined;
79
94
  }
80
95
 
81
- export type { AccessGuardOptions, AccessGuardRequest, AccessGuardType, InjectedDependencies };
96
+ export type { AccessGuardOptions, AccessGuardRequest, AccessGuardSource, AccessGuardType, InjectedDependencies };
@@ -1,10 +1,16 @@
1
1
  import { InjectionToken, Type, CanActivate } from '@nestjs/common';
2
2
 
3
3
  /**
4
- * The part of an HTTP request an access guard reads: the route parameters
4
+ * A part of an HTTP request an access guard can read the id from: the route parameters, the parsed body or the query string
5
+ */
6
+ type AccessGuardSource = 'params' | 'body' | 'query';
7
+ /**
8
+ * The parts of an HTTP request an access guard reads (see {@link AccessGuardOptions.from})
5
9
  */
6
10
  interface AccessGuardRequest {
7
11
  params?: Record<string, unknown>;
12
+ body?: unknown;
13
+ query?: unknown;
8
14
  }
9
15
  /**
10
16
  * The instances of the injection tokens in {@link AccessGuardOptions.inject}, in order:
@@ -18,9 +24,18 @@ type InjectedDependencies<Tokens extends readonly InjectionToken[]> = {
18
24
  */
19
25
  interface AccessGuardOptions<Access, Requirement, Request extends AccessGuardRequest, Tokens extends readonly InjectionToken[]> {
20
26
  /**
21
- * The route parameter holding the id of what is accessed, e.g. `'projectId'` for `/projects/:projectId/items`
27
+ * The parameter holding the id of what is accessed, e.g. `'projectId'` for `/projects/:projectId/items`.
28
+ * By default a route parameter; see `from` to read a body field or query parameter of that name.
22
29
  */
23
30
  param: string;
31
+ /**
32
+ * Where to read `param` from. With several sources, the first one holding a string value is used,
33
+ * e.g. `['params', 'body']` for routes that take the id in the path or, without a route parameter, in the body.
34
+ * A missing or non-string value (also a repeated query parameter, which arrives as an array) answers 404.
35
+ *
36
+ * @default 'params'
37
+ */
38
+ from?: AccessGuardSource | readonly AccessGuardSource[];
24
39
  /**
25
40
  * Checks the parameter's format before `resolve` runs, e.g. `isUUID` from class-validator.
26
41
  * Malformed values answer 404 without a lookup.
@@ -36,7 +51,7 @@ interface AccessGuardOptions<Access, Requirement, Request extends AccessGuardReq
36
51
  * Resolves the caller's access to what the parameter identifies; `null` or `undefined` when there is none
37
52
  * (no such entity, or the caller may not see it), which answers 404
38
53
  *
39
- * @param value The route parameter, after `validate`
54
+ * @param value The parameter, after `validate`
40
55
  * @param request The HTTP request, e.g. with the authenticated user
41
56
  * @param dependencies The instances of the `inject` tokens
42
57
  */
@@ -78,4 +93,4 @@ interface AccessGuardType<Access, Requirement> extends Type<CanActivate> {
78
93
  accessOf(request: object): Access | undefined;
79
94
  }
80
95
 
81
- export type { AccessGuardOptions, AccessGuardRequest, AccessGuardType, InjectedDependencies };
96
+ export type { AccessGuardOptions, AccessGuardRequest, AccessGuardSource, AccessGuardType, InjectedDependencies };
@@ -8,9 +8,10 @@ var core = require('@nestjs/core');
8
8
  * #### Create Access Guard
9
9
  *
10
10
  * Creates a guard for routes about one entity, e.g. a project in `/projects/:projectId/...`.
11
- * The guard resolves the caller's access to the entity in a route parameter and checks the route's requirements:
11
+ * The guard resolves the caller's access to the entity in a route parameter (or a body field or query parameter, see `from`)
12
+ * and checks the route's requirements:
12
13
  *
13
- * - malformed parameter (see `validate`), or no access (`resolve` gives `null`/`undefined`): **404**,
14
+ * - missing or malformed parameter (see `validate`), or no access (`resolve` gives `null`/`undefined`): **404**,
14
15
  * so callers can't probe which ids exist
15
16
  * - access that does not meet every requirement of the route (see `allows`): **403**
16
17
  * - otherwise the request passes, and the resolved access is kept on the request for `@Guard.access()`
@@ -50,7 +51,8 @@ var core = require('@nestjs/core');
50
51
  */
51
52
  function createAccessGuard(options) {
52
53
  var AccessGuard_1;
53
- const { param, validate = () => true, inject = [], resolve, allows, notFound = 'Not Found', forbidden = 'Forbidden' } = options;
54
+ const { param, from = 'params', validate = () => true, inject = [], resolve, allows, notFound = 'Not Found', forbidden = 'Forbidden' } = options;
55
+ const sources = typeof from === 'string' ? [from] : from;
54
56
  const requirementsKey = Symbol(`access-guard:${param}:requirements`);
55
57
  const accessKey = Symbol(`access-guard:${param}:access`);
56
58
  let AccessGuard = class AccessGuard {
@@ -72,12 +74,21 @@ function createAccessGuard(options) {
72
74
  static accessOf(request) {
73
75
  return request[accessKey];
74
76
  }
77
+ /**
78
+ * The parameter in the first source holding a string value
79
+ */
80
+ static idOf(request) {
81
+ return sources
82
+ .map(source => request[source])
83
+ .map(holder => (typeof holder === 'object' && holder !== null ? holder[param] : undefined))
84
+ .find((value) => typeof value === 'string');
85
+ }
75
86
  static notGuarded() {
76
87
  throw new Error(`The access of :${param} is read on a route without its access guard; add \`.require()\` to the route or controller`);
77
88
  }
78
89
  canActivate(context) {
79
90
  const request = context.switchToHttp().getRequest();
80
- const value = request.params?.[param];
91
+ const value = AccessGuard_1.idOf(request);
81
92
  const required = this.reflector.getAllAndOverride(requirementsKey, [context.getHandler(), context.getClass()]) ?? [];
82
93
  return Promise.resolve(typeof value === 'string' && validate(value) ? resolve(value, request, ...this.dependencies) : null).then(access => {
83
94
  if (access === null || access === undefined) {
@@ -1 +1 @@
1
- {"version":3,"file":"create-access-guard.cjs","sources":["../../../../libs/nest-pack/src/access/create-access-guard.ts"],"sourcesContent":[null],"names":["createParamDecorator","applyDecorators","SetMetadata","UseGuards","NotFoundException","ForbiddenException","__decorate","Injectable","Reflector","Inject"],"mappings":";;;;;;AAkBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CG;AACG,SAAU,iBAAiB,CAK/B,OAAiE,EAAA;;AACjE,IAAA,MAAM,EAAE,KAAK,EAAE,Q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":["../../../../libs/nest-pack/src/access/create-access-guard.ts"],"sourcesContent":[null],"names":["createParamDecorator","applyDecorators","SetMetadata","UseGuards","NotFoundException","ForbiddenException","__decorate","Injectable","Reflector","Inject"],"mappings":";;;;;;AAkBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CG;AACG,SAAU,iBAAiB,CAK/B,OAAiE,EAAA;;AACjE,IAAA,MAAM,EAAE,KAAK,EAAE,IAAI,GAAG,QAAQ,EAAE,QAAQ,GAAG,MAAM,IAAI,EAAE,MAAM,GAAG,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,GAAG,WAAW,EAAE,SAAS,GAAG,WAAW,EAAE,GAAG,OAAO;AAChJ,IAAA,MAAM,OAAO,GAAiC,OAAO,IAAI,KAAK,QAAQ,GAAG,CAAC,IAAI,CAAC,GAAG,IAAI;IACtF,MAAM,eAAe,GAAG,MAAM,CAAC,gBAAgB,KAAK,CAAA,aAAA,CAAe,CAAC;IACpE,MAAM,SAAS,GAAG,MAAM,CAAC,gBAAgB,KAAK,CAAA,OAAA,CAAS,CAAC;IAExD,IACM,WAAW,GADjB,MACM,WAAW,CAAA;;AACf,QAAA,OAAgB,MAAM,GAAGA,2BAAoB,CAC3C,CAAC,KAAc,EAAE,OAAyB,KACxC,aAAW,CAAC,QAAQ,CAAC,OAAO,CAAC,YAAY,EAAE,CAAC,UAAU,EAAU,CAAC,IAAI,aAAW,CAAC,UAAU,EAAE,CAChG;AAEgB,QAAA,SAAS;AACT,QAAA,YAAY;AAE7B;;AAEG;AACH,QAAA,WAAA,CAAY,GAAG,QAAmC,EAAA;YAChD,MAAM,CAAC,SAAS,EAAE,GAAG,YAAY,CAAC,GAAG,QAAQ;AAE7C,YAAA,IAAI,CAAC,SAAS,GAAG,SAAS;AAC1B,YAAA,IAAI,CAAC,YAAY,GAAG,YAA4C;QAClE;AAEA,QAAA,OAAO,OAAO,CAA0B,GAAG,YAA2B,EAAA;AACpE,YAA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AK,SAAS,EAAE;AAC3C,oBAAA,MAAM,IAAIC,wBAAiB,CAAC,QAAQ,CAAC;gBACvC;AAEA,gBAAA,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,WAAW,IAAI,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC,EAAE;AAC/D,oBAAA,MAAM,IAAIC,yBAAkB,CAAC,SAAS,CAAC;gBACzC;AAEA,gBAAA,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,EAAE,CAAC,SAAS,GAAG,MAAM,EAAE,CAAC;AAE/C,gBAAA,OAAO,IAAI;AACb,YAAA,CAAC,CAAC;QACJ;;IA3DI,WAAW,GAAA,aAAA,GAAAC,gBAAA,CAAA;AADhB,QAAAC,iBAAU,EAAE;;AACP,KAAA,EAAA,WAAW,CA4DhB;IAED,CAACC,cAAS,EAAE,GAAG,MAAM,CAAC,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,KAAK,KAAKC,aAAM,CAAC,KAAK,CAAC,CAAC,WAAW,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC;AAE9F,IAAA,OAAO,WAAW;AACpB;;;;"}
@@ -5,9 +5,10 @@ import { InjectionToken } from '@nestjs/common';
5
5
  * #### Create Access Guard
6
6
  *
7
7
  * Creates a guard for routes about one entity, e.g. a project in `/projects/:projectId/...`.
8
- * The guard resolves the caller's access to the entity in a route parameter and checks the route's requirements:
8
+ * The guard resolves the caller's access to the entity in a route parameter (or a body field or query parameter, see `from`)
9
+ * and checks the route's requirements:
9
10
  *
10
- * - malformed parameter (see `validate`), or no access (`resolve` gives `null`/`undefined`): **404**,
11
+ * - missing or malformed parameter (see `validate`), or no access (`resolve` gives `null`/`undefined`): **404**,
11
12
  * so callers can't probe which ids exist
12
13
  * - access that does not meet every requirement of the route (see `allows`): **403**
13
14
  * - otherwise the request passes, and the resolved access is kept on the request for `@Guard.access()`
@@ -5,9 +5,10 @@ import { InjectionToken } from '@nestjs/common';
5
5
  * #### Create Access Guard
6
6
  *
7
7
  * Creates a guard for routes about one entity, e.g. a project in `/projects/:projectId/...`.
8
- * The guard resolves the caller's access to the entity in a route parameter and checks the route's requirements:
8
+ * The guard resolves the caller's access to the entity in a route parameter (or a body field or query parameter, see `from`)
9
+ * and checks the route's requirements:
9
10
  *
10
- * - malformed parameter (see `validate`), or no access (`resolve` gives `null`/`undefined`): **404**,
11
+ * - missing or malformed parameter (see `validate`), or no access (`resolve` gives `null`/`undefined`): **404**,
11
12
  * so callers can't probe which ids exist
12
13
  * - access that does not meet every requirement of the route (see `allows`): **403**
13
14
  * - otherwise the request passes, and the resolved access is kept on the request for `@Guard.access()`
@@ -6,9 +6,10 @@ import { Reflector } from '@nestjs/core';
6
6
  * #### Create Access Guard
7
7
  *
8
8
  * Creates a guard for routes about one entity, e.g. a project in `/projects/:projectId/...`.
9
- * The guard resolves the caller's access to the entity in a route parameter and checks the route's requirements:
9
+ * The guard resolves the caller's access to the entity in a route parameter (or a body field or query parameter, see `from`)
10
+ * and checks the route's requirements:
10
11
  *
11
- * - malformed parameter (see `validate`), or no access (`resolve` gives `null`/`undefined`): **404**,
12
+ * - missing or malformed parameter (see `validate`), or no access (`resolve` gives `null`/`undefined`): **404**,
12
13
  * so callers can't probe which ids exist
13
14
  * - access that does not meet every requirement of the route (see `allows`): **403**
14
15
  * - otherwise the request passes, and the resolved access is kept on the request for `@Guard.access()`
@@ -48,7 +49,8 @@ import { Reflector } from '@nestjs/core';
48
49
  */
49
50
  function createAccessGuard(options) {
50
51
  var AccessGuard_1;
51
- const { param, validate = () => true, inject = [], resolve, allows, notFound = 'Not Found', forbidden = 'Forbidden' } = options;
52
+ const { param, from = 'params', validate = () => true, inject = [], resolve, allows, notFound = 'Not Found', forbidden = 'Forbidden' } = options;
53
+ const sources = typeof from === 'string' ? [from] : from;
52
54
  const requirementsKey = Symbol(`access-guard:${param}:requirements`);
53
55
  const accessKey = Symbol(`access-guard:${param}:access`);
54
56
  let AccessGuard = class AccessGuard {
@@ -70,12 +72,21 @@ function createAccessGuard(options) {
70
72
  static accessOf(request) {
71
73
  return request[accessKey];
72
74
  }
75
+ /**
76
+ * The parameter in the first source holding a string value
77
+ */
78
+ static idOf(request) {
79
+ return sources
80
+ .map(source => request[source])
81
+ .map(holder => (typeof holder === 'object' && holder !== null ? holder[param] : undefined))
82
+ .find((value) => typeof value === 'string');
83
+ }
73
84
  static notGuarded() {
74
85
  throw new Error(`The access of :${param} is read on a route without its access guard; add \`.require()\` to the route or controller`);
75
86
  }
76
87
  canActivate(context) {
77
88
  const request = context.switchToHttp().getRequest();
78
- const value = request.params?.[param];
89
+ const value = AccessGuard_1.idOf(request);
79
90
  const required = this.reflector.getAllAndOverride(requirementsKey, [context.getHandler(), context.getClass()]) ?? [];
80
91
  return Promise.resolve(typeof value === 'string' && validate(value) ? resolve(value, request, ...this.dependencies) : null).then(access => {
81
92
  if (access === null || access === undefined) {
@@ -1 +1 @@
1
- {"version":3,"file":"create-access-guard.js","sources":["../../../../libs/nest-pack/src/access/create-access-guard.ts"],"sourcesContent":[null],"names":[],"mappings":";;;;AAkBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CG;AACG,SAAU,iBAAiB,CAK/B,OAAiE,EAAA;;AACjE,IAAA,MAAM,EAAE,KAAK,EAAE,QAAQ,GAAG,MAAM,IAAI,EAAE,MAAM,GAAG,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,GAAG,WAAW,EAAE,SAAS,GAAG,WAAW,EAAE,GAAG,OAAO;IAC/H,MAAM,eAAe,GAAG,MAAM,CAAC,gBAAgB,KAAK,CAAA,aAAA,CAAe,CAAC;IACpE,MAAM,SAAS,GAAG,MAAM,CAAC,gBAAgB,KAAK,CAAA,OAAA,CAAS,CAAC;IAExD,IACM,WAAW,GADjB,MACM,WAAW,CAAA;;AACf,QAAA,OAAgB,MAAM,GAAG,oBAAoB,CAC3C,CAAC,KAAc,EAAE,OAAyB,KACxC,aAAW,CAAC,QAAQ,C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CAAC,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,KAAK,KAAK,MAAM,CAAC,KAAK,CAAC,CAAC,WAAW,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC;AAE9F,IAAA,OAAO,WAAW;AACpB;;;;"}
@@ -1,3 +1,3 @@
1
- export { AccessGuardOptions, AccessGuardRequest, AccessGuardType, InjectedDependencies } from './access-guard-options.cjs';
1
+ export { AccessGuardOptions, AccessGuardRequest, AccessGuardSource, AccessGuardType, InjectedDependencies } from './access-guard-options.cjs';
2
2
  export { createAccessGuard } from './create-access-guard.cjs';
3
3
  import '@nestjs/common';
package/access/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- export { AccessGuardOptions, AccessGuardRequest, AccessGuardType, InjectedDependencies } from './access-guard-options.js';
1
+ export { AccessGuardOptions, AccessGuardRequest, AccessGuardSource, AccessGuardType, InjectedDependencies } from './access-guard-options.js';
2
2
  export { createAccessGuard } from './create-access-guard.js';
3
3
  import '@nestjs/common';
@@ -6,9 +6,10 @@ import { Reflector } from '@nestjs/core';
6
6
  * #### Create Access Guard
7
7
  *
8
8
  * Creates a guard for routes about one entity, e.g. a project in `/projects/:projectId/...`.
9
- * The guard resolves the caller's access to the entity in a route parameter and checks the route's requirements:
9
+ * The guard resolves the caller's access to the entity in a route parameter (or a body field or query parameter, see `from`)
10
+ * and checks the route's requirements:
10
11
  *
11
- * - malformed parameter (see `validate`), or no access (`resolve` gives `null`/`undefined`): **404**,
12
+ * - missing or malformed parameter (see `validate`), or no access (`resolve` gives `null`/`undefined`): **404**,
12
13
  * so callers can't probe which ids exist
13
14
  * - access that does not meet every requirement of the route (see `allows`): **403**
14
15
  * - otherwise the request passes, and the resolved access is kept on the request for `@Guard.access()`
@@ -48,7 +49,8 @@ import { Reflector } from '@nestjs/core';
48
49
  */
49
50
  function createAccessGuard(options) {
50
51
  var AccessGuard_1;
51
- const { param, validate = () => true, inject = [], resolve, allows, notFound = 'Not Found', forbidden = 'Forbidden' } = options;
52
+ const { param, from = 'params', validate = () => true, inject = [], resolve, allows, notFound = 'Not Found', forbidden = 'Forbidden' } = options;
53
+ const sources = typeof from === 'string' ? [from] : from;
52
54
  const requirementsKey = Symbol(`access-guard:${param}:requirements`);
53
55
  const accessKey = Symbol(`access-guard:${param}:access`);
54
56
  let AccessGuard = class AccessGuard {
@@ -70,12 +72,21 @@ function createAccessGuard(options) {
70
72
  static accessOf(request) {
71
73
  return request[accessKey];
72
74
  }
75
+ /**
76
+ * The parameter in the first source holding a string value
77
+ */
78
+ static idOf(request) {
79
+ return sources
80
+ .map(source => request[source])
81
+ .map(holder => (typeof holder === 'object' && holder !== null ? holder[param] : undefined))
82
+ .find((value) => typeof value === 'string');
83
+ }
73
84
  static notGuarded() {
74
85
  throw new Error(`The access of :${param} is read on a route without its access guard; add \`.require()\` to the route or controller`);
75
86
  }
76
87
  canActivate(context) {
77
88
  const request = context.switchToHttp().getRequest();
78
- const value = request.params?.[param];
89
+ const value = AccessGuard_1.idOf(request);
79
90
  const required = this.reflector.getAllAndOverride(requirementsKey, [context.getHandler(), context.getClass()]) ?? [];
80
91
  return Promise.resolve(typeof value === 'string' && validate(value) ? resolve(value, request, ...this.dependencies) : null).then(access => {
81
92
  if (access === null || access === undefined) {
@@ -1 +1 @@
1
- {"version":3,"file":"nest-pack.mjs","sources":["../../../../libs/nest-pack/src/access/create-access-guard.ts"],"sourcesContent":[null],"names":[],"mappings":";;;;AAkBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CG;AACG,SAAU,iBAAiB,CAK/B,OAAiE,EAAA;;AACjE,IAAA,MAAM,EAAE,KAAK,EAAE,QAAQ,GAAG,MAAM,IAAI,EAAE,MAAM,GAAG,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,GAAG,WAAW,EAAE,SAAS,GAAG,WAAW,EAAE,GAAG,OAAO;IAC/H,MAAM,eAAe,GAAG,MAAM,CAAC,gBAAgB,KAAK,CAAA,aAAA,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AAC,SAAS,GAAG,MAAM,EAAE,CAAC;AAE/C,gBAAA,OAAO,IAAI;AACb,YAAA,CAAC,CAAC;QACJ;;IA3DI,WAAW,GAAA,aAAA,GAAA,UAAA,CAAA;AADhB,QAAA,UAAU,EAAE;;AACP,KAAA,EAAA,WAAW,CA4DhB;IAED,CAAC,SAAS,EAAE,GAAG,MAAM,CAAC,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,KAAK,KAAK,MAAM,CAAC,KAAK,CAAC,CAAC,WAAW,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC;AAE9F,IAAA,OAAO,WAAW;AACpB;;;;"}
package/index.d.cts CHANGED
@@ -1,3 +1,3 @@
1
- export { AccessGuardOptions, AccessGuardRequest, AccessGuardType, InjectedDependencies } from './access/access-guard-options.cjs';
1
+ export { AccessGuardOptions, AccessGuardRequest, AccessGuardSource, AccessGuardType, InjectedDependencies } from './access/access-guard-options.cjs';
2
2
  export { createAccessGuard } from './access/create-access-guard.cjs';
3
3
  import '@nestjs/common';
package/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- export { AccessGuardOptions, AccessGuardRequest, AccessGuardType, InjectedDependencies } from './access/access-guard-options.js';
1
+ export { AccessGuardOptions, AccessGuardRequest, AccessGuardSource, AccessGuardType, InjectedDependencies } from './access/access-guard-options.js';
2
2
  export { createAccessGuard } from './access/create-access-guard.js';
3
3
  import '@nestjs/common';
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@telperion/nest-pack",
3
- "version": "1.0.0",
4
- "description": "NestJS utilities: access guards and validation helpers",
3
+ "version": "1.1.0",
4
+ "description": "NestJS utilities: access guards, validation helpers and pagination",
5
5
  "keywords": [
6
6
  "nestjs",
7
7
  "nest",
@@ -13,7 +13,10 @@
13
13
  "class-transformer",
14
14
  "class-validator",
15
15
  "validation",
16
- "trim"
16
+ "trim",
17
+ "pagination",
18
+ "paging",
19
+ "dto"
17
20
  ],
18
21
  "homepage": "https://github.com/telperiontech/telperion/tree/main/libs/nest-pack#readme",
19
22
  "repository": {
@@ -105,6 +108,46 @@
105
108
  "node": "./access/index.cjs",
106
109
  "default": "./access/index.js"
107
110
  },
111
+ "./pagination/index": {
112
+ "types": {
113
+ "import": "./pagination/index.d.ts",
114
+ "require": "./pagination/index.d.cts"
115
+ },
116
+ "import": "./pagination/index.js",
117
+ "require": "./pagination/index.cjs",
118
+ "node": "./pagination/index.cjs",
119
+ "default": "./pagination/index.js"
120
+ },
121
+ "./pagination": {
122
+ "types": {
123
+ "import": "./pagination/index.d.ts",
124
+ "require": "./pagination/index.d.cts"
125
+ },
126
+ "import": "./pagination/index.js",
127
+ "require": "./pagination/index.cjs",
128
+ "node": "./pagination/index.cjs",
129
+ "default": "./pagination/index.js"
130
+ },
131
+ "./pagination/page-query": {
132
+ "types": {
133
+ "import": "./pagination/page-query.d.ts",
134
+ "require": "./pagination/page-query.d.cts"
135
+ },
136
+ "import": "./pagination/page-query.js",
137
+ "require": "./pagination/page-query.cjs",
138
+ "node": "./pagination/page-query.cjs",
139
+ "default": "./pagination/page-query.js"
140
+ },
141
+ "./pagination/page": {
142
+ "types": {
143
+ "import": "./pagination/page.d.ts",
144
+ "require": "./pagination/page.d.cts"
145
+ },
146
+ "import": "./pagination/page.js",
147
+ "require": "./pagination/page.cjs",
148
+ "node": "./pagination/page.cjs",
149
+ "default": "./pagination/page.js"
150
+ },
108
151
  "./validation/index": {
109
152
  "types": {
110
153
  "import": "./validation/index.d.ts",
@@ -0,0 +1,10 @@
1
+ 'use strict';
2
+
3
+ var pagination_page = require('./page.cjs');
4
+ var pagination_pageQuery = require('./page-query.cjs');
5
+
6
+
7
+
8
+ exports.Page = pagination_page.Page;
9
+ exports.PageQuery = pagination_pageQuery.PageQuery;
10
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;"}
@@ -0,0 +1,2 @@
1
+ export { Page } from './page.cjs';
2
+ export { PageQuery } from './page-query.cjs';
@@ -0,0 +1,2 @@
1
+ export { Page } from './page.js';
2
+ export { PageQuery } from './page-query.js';
@@ -0,0 +1,3 @@
1
+ export { Page } from './page.js';
2
+ export { PageQuery } from './page-query.js';
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";"}
@@ -0,0 +1,92 @@
1
+ 'use strict';
2
+
3
+ var tslib = require('tslib');
4
+ var classTransformer = require('class-transformer');
5
+ var classValidator = require('class-validator');
6
+
7
+ /**
8
+ * #### Page Query
9
+ *
10
+ * Query DTO of a paged list endpoint: `?page=2&pageSize=50&search=ada`.
11
+ * Query values arrive as strings and are converted to numbers (`@Type(() => Number)`), so use it with
12
+ * `ValidationPipe({ transform: true })`; missing values keep their defaults.
13
+ *
14
+ * - `page`: integer, at least 1, default 1
15
+ * - `pageSize`: integer from 1 to 100, default 25
16
+ * - `search`: optional free text, at most 200 characters
17
+ *
18
+ * Extend it to add filters or to redeclare a property with other limits or Swagger metadata.
19
+ * Requires `class-transformer` and `class-validator` in your project.
20
+ *
21
+ * * * *
22
+ * Example:
23
+ * ```typescript
24
+ * import { Page, PageQuery } from '@telperion/nest-pack/pagination';
25
+ *
26
+ * @Get()
27
+ * async list(@Query() query: PageQuery): Promise<Page<User>> {
28
+ * const [items, total] = await this.users.findAndCount({
29
+ * where: query.search ? { name: ILike(PageQuery.likePattern(query.search)) } : {},
30
+ * ...PageQuery.skipTake(query),
31
+ * });
32
+ *
33
+ * return Page.of(items, total, query);
34
+ * }
35
+ * ```
36
+ * * * *
37
+ */
38
+ class PageQuery {
39
+ /**
40
+ * The page, from 1
41
+ */
42
+ page = 1;
43
+ /**
44
+ * The items per page, from 1 to 100
45
+ */
46
+ pageSize = 25;
47
+ /**
48
+ * Free-text search, at most 200 characters
49
+ */
50
+ search;
51
+ /**
52
+ * The rows to skip and to take for a page, as TypeORM's and Prisma's `skip` and `take` options
53
+ *
54
+ * @param query The page and page size
55
+ */
56
+ static skipTake(query) {
57
+ return { skip: (query.page - 1) * query.pageSize, take: query.pageSize };
58
+ }
59
+ /**
60
+ * A `LIKE`/`ILIKE` pattern matching values that contain the search text literally:
61
+ * `\`, `%` and `_` are escaped with `\` (the default escape character of PostgreSQL and MySQL), and the text is wrapped in `%`
62
+ *
63
+ * @param search The search text
64
+ */
65
+ static likePattern(search) {
66
+ return `%${search.replace(/[\\%_]/g, character => `\\${character}`)}%`;
67
+ }
68
+ }
69
+ tslib.__decorate([
70
+ classValidator.IsOptional(),
71
+ classTransformer.Type(() => Number),
72
+ classValidator.IsInt(),
73
+ classValidator.Min(1),
74
+ tslib.__metadata("design:type", Number)
75
+ ], PageQuery.prototype, "page", void 0);
76
+ tslib.__decorate([
77
+ classValidator.IsOptional(),
78
+ classTransformer.Type(() => Number),
79
+ classValidator.IsInt(),
80
+ classValidator.Min(1),
81
+ classValidator.Max(100),
82
+ tslib.__metadata("design:type", Number)
83
+ ], PageQuery.prototype, "pageSize", void 0);
84
+ tslib.__decorate([
85
+ classValidator.IsOptional(),
86
+ classValidator.IsString(),
87
+ classValidator.MaxLength(200),
88
+ tslib.__metadata("design:type", String)
89
+ ], PageQuery.prototype, "search", void 0);
90
+
91
+ exports.PageQuery = PageQuery;
92
+ //# sourceMappingURL=page-query.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"page-query.cjs","sources":["../../../../libs/nest-pack/src/pagination/page-query.ts"],"sourcesContent":[null],"names":["__decorate","IsOptional","Type","IsInt","Min","Max","IsString","MaxLength"],"mappings":";;;;;;AAGA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BG;MACU,SAAS,CAAA;AACpB;;AAEG;IAKH,IAAI,GAAW,CAAC;AAEhB;;AAEG;IAMH,QAAQ,GAAW,EAAE;AAErB;;AAEG;AAIH,IAAA,MAAM;AAEN;;;;AAIG;IACH,OAAO,QAAQ,CAAC,KAA2C,EAAA;QACzD,OAAO,EAAE,IAAI,EAAE,CAAC,KAAK,CAAC,IAAI,GAAG,CAAC,IAAI,KAAK,CAAC,QAAQ,EAAE,IAAI,EAAE,KAAK,CAAC,QAAQ,EAAE;IAC1E;AAEA;;;;;AAKG;IACH,OAAO,WAAW,CAAC,MAAc,EAAA;AAC/B,QAAA,OAAO,IAAI,MAAM,CAAC,OAAO,CAAC,SAAS,EAAE,SAAS,IAAI,CAAA,EAAA,EAAK,SAAS,CAAA,CAAE,CAAC,GAAG;IACxE;AACD;AAtCCA,gBAAA,CAAA;AAJC,IAAAC,yBAAU,EAAE;AACZ,IAAAC,qBAAI,CAAC,MAAM,MAAM,CAAC;AAClB,IAAAC,oBAAK,EAAE;IACPC,kBAAG,CAAC,CAAC,CAAC;;AACU,CAAA,EAAA,SAAA,CAAA,SAAA,EAAA,MAAA,EAAA,MAAA,CAAA;AAUjBJ,gBAAA,CAAA;AALC,IAAAC,yBAAU,EAAE;AACZ,IAAAC,qBAAI,CAAC,MAAM,MAAM,CAAC;AAClB,IAAAC,oBAAK,EAAE;IACPC,kBAAG,CAAC,CAAC,CAAC;IACNC,kBAAG,CAAC,GAAG,CAAC;;AACa,CAAA,EAAA,SAAA,CAAA,SAAA,EAAA,UAAA,EAAA,MAAA,CAAA;AAQtBL,gBAAA,CAAA;AAHC,IAAAC,yBAAU,EAAE;AACZ,IAAAK,uBAAQ,EAAE;IACVC,wBAAS,CAAC,GAAG,CAAC;;AACC,CAAA,EAAA,SAAA,CAAA,SAAA,EAAA,QAAA,EAAA,MAAA,CAAA;;;;"}
@@ -0,0 +1,63 @@
1
+ /**
2
+ * #### Page Query
3
+ *
4
+ * Query DTO of a paged list endpoint: `?page=2&pageSize=50&search=ada`.
5
+ * Query values arrive as strings and are converted to numbers (`@Type(() => Number)`), so use it with
6
+ * `ValidationPipe({ transform: true })`; missing values keep their defaults.
7
+ *
8
+ * - `page`: integer, at least 1, default 1
9
+ * - `pageSize`: integer from 1 to 100, default 25
10
+ * - `search`: optional free text, at most 200 characters
11
+ *
12
+ * Extend it to add filters or to redeclare a property with other limits or Swagger metadata.
13
+ * Requires `class-transformer` and `class-validator` in your project.
14
+ *
15
+ * * * *
16
+ * Example:
17
+ * ```typescript
18
+ * import { Page, PageQuery } from '@telperion/nest-pack/pagination';
19
+ *
20
+ * @Get()
21
+ * async list(@Query() query: PageQuery): Promise<Page<User>> {
22
+ * const [items, total] = await this.users.findAndCount({
23
+ * where: query.search ? { name: ILike(PageQuery.likePattern(query.search)) } : {},
24
+ * ...PageQuery.skipTake(query),
25
+ * });
26
+ *
27
+ * return Page.of(items, total, query);
28
+ * }
29
+ * ```
30
+ * * * *
31
+ */
32
+ declare class PageQuery {
33
+ /**
34
+ * The page, from 1
35
+ */
36
+ page: number;
37
+ /**
38
+ * The items per page, from 1 to 100
39
+ */
40
+ pageSize: number;
41
+ /**
42
+ * Free-text search, at most 200 characters
43
+ */
44
+ search?: string;
45
+ /**
46
+ * The rows to skip and to take for a page, as TypeORM's and Prisma's `skip` and `take` options
47
+ *
48
+ * @param query The page and page size
49
+ */
50
+ static skipTake(query: Pick<PageQuery, 'page' | 'pageSize'>): {
51
+ skip: number;
52
+ take: number;
53
+ };
54
+ /**
55
+ * A `LIKE`/`ILIKE` pattern matching values that contain the search text literally:
56
+ * `\`, `%` and `_` are escaped with `\` (the default escape character of PostgreSQL and MySQL), and the text is wrapped in `%`
57
+ *
58
+ * @param search The search text
59
+ */
60
+ static likePattern(search: string): string;
61
+ }
62
+
63
+ export { PageQuery };
@@ -0,0 +1,63 @@
1
+ /**
2
+ * #### Page Query
3
+ *
4
+ * Query DTO of a paged list endpoint: `?page=2&pageSize=50&search=ada`.
5
+ * Query values arrive as strings and are converted to numbers (`@Type(() => Number)`), so use it with
6
+ * `ValidationPipe({ transform: true })`; missing values keep their defaults.
7
+ *
8
+ * - `page`: integer, at least 1, default 1
9
+ * - `pageSize`: integer from 1 to 100, default 25
10
+ * - `search`: optional free text, at most 200 characters
11
+ *
12
+ * Extend it to add filters or to redeclare a property with other limits or Swagger metadata.
13
+ * Requires `class-transformer` and `class-validator` in your project.
14
+ *
15
+ * * * *
16
+ * Example:
17
+ * ```typescript
18
+ * import { Page, PageQuery } from '@telperion/nest-pack/pagination';
19
+ *
20
+ * @Get()
21
+ * async list(@Query() query: PageQuery): Promise<Page<User>> {
22
+ * const [items, total] = await this.users.findAndCount({
23
+ * where: query.search ? { name: ILike(PageQuery.likePattern(query.search)) } : {},
24
+ * ...PageQuery.skipTake(query),
25
+ * });
26
+ *
27
+ * return Page.of(items, total, query);
28
+ * }
29
+ * ```
30
+ * * * *
31
+ */
32
+ declare class PageQuery {
33
+ /**
34
+ * The page, from 1
35
+ */
36
+ page: number;
37
+ /**
38
+ * The items per page, from 1 to 100
39
+ */
40
+ pageSize: number;
41
+ /**
42
+ * Free-text search, at most 200 characters
43
+ */
44
+ search?: string;
45
+ /**
46
+ * The rows to skip and to take for a page, as TypeORM's and Prisma's `skip` and `take` options
47
+ *
48
+ * @param query The page and page size
49
+ */
50
+ static skipTake(query: Pick<PageQuery, 'page' | 'pageSize'>): {
51
+ skip: number;
52
+ take: number;
53
+ };
54
+ /**
55
+ * A `LIKE`/`ILIKE` pattern matching values that contain the search text literally:
56
+ * `\`, `%` and `_` are escaped with `\` (the default escape character of PostgreSQL and MySQL), and the text is wrapped in `%`
57
+ *
58
+ * @param search The search text
59
+ */
60
+ static likePattern(search: string): string;
61
+ }
62
+
63
+ export { PageQuery };
@@ -0,0 +1,90 @@
1
+ import { __decorate, __metadata } from 'tslib';
2
+ import { Type } from 'class-transformer';
3
+ import { IsOptional, IsInt, Min, Max, IsString, MaxLength } from 'class-validator';
4
+
5
+ /**
6
+ * #### Page Query
7
+ *
8
+ * Query DTO of a paged list endpoint: `?page=2&pageSize=50&search=ada`.
9
+ * Query values arrive as strings and are converted to numbers (`@Type(() => Number)`), so use it with
10
+ * `ValidationPipe({ transform: true })`; missing values keep their defaults.
11
+ *
12
+ * - `page`: integer, at least 1, default 1
13
+ * - `pageSize`: integer from 1 to 100, default 25
14
+ * - `search`: optional free text, at most 200 characters
15
+ *
16
+ * Extend it to add filters or to redeclare a property with other limits or Swagger metadata.
17
+ * Requires `class-transformer` and `class-validator` in your project.
18
+ *
19
+ * * * *
20
+ * Example:
21
+ * ```typescript
22
+ * import { Page, PageQuery } from '@telperion/nest-pack/pagination';
23
+ *
24
+ * @Get()
25
+ * async list(@Query() query: PageQuery): Promise<Page<User>> {
26
+ * const [items, total] = await this.users.findAndCount({
27
+ * where: query.search ? { name: ILike(PageQuery.likePattern(query.search)) } : {},
28
+ * ...PageQuery.skipTake(query),
29
+ * });
30
+ *
31
+ * return Page.of(items, total, query);
32
+ * }
33
+ * ```
34
+ * * * *
35
+ */
36
+ class PageQuery {
37
+ /**
38
+ * The page, from 1
39
+ */
40
+ page = 1;
41
+ /**
42
+ * The items per page, from 1 to 100
43
+ */
44
+ pageSize = 25;
45
+ /**
46
+ * Free-text search, at most 200 characters
47
+ */
48
+ search;
49
+ /**
50
+ * The rows to skip and to take for a page, as TypeORM's and Prisma's `skip` and `take` options
51
+ *
52
+ * @param query The page and page size
53
+ */
54
+ static skipTake(query) {
55
+ return { skip: (query.page - 1) * query.pageSize, take: query.pageSize };
56
+ }
57
+ /**
58
+ * A `LIKE`/`ILIKE` pattern matching values that contain the search text literally:
59
+ * `\`, `%` and `_` are escaped with `\` (the default escape character of PostgreSQL and MySQL), and the text is wrapped in `%`
60
+ *
61
+ * @param search The search text
62
+ */
63
+ static likePattern(search) {
64
+ return `%${search.replace(/[\\%_]/g, character => `\\${character}`)}%`;
65
+ }
66
+ }
67
+ __decorate([
68
+ IsOptional(),
69
+ Type(() => Number),
70
+ IsInt(),
71
+ Min(1),
72
+ __metadata("design:type", Number)
73
+ ], PageQuery.prototype, "page", void 0);
74
+ __decorate([
75
+ IsOptional(),
76
+ Type(() => Number),
77
+ IsInt(),
78
+ Min(1),
79
+ Max(100),
80
+ __metadata("design:type", Number)
81
+ ], PageQuery.prototype, "pageSize", void 0);
82
+ __decorate([
83
+ IsOptional(),
84
+ IsString(),
85
+ MaxLength(200),
86
+ __metadata("design:type", String)
87
+ ], PageQuery.prototype, "search", void 0);
88
+
89
+ export { PageQuery };
90
+ //# sourceMappingURL=page-query.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"page-query.js","sources":["../../../../libs/nest-pack/src/pagination/page-query.ts"],"sourcesContent":[null],"names":[],"mappings":";;;;AAGA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BG;MACU,SAAS,CAAA;AACpB;;AAEG;IAKH,IAAI,GAAW,CAAC;AAEhB;;AAEG;IAMH,QAAQ,GAAW,EAAE;AAErB;;AAEG;AAIH,IAAA,MAAM;AAEN;;;;AAIG;IACH,OAAO,QAAQ,CAAC,KAA2C,EAAA;QACzD,OAAO,EAAE,IAAI,EAAE,CAAC,KAAK,CAAC,IAAI,GAAG,CAAC,IAAI,KAAK,CAAC,QAAQ,EAAE,IAAI,EAAE,KAAK,CAAC,QAAQ,EAAE;IAC1E;AAEA;;;;;AAKG;IACH,OAAO,WAAW,CAAC,MAAc,EAAA;AAC/B,QAAA,OAAO,IAAI,MAAM,CAAC,OAAO,CAAC,SAAS,EAAE,SAAS,IAAI,CAAA,EAAA,EAAK,SAAS,CAAA,CAAE,CAAC,GAAG;IACxE;AACD;AAtCC,UAAA,CAAA;AAJC,IAAA,UAAU,EAAE;AACZ,IAAA,IAAI,CAAC,MAAM,MAAM,CAAC;AAClB,IAAA,KAAK,EAAE;IACP,GAAG,CAAC,CAAC,CAAC;;AACU,CAAA,EAAA,SAAA,CAAA,SAAA,EAAA,MAAA,EAAA,MAAA,CAAA;AAUjB,UAAA,CAAA;AALC,IAAA,UAAU,EAAE;AACZ,IAAA,IAAI,CAAC,MAAM,MAAM,CAAC;AAClB,IAAA,KAAK,EAAE;IACP,GAAG,CAAC,CAAC,CAAC;IACN,GAAG,CAAC,GAAG,CAAC;;AACa,CAAA,EAAA,SAAA,CAAA,SAAA,EAAA,UAAA,EAAA,MAAA,CAAA;AAQtB,UAAA,CAAA;AAHC,IAAA,UAAU,EAAE;AACZ,IAAA,QAAQ,EAAE;IACV,SAAS,CAAC,GAAG,CAAC;;AACC,CAAA,EAAA,SAAA,CAAA,SAAA,EAAA,QAAA,EAAA,MAAA,CAAA;;;;"}
@@ -0,0 +1,48 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * #### Page
5
+ *
6
+ * Response of a paged list endpoint: the items of one page, the total count of matching items,
7
+ * and the page and page size of the request. Create it with {@link Page.of}.
8
+ *
9
+ * * * *
10
+ * Example:
11
+ * ```typescript
12
+ * const [items, total] = await this.users.findAndCount(PageQuery.skipTake(query));
13
+ *
14
+ * return Page.of(items, total, query); // { items, total, page: 2, pageSize: 25 }
15
+ * ```
16
+ * * * *
17
+ */
18
+ class Page {
19
+ items;
20
+ total;
21
+ page;
22
+ pageSize;
23
+ /**
24
+ * @param items The items of this page
25
+ * @param total The count of all matching items, on every page
26
+ * @param page The page, from 1
27
+ * @param pageSize The items per page
28
+ */
29
+ constructor(items, total, page, pageSize) {
30
+ this.items = items;
31
+ this.total = total;
32
+ this.page = page;
33
+ this.pageSize = pageSize;
34
+ }
35
+ /**
36
+ * The page of `items` for a query
37
+ *
38
+ * @param items The items of this page
39
+ * @param total The count of all matching items, on every page
40
+ * @param query The query the page answers
41
+ */
42
+ static of(items, total, query) {
43
+ return new Page(items, total, query.page, query.pageSize);
44
+ }
45
+ }
46
+
47
+ exports.Page = Page;
48
+ //# sourceMappingURL=page.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"page.cjs","sources":["../../../../libs/nest-pack/src/pagination/page.ts"],"sourcesContent":[null],"names":[],"mappings":";;AAEA;;;;;;;;;;;;;;AAcG;MACU,IAAI,CAAA;AAQJ,IAAA,KAAA;AACA,IAAA,KAAA;AACA,IAAA,IAAA;AACA,IAAA,QAAA;AAVX;;;;;AAKG;AACH,IAAA,WAAA,CACW,KAAU,EACV,KAAa,EACb,IAAY,EACZ,QAAgB,EAAA;QAHhB,IAAA,CAAA,KAAK,GAAL,KAAK;QACL,IAAA,CAAA,KAAK,GAAL,KAAK;QACL,IAAA,CAAA,IAAI,GAAJ,IAAI;QACJ,IAAA,CAAA,QAAQ,GAAR,QAAQ;IAChB;AAEH;;;;;;AAMG;AACH,IAAA,OAAO,EAAE,CAAI,KAAU,EAAE,KAAa,EAAE,KAA2C,EAAA;AACjF,QAAA,OAAO,IAAI,IAAI,CAAC,KAAK,EAAE,KAAK,EAAE,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,QAAQ,CAAC;IAC3D;AACD;;;;"}
@@ -0,0 +1,40 @@
1
+ import { PageQuery } from './page-query.cjs';
2
+
3
+ /**
4
+ * #### Page
5
+ *
6
+ * Response of a paged list endpoint: the items of one page, the total count of matching items,
7
+ * and the page and page size of the request. Create it with {@link Page.of}.
8
+ *
9
+ * * * *
10
+ * Example:
11
+ * ```typescript
12
+ * const [items, total] = await this.users.findAndCount(PageQuery.skipTake(query));
13
+ *
14
+ * return Page.of(items, total, query); // { items, total, page: 2, pageSize: 25 }
15
+ * ```
16
+ * * * *
17
+ */
18
+ declare class Page<T> {
19
+ readonly items: T[];
20
+ readonly total: number;
21
+ readonly page: number;
22
+ readonly pageSize: number;
23
+ /**
24
+ * @param items The items of this page
25
+ * @param total The count of all matching items, on every page
26
+ * @param page The page, from 1
27
+ * @param pageSize The items per page
28
+ */
29
+ constructor(items: T[], total: number, page: number, pageSize: number);
30
+ /**
31
+ * The page of `items` for a query
32
+ *
33
+ * @param items The items of this page
34
+ * @param total The count of all matching items, on every page
35
+ * @param query The query the page answers
36
+ */
37
+ static of<T>(items: T[], total: number, query: Pick<PageQuery, 'page' | 'pageSize'>): Page<T>;
38
+ }
39
+
40
+ export { Page };
@@ -0,0 +1,40 @@
1
+ import { PageQuery } from './page-query.js';
2
+
3
+ /**
4
+ * #### Page
5
+ *
6
+ * Response of a paged list endpoint: the items of one page, the total count of matching items,
7
+ * and the page and page size of the request. Create it with {@link Page.of}.
8
+ *
9
+ * * * *
10
+ * Example:
11
+ * ```typescript
12
+ * const [items, total] = await this.users.findAndCount(PageQuery.skipTake(query));
13
+ *
14
+ * return Page.of(items, total, query); // { items, total, page: 2, pageSize: 25 }
15
+ * ```
16
+ * * * *
17
+ */
18
+ declare class Page<T> {
19
+ readonly items: T[];
20
+ readonly total: number;
21
+ readonly page: number;
22
+ readonly pageSize: number;
23
+ /**
24
+ * @param items The items of this page
25
+ * @param total The count of all matching items, on every page
26
+ * @param page The page, from 1
27
+ * @param pageSize The items per page
28
+ */
29
+ constructor(items: T[], total: number, page: number, pageSize: number);
30
+ /**
31
+ * The page of `items` for a query
32
+ *
33
+ * @param items The items of this page
34
+ * @param total The count of all matching items, on every page
35
+ * @param query The query the page answers
36
+ */
37
+ static of<T>(items: T[], total: number, query: Pick<PageQuery, 'page' | 'pageSize'>): Page<T>;
38
+ }
39
+
40
+ export { Page };
@@ -0,0 +1,46 @@
1
+ /**
2
+ * #### Page
3
+ *
4
+ * Response of a paged list endpoint: the items of one page, the total count of matching items,
5
+ * and the page and page size of the request. Create it with {@link Page.of}.
6
+ *
7
+ * * * *
8
+ * Example:
9
+ * ```typescript
10
+ * const [items, total] = await this.users.findAndCount(PageQuery.skipTake(query));
11
+ *
12
+ * return Page.of(items, total, query); // { items, total, page: 2, pageSize: 25 }
13
+ * ```
14
+ * * * *
15
+ */
16
+ class Page {
17
+ items;
18
+ total;
19
+ page;
20
+ pageSize;
21
+ /**
22
+ * @param items The items of this page
23
+ * @param total The count of all matching items, on every page
24
+ * @param page The page, from 1
25
+ * @param pageSize The items per page
26
+ */
27
+ constructor(items, total, page, pageSize) {
28
+ this.items = items;
29
+ this.total = total;
30
+ this.page = page;
31
+ this.pageSize = pageSize;
32
+ }
33
+ /**
34
+ * The page of `items` for a query
35
+ *
36
+ * @param items The items of this page
37
+ * @param total The count of all matching items, on every page
38
+ * @param query The query the page answers
39
+ */
40
+ static of(items, total, query) {
41
+ return new Page(items, total, query.page, query.pageSize);
42
+ }
43
+ }
44
+
45
+ export { Page };
46
+ //# sourceMappingURL=page.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"page.js","sources":["../../../../libs/nest-pack/src/pagination/page.ts"],"sourcesContent":[null],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;AAcG;MACU,IAAI,CAAA;AAQJ,IAAA,KAAA;AACA,IAAA,KAAA;AACA,IAAA,IAAA;AACA,IAAA,QAAA;AAVX;;;;;AAKG;AACH,IAAA,WAAA,CACW,KAAU,EACV,KAAa,EACb,IAAY,EACZ,QAAgB,EAAA;QAHhB,IAAA,CAAA,KAAK,GAAL,KAAK;QACL,IAAA,CAAA,KAAK,GAAL,KAAK;QACL,IAAA,CAAA,IAAI,GAAJ,IAAI;QACJ,IAAA,CAAA,QAAQ,GAAR,QAAQ;IAChB;AAEH;;;;;;AAMG;AACH,IAAA,OAAO,EAAE,CAAI,KAAU,EAAE,KAAa,EAAE,KAA2C,EAAA;AACjF,QAAA,OAAO,IAAI,IAAI,CAAC,KAAK,EAAE,KAAK,EAAE,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,QAAQ,CAAC;IAC3D;AACD;;;;"}