@itrocks/lazy-loading 0.0.16 → 0.0.17

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.
Files changed (2) hide show
  1. package/README.md +242 -0
  2. package/package.json +4 -2
package/README.md CHANGED
@@ -7,3 +7,245 @@
7
7
  # lazy-loading
8
8
 
9
9
  Integrates lazy loading for objects and collections in TypeScript classes.
10
+
11
+ *This documentation was written by an artificial intelligence and may contain errors or approximations.
12
+ It has not yet been fully reviewed by a human. If anything seems unclear or incomplete,
13
+ please feel free to contact the author of this package.*
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ npm i @itrocks/lazy-loading
19
+ ```
20
+
21
+ You will typically use this package together with `@itrocks/store` and
22
+ `@itrocks/storage`, which provide the actual persistence layer.
23
+
24
+ ## Usage
25
+
26
+ `@itrocks/lazy-loading` hooks into Node's module loader to automatically
27
+ wrap your entity classes and add lazy properties to them.
28
+
29
+ At application startup, call `initLazyLoading()` **before importing the
30
+ modules that declare your entity classes**. Any exported entity class with
31
+ `@itrocks/store` metadata will then be replaced by a lazily-loading
32
+ variant.
33
+
34
+ ### Minimal example
35
+
36
+ ```ts
37
+ // main.ts (entrypoint)
38
+ import { initLazyLoading } from '@itrocks/lazy-loading'
39
+
40
+ // Enable lazy loading for subsequently required modules
41
+ initLazyLoading()
42
+
43
+ // After this point, imports may be wrapped with lazy-loading behaviour
44
+ import { User } from './user.js'
45
+
46
+ async function run() {
47
+ // Assuming the store and data source are configured elsewhere
48
+ const user = new User()
49
+
50
+ // When first accessed, `user.profile` will be loaded from the data source
51
+ const profile = await user.profile
52
+ }
53
+
54
+ run().catch(console.error)
55
+ ```
56
+
57
+ ```ts
58
+ // user.ts
59
+ import { AnyType, Type } from '@itrocks/class-type'
60
+ import { store } from '@itrocks/store'
61
+
62
+ @store({ /* store options */ })
63
+ export class User {
64
+ id = 0
65
+
66
+ // A lazily-loaded single object
67
+ profile?: Profile
68
+ profileId?: number
69
+
70
+ // A lazily-loaded collection
71
+ roles: Role[] = []
72
+ roleIds?: number[]
73
+ }
74
+
75
+ export class Profile {
76
+ id = 0
77
+ name = ''
78
+ }
79
+
80
+ export class Role {
81
+ id = 0
82
+ name = ''
83
+ }
84
+ ```
85
+
86
+ In this example, the `User` class is annotated with a store decorator
87
+ from `@itrocks/store`. Once `initLazyLoading()` has been called, the
88
+ exported `User` class is replaced with a subclass whose `profile` and
89
+ `roles` properties are:
90
+
91
+ - defined as asynchronous getters that
92
+ - read `profileId` / `roleIds` when present and load the referenced
93
+ objects from the configured data source, or
94
+ - fall back to reading the related objects/collections directly from
95
+ the store;
96
+ - writable: once you explicitly assign `user.profile` or `user.roles`,
97
+ the value is stored on the instance and will no longer trigger a
98
+ reload on access.
99
+
100
+ The convention is that each lazily-loaded property may have a matching
101
+ identifier field:
102
+
103
+ - `property` ↔ `propertyId`
104
+ - `property` (collection) ↔ `propertyIds`
105
+
106
+ ### Example with manual class initialization
107
+
108
+ If you do not want to use the global module loader hook, you can call
109
+ `initClass()` manually on your entity classes.
110
+
111
+ ```ts
112
+ import { initClass } from '@itrocks/lazy-loading'
113
+
114
+ class Order {
115
+ id = 0
116
+
117
+ customer?: Customer
118
+ customerId?: number
119
+ }
120
+
121
+ class Customer {
122
+ id = 0
123
+ name = ''
124
+ }
125
+
126
+ // Create a lazily-loading variant of Order, if applicable
127
+ const LazyOrder = initClass(Order) ?? Order
128
+
129
+ async function process(orderId: number) {
130
+ const order = new LazyOrder()
131
+ order.id = orderId
132
+
133
+ // First access will load `customer` based on `customerId`
134
+ const customer = await order.customer
135
+ }
136
+ ```
137
+
138
+ Here, `initClass(Order)` inspects the `Order` metadata and, when it
139
+ finds lazily-loadable properties, returns a subclass that contains the
140
+ lazy getters. If the class cannot be configured for lazy loading (for
141
+ instance, because it is not associated with a store), `initClass()`
142
+ returns `undefined` and you can fall back to using the original class.
143
+
144
+ ## API
145
+
146
+ ### `const PROTECT_GET: unique symbol`
147
+
148
+ Symbol used as a metadata key on lazily-loaded properties.
149
+
150
+ This symbol is exposed for advanced integrations with custom
151
+ persistence/ORM layers. Typical usages include:
152
+
153
+ - detecting whether a property is currently under lazy-loading
154
+ protection (its value is managed by the lazy getter), and
155
+ - deciding whether a persistence layer should re-fetch or reuse the
156
+ in-memory value when saving.
157
+
158
+ Most applications do not need to access `PROTECT_GET` directly. The
159
+ `@itrocks/framework` integration uses it behind the scenes when
160
+ implementing database transformers.
161
+
162
+ ---
163
+
164
+ ### `type PropertyDescriptorWithProtectGet`
165
+
166
+ ```ts
167
+ type PropertyDescriptorWithProtectGet = PropertyDescriptor & ThisType<any> & {
168
+ [PROTECT_GET]?: true
169
+ }
170
+ ```
171
+
172
+ Helper type describing property descriptors that may carry the
173
+ `PROTECT_GET` marker. This is primarily useful when extending or
174
+ customizing the lazy-loading behaviour at a low level, for example when
175
+ defining additional decorators or property interceptors.
176
+
177
+ ---
178
+
179
+ ### `function initClass<T extends object>(classType: Type<T>): Type<T> | undefined`
180
+
181
+ Analyses the given class and returns a lazily-loading subclass when at
182
+ least one property can be configured for lazy loading.
183
+
184
+ The returned subclass extends `classType` and overrides qualifying
185
+ properties with asynchronous getters/setters that:
186
+
187
+ - lazily load a single related object based on `propertyId`,
188
+ - lazily load a collection based on `propertyIds`, or
189
+ - lazily fetch related data from the configured store when no id field
190
+ exists.
191
+
192
+ #### Parameters
193
+
194
+ - `classType` – the entity class to inspect and wrap with lazy-loading
195
+ behaviour.
196
+
197
+ #### Return value
198
+
199
+ - `Type<T> | undefined` – a subclass of `classType` that implements
200
+ lazy loading, or `undefined` if the class cannot be configured (for
201
+ example, because no store is registered for it).
202
+
203
+ #### Example
204
+
205
+ ```ts
206
+ import type { Type } from '@itrocks/class-type'
207
+ import { initClass } from '@itrocks/lazy-loading'
208
+
209
+ function withLazyLoading<T extends object>(classType: Type<T>): Type<T> {
210
+ return initClass(classType) ?? classType
211
+ }
212
+
213
+ // Later, when registering entities
214
+ const LazyUser = withLazyLoading(User)
215
+ ```
216
+
217
+ ---
218
+
219
+ ### `function initLazyLoading(): void`
220
+
221
+ Installs a global hook on Node's module loader so that exported entity
222
+ classes are transparently replaced by lazily-loading subclasses.
223
+
224
+ Once `initLazyLoading()` has been called, every subsequent `require()`
225
+ or `import` is inspected. For each exported value that looks like an
226
+ entity class (based on `@itrocks/store` metadata):
227
+
228
+ - its properties are analysed via reflection,
229
+ - eligible properties are replaced with lazy getters/setters, and
230
+ - the module export is updated to reference the new subclass.
231
+
232
+ The hook also handles *deferred types*, so that circular or late-bound
233
+ dependencies between entities can still benefit from lazy loading.
234
+
235
+ Call this function only once, early in your application's startup
236
+ sequence, before loading the bulk of your entity modules.
237
+
238
+ ## Typical use cases
239
+
240
+ - Add transparent lazy loading to entity relationships (one-to-one or
241
+ one-to-many) without changing your domain model code.
242
+ - Defer loading of large collections until they are actually accessed,
243
+ reducing memory usage and database round-trips.
244
+ - Work with simple `Id`/`Ids` fields while exposing rich object graphs
245
+ to the rest of the application.
246
+ - Integrate with `@itrocks/framework`, which automatically enables lazy
247
+ loading and uses `PROTECT_GET` when reading from and writing to the
248
+ database.
249
+ - Implement advanced persistence strategies by inspecting
250
+ `PROTECT_GET` metadata when deciding how and when to persist entity
251
+ properties.
package/package.json CHANGED
@@ -33,6 +33,7 @@
33
33
  "keywords": [
34
34
  "backend",
35
35
  "collection",
36
+ "entity",
36
37
  "it.rocks",
37
38
  "lazy",
38
39
  "lazy-loading",
@@ -40,7 +41,8 @@
40
41
  "object",
41
42
  "orm",
42
43
  "reflect",
43
- "reflection"
44
+ "reflection",
45
+ "relationship"
44
46
  ],
45
47
  "license": "ISC",
46
48
  "name": "@itrocks/lazy-loading",
@@ -54,5 +56,5 @@
54
56
  "build:esm": "tsc -p tsconfig.esm.json && node esm/esm"
55
57
  },
56
58
  "types": "./esm/lazy-loading.d.ts",
57
- "version": "0.0.16"
59
+ "version": "0.0.17"
58
60
  }