denwa-nest-shared 1.0.78 → 1.0.80

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/package.json CHANGED
@@ -1,7 +1,8 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "denwa-nest-shared",
4
- "version": "1.0.78",
4
+ "version": "1.0.80",
5
+ "skills": "skills",
5
6
  "types": "./dist/index.d.ts",
6
7
  "main": "./cjs/index.js",
7
8
  "module": "./dist/index.js",
@@ -11,6 +12,8 @@
11
12
  "files": [
12
13
  "cjs",
13
14
  "dist",
15
+ "skills",
16
+ "!skills/_artifacts",
14
17
  "CHANGELOG.md",
15
18
  "README.md"
16
19
  ],
@@ -24,7 +27,9 @@
24
27
  "release:minor": "npm run build && standard-version minor",
25
28
  "release:patch": "npm run build && standard-version patch"
26
29
  },
27
- "keywords": [],
30
+ "keywords": [
31
+ "tanstack-intent"
32
+ ],
28
33
  "license": "ISC",
29
34
  "description": "",
30
35
  "repository": {
@@ -57,7 +62,8 @@
57
62
  "ts-morph": "^25.0.1",
58
63
  "tsconfig-paths": "^4.2.0",
59
64
  "typescript": "^5.7.3",
60
- "typescript-eslint": "^8.24.0"
65
+ "typescript-eslint": "^8.24.0",
66
+ "@tanstack/intent": "latest"
61
67
  },
