1

Module code:

const fs = require('fs');

class database {
    constructor(database, object) {
        typeof database === "object" && (object = database);
        this.file = (typeof database === "string" ? database : 'db') + '.json';
        object && fs.writeFileSync(this.file, JSON.stringify(object));
        this.db = fs.existsSync(this.file) ? JSON.parse(fs.readFileSync(this.file, 'utf-8')) : {};
        return new Proxy(this.db, this)
    }

    set(target, key, value) {
        this.db[key] = value;
        fs.writeFileSync(this.file, JSON.stringify(this.db));
    }

}

module.exports = database;

Example Script:

var db = require('./index.js')
var test = new db();

test.a = []; // Proxy is called here
test.a.push('a'); // It's not called here, despite test.a being set.

I'm expecting the set handler to fire anytime the object is updated, but when pushing to an array inside the object, it doesn't happen. Why is it not firing?

I'm using node v8.1.4. Supposedly all proxy issues were fixed after v6.

1 Answer 1

3

Unfortunately, proxies can only observe changes made on the target object -- proxies cannot observe changes to other objects nested on the target.

test and test.a are two separate objects. So while Proxy will invoke set whenever a change is made to test, it will not invoke set whenever a change is made to test.a.

If you'd like to observe changes to an object and all nested children of that object, then you'll want to use a library purpose built for the job.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.