Coder Social home page Coder Social logo

rebridge's Introduction

Rebridge

npm Build Status

Rebridge is a transparent Javascript-Redis bridge. You can use it to create JavaScript objects that are automatically synchronized to a Redis database.

Install

npm install rebridge

Usage

Synchronous, non-blocking usage

const Rebridge = require("rebridge");
const redis = require("redis");

const client = redis.createClient();
const db = new Rebridge(client, {
    mode: "deasync"
});

db.users = [];
db.users.push({
    username: "johndoe",
    email: "[email protected]"
});
db.users.push({
    username: "foobar",
    email: "[email protected]"
});
db.users.push({
    username: "CapacitorSet",
    email: "[email protected]"
});
console.log("Users:", db.users._value); // Prints the list of users
const [me] = db.users.filter(user => user.username === "CapacitorSet");
console.log("Me:", me); // Prints [{username: "CapacitorSet", email: "..."}]
client.quit();

Asynchronous usage

const Rebridge = require("rebridge");
const redis = require("redis");

const client = redis.createClient();
const db = new Rebridge(client);

db.users.set([])
    .then(() => Promise.all([
        db.users.push({
            username: "johndoe",
            email: "[email protected]"
        }),
        db.users.push({
            username: "foobar",
            email: "[email protected]"
        }),
        db.users.push({
            username: "CapacitorSet",
            email: "[email protected]"
        })
    ]))
    .then(() => db.users._promise)
    .then(arr => console.log("Users:", arr)) // Prints the list of users
    .then(() => db.users.filter(user => user.username === "CapacitorSet"))
    .then(([me]) => console.log("Me:", me)) // Prints [{username: "CapacitorSet", email: "..."}]
    .then(() => client.quit())
    .catch(err => console.log("An error occurred:", err));

Requirements

Rebridge uses ES6 Proxy objects, so it requires at least Node 6.

Limitations

  • By default, Rebridge objects can't contain functions, circular references, and in general everything for which x === JSON.parse(JSON.stringify(x)) doesn't hold true. However, you can use a custom serialization function (see below).

  • Obviously, you cannot write directly to db (i.e. you can't do var db = Rebridge(); db = {"name": "foo"}).

Custom serialization

By default, Rebridge serializes to JSON, but you can pass a custom serialization function. For instance, if you wanted to serialize to YAML, you would do something like this:

const yaml = require("js-yaml");
const db = new Rebridge(client, {
    serialize: yaml.dump,
    deserialize: yaml.load
});

How it works

Rebridge() returns an ES6 Proxy object around {}. When you try to read one of its properties, the getter intercepts the call, retrieves and deserializes the result from the database, and returns that instead; the same happens when you write to it.

The Proxy will forward the native methods and properties transparently, so that the objects it returns should behave the same as native objects; if this is not the case, file an issue on GitHub.

First-level objects (eg. db.foo) correspond to keys in the Redis database; they are serialized using JSON. When requesting deeper objects (eg. db.foo.bar.baz), the first-level object (db.foo) is deserialized to a native object, which is then accessed in the standard way.

rebridge's People

Contributors

bassarisse avatar capacitorset avatar joshwyatt avatar nikolvs avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rebridge's Issues

An advice

Just an advice.
The initialization of the rebridge is not safe. Just like below example code :
................................................................................................................................................................................................
const Rebridge = require("rebridge");
const redis = require("redis");

const client = redis.createClient();
const db = new Rebridge(client, {
mode: "deasync"
});

db.users = [ ]; // This is what I want to say
............................................................................................................................................................
If I put "db.users = [ ]" in my codes, I will worry about it may clean up the datas in the db.users.
I think it should change to just like "InsertOrCreate", if the db.users exists, it will insert item into db.users; if the db.users does not exist, it will create the db.users, then insert item into the new db.users.
......................................................
Just an advice, Thank you.

Rebridge somehow steals context of "this"

I've been trying to port a project I'm working on over to Redis, however I've been having some issues with this library.
Somehow, it seems that Rebridge is stealing what this means, while in the context of my main class.
I've been getting TypeError: this.pickGame is not a function and I've checked and I don't have anything that could change the context of this, and when I try logging this to the console, I get AssertionError [ERR_ASSERTION]: 'symbol' deepEqual 'string' and the stack trace leads to Rebridge.

class KnifeBot extends Eris.Client {
    constructor(config, options={}) {
        ...
        this.redis = Redis.createClient(config.redisOptions);
        this.db = new Rebridge(this.redis, config.rebridgeOptions);
        ...
    }

    pickGame() {
        // returns a random string
    }

    setGame() {
        let game = this.pickGame() // This line errors
        ...
    }
}

Code above is cut down to get point across.

Unexpected Token index.js

This is a really neat idea! I can't wait to try it out.

I'm getting this error:

/node_modules/rebridge/index.js:11
function _Rebridge(client, base = {}, inTree = []) {
                                ^

SyntaxError: Unexpected token =
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:373:25)
    at Module._extensions..js (module.js:416:10)
    at Object.require.extensions.(anonymous function) [as .js] (/Users/Jon/Code/bike-pretty/node_modules/babel-cli/node_modules/babel-register/lib/node.js:152:7)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (/Users/Jon/Code/bike-pretty/shopify/Product.js:24:16)
    at Module._compile (module.js:409:26)

I thought this might have something to do with ES6, but that didn't work either. What am I doing wrong?

Splicing a second-level array throws an error

Example code:

const index = "2"

db.example.replacements = [{f:"f"}, {f:"f"}, {f:"f"}, {f:"f"}, {f:"f"}];

db.example.replacements.splice(Number(index), 1);

This fails with the following error:

/home/CapacitorSet/rebridge/node_modules/redis-parser/lib/parser.js:403
  while (this.offset < this.buffer.length) {
                                  ^

TypeError: Cannot read property 'length' of null
    at JavascriptRedisParser.execute (/home/CapacitorSet/rebridge/node_modules/redis-parser/lib/parser.js:403:35)
    at Socket.<anonymous> (/home/CapacitorSet/rebridge/node_modules/redis/index.js:267:27)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)
    at readableAddChunk (_stream_readable.js:176:18)
    at Socket.Readable.push (_stream_readable.js:134:10)
    at TCP.onread (net.js:548:20)
    at Function.module.exports.runLoopOnce (/home/CapacitorSet/rebridge/node_modules/deasync/index.js:66:11)
    at Object.set (/home/CapacitorSet/rebridge/index.js:95:27)
    at Object.<anonymous> (/home/CapacitorSet/rebridge/test.js:41:25)

Any help is welcome.

About the delete function?

I see the Usage Example of the rebridge.
But How to delete one member or all mebers of the JavaScript objects ?
Thank you..

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.