4

I'm trying to setup a Zone in my NodeJs api using Express. I've got the following require...

const Zone = require('zone.js/dist/zone-node.js');

and the following middleware function...

function setupAuthZone(req, res, next) {
    return Zone.current.fork({
        name: 'api',
        properties: {
            id: Math.random()
        }
    }).run(() => {
        next();
    })
}

which I use via

app.use(setupAuthZone);

When I call any endpoint in my api, I get "Cannot read property 'fork' of undefined". The Zone object has nothing hanging off of it, certainly not a current property.

Can anyone point me to a working, very simple example of using ZoneJs in a NodeJs api? I would like to create a Zone per request, and set some variables in that Zone and pull them out in some of my controller actions, like the currently authenticated user. I'd like to use it like a request context.

Update

I've altered the require to be

require('zone.js/dist/zone-node.js');

and now I have a Zone.current. I don't fully understand properties though. If I set Zone.current.currentUser in my passport middleware, I can pull it back out elsewhere, but I can't get to the "properties" property listed above. I don't see it on Zone.current. Also, if I change the setupAuthZone function to

function setupAuthZone(req, res, next) {
    return Zone.current.fork({
        name: 'api'
    })
    .run(() => {
        Zone.current.id = Math.random();
        next();
    })
}

I can't see the id property later when I look at Zone.current.id. It's simply not there. I can see some properties I set and I can't see others.

Tim Hardy
  • 1,654
  • 1
  • 17
  • 36

0 Answers0