mastercontroller 1.3.28 → 1.3.29
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/MasterRouter.js +1 -0
- package/README.md +23 -3
- package/package.json +1 -1
package/MasterRouter.js
CHANGED
|
@@ -816,6 +816,7 @@ class MasterRouter {
|
|
|
816
816
|
control.__currentRoute = currentRoute;
|
|
817
817
|
control.__response = requestObject.response;
|
|
818
818
|
control.__request = requestObject.request;
|
|
819
|
+
control.state = requestObject.state || {};
|
|
819
820
|
const _callEmit = new EventEmitter();
|
|
820
821
|
|
|
821
822
|
_callEmit.once(EVENT_NAMES.CONTROLLER, function(){
|
package/README.md
CHANGED
|
@@ -268,7 +268,7 @@ Middleware receives a context object:
|
|
|
268
268
|
formData: {}, // POST body data
|
|
269
269
|
periodId: '123' // Route parameters (e.g., /period/:periodId)
|
|
270
270
|
},
|
|
271
|
-
state: {}, // Custom state
|
|
271
|
+
state: {}, // Custom state shared between middleware and controllers (this.state)
|
|
272
272
|
master: master, // Framework instance
|
|
273
273
|
isStatic: false // Is this a static file request?
|
|
274
274
|
}
|
|
@@ -718,10 +718,30 @@ console.log(JSON.stringify(snapshot));
|
|
|
718
718
|
|
|
719
719
|
### Use Cases
|
|
720
720
|
|
|
721
|
-
**Share data between middleware and controllers
|
|
721
|
+
**Share data between middleware and controllers via `state`:**
|
|
722
|
+
```javascript
|
|
723
|
+
// In middleware — set state on ctx
|
|
724
|
+
master.pipeline.use(async (ctx, next) => {
|
|
725
|
+
const token = ctx.request.headers.authorization?.replace('Bearer ', '');
|
|
726
|
+
ctx.state.user = await validateToken(token);
|
|
727
|
+
ctx.state.requestStart = Date.now();
|
|
728
|
+
await next();
|
|
729
|
+
});
|
|
730
|
+
|
|
731
|
+
// In controller — access state via this.state
|
|
732
|
+
async index() {
|
|
733
|
+
const user = this.state.user; // Set by auth middleware
|
|
734
|
+
const start = this.state.requestStart;
|
|
735
|
+
return this.returnJson({ user, loadTime: Date.now() - start });
|
|
736
|
+
}
|
|
737
|
+
```
|
|
738
|
+
|
|
739
|
+
`this.state` in controllers is the same object reference as `ctx.state` in middleware — mutations in either direction are shared within the request lifecycle.
|
|
740
|
+
|
|
741
|
+
**Share data using temp (key-value store):**
|
|
722
742
|
```javascript
|
|
723
743
|
// In middleware
|
|
724
|
-
master.use(async (ctx, next) => {
|
|
744
|
+
master.pipeline.use(async (ctx, next) => {
|
|
725
745
|
ctx.temp.add('requestStart', Date.now());
|
|
726
746
|
await next();
|
|
727
747
|
const duration = Date.now() - ctx.temp.get('requestStart');
|
package/package.json
CHANGED