Using JSData in Node.js

How-To Guides

Using JSData in Node.js

JSData works in Node.js and in the browser, opening up the possibility of universal models (model code is shared between the client and the server). Currently available server-side adapters: Google Cloud Datastore, RethinkDB, MongoDB, SQL and Redis adapters.

Check out our example application which shows how to use JSData with shared code between the browser and Node.js.

The server is quite a different environment than the browser with different performance and data handling considerations.

👍

Tip

On the server you should use a Container component instead of the SimpleStore or DataStore components.

Why use Container instead of SimpleStore or DataStore? If you're running multiple instances of your app then you probably don't want to be caching data in the in-memory data store, otherwise your instances would get out of sync and you might get out-of-date reads and writes depending on which instance you hit.

Example

Here's an example of setting JSData up on the server:

import express from 'express'; 
import { Container } from 'js-data';
import { RethinkDbAdapter } from 'js-data-rethinkdb';

const app = express();
const adapter new RethinkDbAdapter({
  rOpts: {
    host: config.DB_HOST,
    port: config.DB_PORT,
    db: config.DB_DATABASE,
    authKey: config.DB_AUTH_KEY,
    min: 10,
    max: 50
  }
});

// Use Container instead of DataStore on the server
const store = new Container();
store.registerAdapter('rethinkdb', adapter, { default: true });

store.defineMapper('user');

app.get('/users/:id', (req, res, next) => {
  store.find('user', req.params.id)
    .then((user) => res.status(200).send(user).end())
    .catch(next);
});

In-memory caching using DataStore

🚧

Caution

Using DataStore or SimpleStore on the server is not recommended, but it will work when all your data fits in memory and you're only running one instance of your app.

import express from 'express';
import { DataStore } from 'js-data';
import { RethinkDbAdapter } from 'js-data-rethinkdb';

const app = express();
const adapter = new RethinkDbAdapter();

// Using DataStore...
const store = new DataStore();
store.registerAdapter('rethinkdb', adapter, { default: true });

store.defineMapper('user');

app.get('/users/:id', (req, res, next) => {
  store.find('user', req.params.id)
    .then((user) => res.status(200).send(user).end())
    .catch(next);
});