Use a Database Without Database

Sometime when you develop a new application you don’t really need to use any backend, you can do so many things now with javascript and all html5 api but one thing you cannot do is to persist your data to be accessible everywhere (yes I just talk about database…).

When you have just few data to save in a global database it’s really boring to have to create a full backend with routing, database access, api… just in order to save few data. Recently I had to work in this kind of project were data are not so important and everything is done locally and even data is stored locally but some have to be synchronized for everyone. Usually I create a simple node server with a database access but this is too much work.

After some research I found MongoHQ, ok this is not new, I already used it many times when I used some mongo database on heroku for example but in fact this is a bit more because you can create your own database and access directly with a REST API and this is good !

Here is a piece of code to do almost everything you need

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
var db = {
  _apikey: 'YOUR_API_KEY',
  _database: 'YOUR_DATABASE',
  _id: function(document) {
    return document._id.$oid;
  },
  url: function(collection, id) {
    if(!id) { id = ''; }
    return ['https://api.mongohq.com/databases/',
      this._database,
      '/collections/',
      collection,
      '/documents/',
      id,
      '?_apikey=',
      this._apikey].join('');
  },
  get: function(collection, id) {
    return $http.get(this.url(collection, id));
  },
  list: function(collection) {
    return $http.get(this.url(collection));
  },
  create: function(collection, document) {
    return $http.post(this.url(collection), {
      document: document
    });
  },
  update: function(collection, document) {
    var data = angular.extend({}, document);
    delete data.$$hashKey; // hack because of angular model
    delete data._id;
    return $http.put(this.url(collection, this._id(document)), {
      document: data
    });
  },
  delete: function(collection, document) {
    return $http.delete(this.url(collection, this._id(document)));
  }
};

Ok with this now you can have your database without any backend to create. Now if you want to fetch all your users for exemple you just have to execute

1
2
3
4
db.list("users").then(function(response) {
  var users = response.data;
  console.log(users);
});

Thats all and for some who didn’t undertand the $http, it’s like the $.ajax in jquery. I just realize now I should change this and use a Service with angular to manage the database access… Maybe another article

Comments

Copyright © 2014 - Anthony Estebe -