Codementor Events

Implement an In-browser Database for offline use

Published Mar 29, 2019
Implement an In-browser Database for offline use

If you are familiar with Laravel Eloquent, this is going to look familiar.

We are going to use a JS library very similar to Eloquent called collect.js. With this little beast in place, all you have to do is use it to transform your data into Eloquent collection in JavaScript, and use all Eloquent magic on the frontend:

// Fake db (aka fake news)
import collect from 'collect.js';
 
const collection = collect({
    users: [
        { id: 1, firstname: 'Jane', lastname: 'Doe', gender: 'F' },
        { id: 2, firstname: 'John', lastname: 'Doe', gender: 'M' },
        { id: 3, firstname: 'Penelope', lastname: 'Cruz', gender: 'F' },
        { id: 4, firstname: 'Eva', lastname: 'Longoria', gender: 'F' },
        { id: 5, firstname: 'Cristiano', lastname: 'Penaldo', gender: 'M' }
    ],
 
    cities: [
        { id: 1, name: 'Sydney', country: 'Australia', humans: 4873217, kangaroos: 9321893, snakes: 22432645},
        { id: 2, name: 'Douala', country: 'Cameroon', humans: 5221943, kangaroos: 0, snakes: 2981023},
        { id: 3, name: 'Villetaneuse', country: 'France', humans: 32987, kangaroos: 0, snakes: 876432}
    ],
 
    friends: [],
    todos: [], // duh
    andSoOn: []
})
 
// Persist in localStore...
localStorage.setItem('fake_db', JSON.stringify(collection))

And there, my friend, you have persisted your entire fake database to the localStorage. If and when you reload the page, or quit and reopen the browser, your data is not lost and you can query it offline like this

// Read and query fake_db
let fakeDB
const data = localStorage.getItem('fake_db')
if (data) {
    fakeDB = collect(JSON.parse(data))
}
 
const females = fakeDB.get('users').where('gender', 'F').all()
console.log(females) // (3) [{...}, {...}, {...}]
//The above array will contain users 1, 3 & 4

As you can see, it looks and behaves like helpers function from Laravel Collection. You could wrap this as a service or use with one of the cool kids like Redux or vuex .Keep in mind though, localStorage is limited in size (MB).

Discover and read more posts from Eddy Ella
get started
post commentsBe the first to share your opinion
Show more replies