Getting Started

  1. Configure Bicycle Server

    This defines two collections, "/people/:person" and "/people/:person/comments/:comment". This naturally defines a simple rest API and will make it easy to query for all of a given person's comments.

    Note that if two collections are ambiguous, an error will be thrown. To fix this, make sure that the paths are different for each collection.

    /bicycle.js
    var BicycleServer = require('bicycle-server');
    
    // passing a directory path automatically uses LevelUp
    var server = new BicycleServer(__dirname + '/data', {
      '/people/:person': {
        read: (user, params) => true,
        write: (user, params, update) => user && params.person === user.id
      },
      '/people/:person/comments/:id': {
        read: (user, params) => true,
        write: (user, params, update) => user && params.person === user.id
      }
    }, {
      auth: function (user, token) {
        if (user === 'ForbesLindesay' && token === 'secret') {
          return { id: '4C6CC5B6' };
        }
      },
      // basic built in static server
      serve: {
        '/': __dirname + '/index.html',
        // browserify is automatically used to serve js
        '/index.js': __dirname + '/index.js'
      }
    });
    
    server.listen(3000);
  2. Connect Client

    It only takes one line of code to connect the client to the server database.

    /index.html
    <dl>
      <dt>Name</dt>
      <dd id="name"></dd>
    <ul id="comments"></ul>
    <script src="/index.js"></script>
    /index.js
    var Bicycle = require('bicycle');
    var db = new Bicycle('/');
  3. Authenticate

    Everything after this call will hapen in the context of the newly authenticated user.

    /index.js
    db.auth('ForbesLindesay', 'secret');
  4. Write some data

    The data consits of named collections of JSON objects.

    :user.id gets replaced with the id of the logged in user and :uid gets replaced with a generated unique id.

    /index.js
    db.set('/people/:user.id', {name: 'Forbes Lindesay'})
    db.set('/comments/:user.id/:uid', {
      message: 'BicycleJS is epic'
    });
  5. Get data in real time

    BicycleJS gives you real time events when data changes.

    /index.js
    db.get('/people/:user.id').on('value', function (person) {
      document.getElementById('name').textContent = person.name;
    });
    db.list('/comments/:user.id').on('value', function (comments) {
      document.getElementById('comments').innerHTML = omments.map(function (c) {
        return '<li>' + c.message + '</ul>';
      }).join('');
    });