62
68
  "dependencies": {
63
69
  "@nestjs/common": "^11.0.9",
@@ -0,0 +1,155 @@
1
+ ---
2
+ name: auth-security
3
+ description: >
4
+ Implementing security and RBAC using Roles, Public, and identity decorators.
5
+ Handles GraphQL and REST contexts uniformly. Includes field-level role checking.
6
+ type: core
7
+ library: denwa-nest-shared
8
+ library_version: '1.0.80'
9
+ sources:
10
+ - 'Denwa799/nest-shared:src/decorators.ts'
11
+ - 'Denwa799/nest-shared:src/interceptors/fields-roles.interceptor.ts'
12
+ ---
13
+
14
+ # RBAC & Identity Decorators
15
+
16
+ Use this skill to protect routes and mutations, and to extract user information regardless of whether the request came from a GraphQL resolver or a standard REST controller.
17
+
18
+ ## Setup
19
+
20
+ Protect a resolver with roles and extract the current user ID.
21
+
22
+ ```typescript
23
+ import { Resolver, Mutation, Args } from '@nestjs/graphql';
24
+ import { Roles, GetCurrentUserId } from 'denwa-nest-shared';
25
+
26
+ @Resolver()
27
+ export class UserResolver {
28
+ @Roles('admin', 'manager')
29
+ @Mutation(() => Boolean)
30
+ async deleteUser(@Args('id') id: string, @GetCurrentUserId() userId: string) {
31
+ // userId is extracted correctly for both GQL and REST
32
+ return true;
33
+ }
34
+ }
35
+ ```
36
+
37
+ ## Core Patterns
38
+
39
+ ### Public Routes
40
+
41
+ Bypass global authentication guards for specific handlers.
42
+
43
+ ```typescript
44
+ import { Public } from 'denwa-nest-shared';
45
+
46
+ @Public()
47
+ @Get('health')
48
+ getHealth() {
49
+ return 'ok';
50
+ }
51
+ ```
52
+
53
+ ### Full User Object Extraction
54
+
55
+ Extract the complete user object from the request context.
56
+
57
+ ```typescript
58
+ import { GetCurrentUser } from 'denwa-nest-shared';
59
+
60
+ @Get('profile')
61
+ getProfile(@GetCurrentUser() user: any) {
62
+ return user;
63
+ }
64
+ ```
65
+
66
+ ### Field-Level Role Protection
67
+
68
+ Apply restrictions to specific GraphQL fields within a request.
69
+
70
+ ```typescript
71
+ import { Resolver, ResolveField, Parent } from '@nestjs/graphql';
72
+ import { CheckFieldsRoles, FieldsRolesInterceptor } from 'denwa-nest-shared';
73
+ import { UseInterceptors } from '@nestjs/common';
74
+
75
+ @Resolver(() => User)
76
+ @UseInterceptors(FieldsRolesInterceptor)
77
+ export class UserResolver {
78
+ @CheckFieldsRoles({ email: ['admin'] })
79
+ @ResolveField(() => String)
80
+ async email(@Parent() user: User) {
81
+ return user.email;
82
+ }
83
+ }
84
+ ```
85
+
86
+ ## Common Mistakes
87
+
88
+ ### HIGH Direct Access to req.user
89
+
90
+ Wrong:
91
+
92
+ ```typescript
93
+ @Mutation()
94
+ async update(@Context() ctx) {
95
+ const user = ctx.req.user; // Potential failure if context not normalized
96
+ }
97
+ ```
98
+
99
+ Correct:
100
+
101
+ ```typescript
102
+ @Mutation()
103
+ async update(@GetCurrentUser() user: User) {
104
+ // Safe extraction across GQL and REST
105
+ }
106
+ ```
107
+
108
+ Directly accessing the request object can fail in mixed environments. The identity decorators handle the underlying context normalization automatically.
109
+
110
+ Source: Denwa799/nest-shared:src/decorators.ts:121
111
+
112
+ ### MEDIUM Listing super-admin in Roles
113
+
114
+ Wrong:
115
+
116
+ ```typescript
117
+ @Roles('admin', 'super-admin')
118
+ @Mutation()
119
+ async delete() {}
120
+ ```
121
+
122
+ Correct:
123
+
124
+ ```typescript
125
+ @Roles('admin')
126
+ @Mutation()
127
+ async delete() {}
128
+ ```
129
+
130
+ The library's `FieldsRolesInterceptor` and standard role guards typically bypass all restrictions for `super-admin` or `super_admin`. You do not need to specify them explicitly in projects.
131
+
132
+ Source: maintainer interview
133
+
134
+ ### LOW Forgetting FieldsRolesInterceptor
135
+
136
+ Wrong:
137
+
138
+ ```typescript
139
+ @CheckFieldsRoles({ salary: ['admin'] })
140
+ @ResolveField()
141
+ async salary() {}
142
+ ```
143
+
144
+ Correct:
145
+
146
+ ```typescript
147
+ @UseInterceptors(FieldsRolesInterceptor)
148
+ @CheckFieldsRoles({ salary: ['admin'] })
149
+ @ResolveField()
150
+ async salary() {}
151
+ ```
152
+
153
+ The `@CheckFieldsRoles` decorator only stores metadata; it requires the `FieldsRolesInterceptor` to be active on the class or handler to actually enforce the restriction.
154
+
155
+ Source: Denwa799/nest-shared:src/interceptors/fields-roles.interceptor.ts
@@ -0,0 +1,163 @@
1
+ ---
2
+ name: data-access-typeorm
3
+ description: >
4
+ Generating complex TypeORM FindOptions using the createQueryData helper.
5
+ Standardizes filtering, ILike searching, range mapping (fromToFields), and pagination.
6
+ type: core
7
+ library: denwa-nest-shared
8
+ library_version: '1.0.80'
9
+ sources:
10
+ - 'Denwa799/nest-shared:src/lib.ts'
11
+ ---
12
+
13
+ # TypeORM Query Generation
14
+
15
+ Use this skill to transform frontend filter and search parameters into standard TypeORM `FindOptions`. This is the preferred way to build all data-fetching logic in projects using this library.
16
+
17
+ ## Setup
18
+
19
+ Initialize a repository query using `createQueryData`.
20
+
21
+ ```typescript
22
+ import { createQueryData } from 'denwa-nest-shared';
23
+ import { Repository } from 'typeorm';
24
+
25
+ async function findUsers(repository: Repository<User>, args: GetUsersArgs) {
26
+ const queryData = createQueryData({
27
+ filter: args.filter, // Object with direct matches
28
+ search: args.search, // Object for ILike search
29
+ paginate: args.paginate, // { page, limit }
30
+ sort: args.sort, // { sortField, sortOrder }
31
+ });
32
+
33
+ return await repository.findAndCount(queryData);
34
+ }
35
+ ```
36
+
37
+ ## Core Patterns
38
+
39
+ ### Range Mapping (fromToFields)
40
+
41
+ Map specific "start" and "end" fields to a single column range (e.g. `priceStart` and `priceEnd` map to `price`).
42
+
43
+ ```typescript
44
+ const queryData = createQueryData({
45
+ filter: { minPrice: 100, maxPrice: 500 },
46
+ fromToFields: [
47
+ {
48
+ fromFieldName: 'minPrice',
49
+ toFieldName: 'maxPrice',
50
+ originalFieldName: 'price',
51
+ },
52
+ ],
53
+ });
54
+ // Result includes: where: { price: And(MoreThanOrEqual(100), LessThanOrEqual(500)) }
55
+ ```
56
+
57
+ ### Array Overlap Filtering
58
+
59
+ Search for entities where an array column contains any of the provided values.
60
+
61
+ ```typescript
62
+ const queryData = createQueryData({
63
+ filter: { categoryIds: [1, 2, 3] },
64
+ oneEntryArrayFields: ['categoryIds'],
65
+ });
66
+ // Uses ArrayOverlap for those fields
67
+ ```
68
+
69
+ ### Combined Search and Filter
70
+
71
+ `createQueryData` supports both strict filtering and fuzzy searching.
72
+
73
+ ```typescript
74
+ const queryData = createQueryData({
75
+ filter: { isActive: true },
76
+ search: { firstName: 'John', lastName: 'Doe' },
77
+ searchType: 'or', // Default: searches for firstName OR lastName matching the terms
78
+ });
79
+ ```
80
+
81
+ ## Common Mistakes
82
+
83
+ ### CRITICAL Manually Building QueryBuilders
84
+
85
+ Wrong:
86
+
87
+ ```typescript
88
+ const qb = repository.createQueryBuilder('user');
89
+ if (filter.name) {
90
+ qb.andWhere('user.name ILIKE :name', { name: `%${filter.name}%` });
91
+ }
92
+ ```
93
+
94
+ Correct:
95
+
96
+ ```typescript
97
+ const queryData = createQueryData({ search: { name: filter.name } });
98
+ const results = await repository.find(queryData);
99
+ ```
100
+
101
+ Falling back to raw QueryBuilders for standard filtering and searching avoids the library's optimized range, overlap, and pagination logic. Always use `createQueryData`.
102
+
103
+ Source: maintainer interview
104
+
105
+ ### HIGH Incorrect fromToFields Mapping
106
+
107
+ Wrong:
108
+
109
+ ```typescript
110
+ createQueryData({
111
+ filter: { ageFrom: 18, ageTo: 99 },
112
+ fromToFields: [
113
+ {
114
+ fromFieldName: 'ageFrom',
115
+ toFieldName: 'ageTo',
116
+ originalFieldName: 'id', // Mismatched field name
117
+ },
118
+ ],
119
+ });
120
+ ```
121
+
122
+ Correct:
123
+
124
+ ```typescript
125
+ createQueryData({
126
+ filter: { ageFrom: 18, ageTo: 99 },
127
+ fromToFields: [
128
+ {
129
+ fromFieldName: 'ageFrom',
130
+ toFieldName: 'ageTo',
131
+ originalFieldName: 'age',
132
+ },
133
+ ],
134
+ });
135
+ ```
136
+
137
+ The `originalFieldName` must exactly match the property name on your Entity.
138
+
139
+ Source: Denwa799/nest-shared:src/lib.ts:454
140
+
141
+ ### MEDIUM Ignoring searchType Default
142
+
143
+ Wrong:
144
+
145
+ ```typescript
146
+ // Assuming this will search for users who match BOTH critera
147
+ const queryData = createQueryData({
148
+ search: { firstName: 'John', email: 'test@' },
149
+ });
150
+ ```
151
+
152
+ Correct:
153
+
154
+ ```typescript
155
+ const queryData = createQueryData({
156
+ search: { firstName: 'John', email: 'test@' },
157
+ searchType: 'and',
158
+ });
159
+ ```
160
+
161
+ By default, `searchType` is `'or'`. If you need strict matching across multiple search fields, you must explicitly set it to `'and'`.
162
+
163
+ Source: Denwa799/nest-shared:src/lib.ts:479
@@ -0,0 +1,113 @@
1
+ ---
2
+ name: file-management
3
+ description: >
4
+ Managing file and image metadata stored as JSON strings in the database.
5
+ Standardizes the lifecycle of temporary uploads, entity sync, and S3 metadata formatting.
6
+ type: core
7
+ library: denwa-nest-shared
8
+ library_version: '1.0.80'
9
+ sources:
10
+ - 'Denwa799/nest-shared:src/lib.ts'
11
+ - 'Denwa799/nest-shared:src/dto.ts'
12
+ ---
13
+
14
+ # File & Image JSON Storage
15
+
16
+ Use this skill to manage file metadata that is stored as stringified JSON in your database. This is used to track S3 locations, alt tags, and file states.
17
+
18
+ ## Setup
19
+
20
+ Synchronize temporary uploads with an entity.
21
+
22
+ ```typescript
23
+ import { prepareTempImages, updateEntityImages } from 'denwa-nest-shared';
24
+
25
+ async function updateProductGallery(product, newImagesDto: TempImagesDto) {
26
+ // 1. Prepare metadata for images that were uploaded to temporary storage
27
+ const prepared = prepareTempImages(newImagesDto.tempImages, 'products-gallery');
28
+
29
+ // 2. Reconcile with existing entity images (adds new, keeps existing, removes deleted)
30
+ product.images = updateEntityImages(product.images, prepared);
31
+
32
+ await repository.save(product);
33
+ }
34
+ ```
35
+
36
+ ## Core Patterns
37
+
38
+ ### Manual Image Formatting
39
+
40
+ Format a raw S3 result or external URL into the library-standard image JSON structure.
41
+
42
+ ```typescript
43
+ import { prepareImages } from 'denwa-nest-shared';
44
+
45
+ const images = prepareImages(
46
+ [
47
+ {
48
+ name: 'photo.jpg',
49
+ url: 'https://s3.aws.com/bucket/photo.jpg',
50
+ },
51
+ ],
52
+ 'avatar',
53
+ );
54
+ ```
55
+
56
+ ### File Meta Retrieval
57
+
58
+ The library assumes that your database columns store these as strings. Ensure you handle the serialized state correctly in your repositories.
59
+
60
+ ```typescript
61
+ // Typical DTO for accepting image updates
62
+ import { AllImagesDto } from 'denwa-nest-shared';
63
+
64
+ export class UpdateProfileDto {
65
+ @ApiValidationProperty({ type: 'string', optional: true })
66
+ avatar?: string; // Standardized image JSON string
67
+ }
68
+ ```
69
+
70
+ ## Common Mistakes
71
+
72
+ ### HIGH Storing Objects instead of Strings
73
+
74
+ Wrong:
75
+
76
+ ```typescript
77
+ product.images = [{ url: '...', name: '...' }]; // DB driver might fail or save as object
78
+ ```
79
+
80
+ Correct:
81
+
82
+ ```typescript
83
+ product.images = JSON.stringify([{ url: '...', name: '...' }]);
84
+ ```
85
+
86
+ The library's internal helpers and TypeORM configuration for these columns often expect a stringified JSON. While some drivers handle object auto-serialization, manually ensuring string format prevents hydration issues.
87
+
88
+ Source: Denwa799/nest-shared:src/lib.ts:741
89
+
90
+ ### MEDIUM Mismatched Folder Keys
91
+
92
+ Wrong:
93
+
94
+ ```typescript
95
+ const prepared = prepareTempImages(temp, 'products');
96
+ product.images = updateEntityImages(product.images, prepared); // Folder key mismatch logic
97
+ ```
98
+
99
+ Correct:
100
+
101
+ ```typescript
102
+ const folder = 'gallery';
103
+ const prepared = prepareTempImages(temp, folder);
104
+ product.images = updateEntityImages(product.images, prepared);
105
+ ```
106
+
107
+ While the `folder` key is primarily for S3 organization, inconsistent use during update cycles can lead to metadata being assigned to the wrong entity scope.
108
+
109
+ Source: Denwa799/nest-shared:src/lib.ts:762
110
+
111
+ ## References
112
+
113
+ - [Image DTO Reference](Denwa799/nest-shared:src/dto.ts#L250)
@@ -0,0 +1,173 @@
1
+ ---
2
+ name: schema-definition
3
+ description: >
4
+ Defining properties in DTOs and Entities using ApiValidationProperty to unify GraphQL, Swagger, and class-validation.
5
+ Includes Paginate, DeleteDto, IdsDto, and OkRequestDto for standardizing request/response shapes.
6
+ type: core
7
+ library: denwa-nest-shared
8
+ library_version: '1.0.80'
9
+ sources:
10
+ - 'Denwa799/nest-shared:src/decorators.ts'
11
+ - 'Denwa799/nest-shared:src/dto.ts'
12
+ ---
13
+
14
+ # Unified Schema Definition
15
+
16
+ Use this skill to define data structures that are automatically compatible with NestJS GraphQL (Apollo), Swagger (OpenAPI), and class-validator using a single decorator.
17
+
18
+ ## Setup
19
+
20
+ Define a standard DTO or Entity using `ApiValidationProperty`.
21
+
22
+ ```typescript
23
+ import { InputType } from '@nestjs/graphql';
24
+ import { ApiValidationProperty } from 'denwa-nest-shared';
25
+
26
+ @InputType()
27
+ export class CreateUserDto {
28
+ @ApiValidationProperty({
29
+ type: 'string',
30
+ description: 'User display name',
31
+ example: 'John Doe',
32
+ minLength: 2,
33
+ })
34
+ name: string;
35
+
36
+ @ApiValidationProperty({
37
+ type: 'string',
38
+ isEmail: true,
39
+ description: 'Login email',
40
+ })
41
+ email: string;
42
+
43
+ @ApiValidationProperty({
44
+ type: 'boolean',
45
+ default: true,
46
+ optional: true,
47
+ })
48
+ isActive?: boolean;
49
+ }
50
+ ```
51
+
52
+ ## Core Patterns
53
+
54
+ ### Defining Enum Properties
55
+
56
+ Map TypeScript enums to GraphQL and Swagger simultaneously.
57
+
58
+ ```typescript
59
+ import { ApiValidationProperty } from 'denwa-nest-shared';
60
+
61
+ enum UserRole {
62
+ ADMIN = 'admin',
63
+ USER = 'user',
64
+ }
65
+
66
+ export class UserDto {
67
+ @ApiValidationProperty({
68
+ type: 'string',
69
+ enumObject: UserRole,
70
+ swaggerType: 'UserRole',
71
+ })
72
+ role: UserRole;
73
+ }
74
+ ```
75
+
76
+ ### Pagination Request Shapes
77
+
78
+ Use the built-in `Paginate` class to standardize list query parameters.
79
+
80
+ ```typescript
81
+ import { ArgsType } from '@nestjs/graphql';
82
+ import { Paginate, ApiValidationProperty } from 'denwa-nest-shared';
83
+
84
+ @ArgsType()
85
+ export class GetUsersArgs extends Paginate {
86
+ @ApiValidationProperty({ type: 'string', optional: true })
87
+ search?: string;
88
+ }
89
+ ```
90
+
91
+ ### Numeric and Date Types
92
+
93
+ Leverage internal type mapping for correct decorator generation.
94
+
95
+ ```typescript
96
+ import { ApiValidationProperty } from 'denwa-nest-shared';
97
+
98
+ export class StatsDto {
99
+ @ApiValidationProperty({ type: 'int', min: 0 })
100
+ count: number;
101
+
102
+ @ApiValidationProperty({ type: 'float', max: 100 })
103
+ score: number;
104
+
105
+ @ApiValidationProperty({ type: 'date', optional: true })
106
+ lastLogin?: Date;
107
+ }
108
+ ```
109
+
110
+ ## Common Mistakes
111
+
112
+ ### CRITICAL Using Separate Decorators
113
+
114
+ Wrong:
115
+
116
+ ```typescript
117
+ @Field()
118
+ @ApiProperty()
119
+ @IsString()
120
+ @MinLength(2)
121
+ name: string;
122
+ ```
123
+
124
+ Correct:
125
+
126
+ ```typescript
127
+ @ApiValidationProperty({ type: 'string', minLength: 2 })
128
+ name: string;
129
+ ```
130
+
131
+ Using separate decorators misses the unified type mapping and default formatting provided by the library.
132
+
133
+ Source: maintainer interview
134
+
135
+ ### HIGH Mismatched Validation for Type
136
+
137
+ Wrong:
138
+
139
+ ```typescript
140
+ @ApiValidationProperty({ type: 'boolean', min: 10 })
141
+ isActive: boolean;
142
+ ```
143
+
144
+ Correct:
145
+
146
+ ```typescript
147
+ @ApiValidationProperty({ type: 'int', min: 10 })
148
+ count: number;
149
+ ```
150
+
151
+ Validation parameters like `min`/`max` only apply to numeric types. Boolean types do not support these constraints.
152
+
153
+ Source: Denwa799/nest-shared:src/decorators.ts:160
154
+
155
+ ### MEDIUM Misusing Optional with Default
156
+
157
+ Wrong:
158
+
159
+ ```typescript
160
+ @ApiValidationProperty({ type: 'string', optional: false, default: 'Guest' })
161
+ name: string;
162
+ ```
163
+
164
+ Correct:
165
+
166
+ ```typescript
167
+ @ApiValidationProperty({ type: 'string', optional: true, default: 'Guest' })
168
+ name: string;
169
+ ```
170
+
171
+ If a property has a `default` value, it should typically be marked as `optional: true` so it registers correctly in the documentation as a non-required field for the consumer.
172
+
173
+ Source: Denwa799/nest-shared:src/decorators.ts:182