Skip to content

Instantly share code, notes, and snippets.

@brunotdantas
Last active March 4, 2020 14:24
Show Gist options
  • Save brunotdantas/08b1cd3d5f4bf7000b89f826d13911a3 to your computer and use it in GitHub Desktop.
Save brunotdantas/08b1cd3d5f4bf7000b89f826d13911a3 to your computer and use it in GitHub Desktop.
To test https://github.com/typicode/lowdb #Json #database #local #storage #localstorage #localdb
'use strict'
/* steps to use this test file:
1- install package lowdb : npm install lowdb
2- create a file empty data.json
3- manipulate the variable option to test the scenarios you want
*/
/** https://www.npmjs.com/package/lowdb */
const low = require('lowdb');
const FileSync = require('lowdb/adapters/FileSync');
const adapter = new FileSync('data.json'); // path and name of your local DB
const db = low(adapter);
//----------------------------------
// I will use switch case to test scenarios below
var option = 3; // Change this variable to test the scenarios you want
//----------------------------------
console.log(' ********************************* ');
switch(option) {
// option = 0 : create a obj. or a "table" named cities
case 0:
console.log( '0 = ');
console.log(
db.defaults({ cities: [] })
.write()
);
console.log(result);
break;
// option = 1 : Insert a city in cities 'table'
// if exists update
case 1:
console.log( '1 = ');
// test a city that already exists
var objToInsert = {
id : 1583326203652,
cityName: 'São Paulo',
state: 'SP'
}
// test a new city
var newCity = {
"id": Date.now(),
"cityName": "Itu",
"state": "SP"
}
// query cities by ID
if (db.get('cities').find({id : objToInsert.id}).value()){
// when found update
console.log(
db
.get('cities')
.find({id:objToInsert.id})
.assign({
cityName: objToInsert.cityName,
state: objToInsert.state
})
.write()
);
}else{
// when NOT found insert
console.log(
db
.get('cities')
.push(newCity)
.write()
);
}
break;
// option = 2 : query a specific city
case 2:
//2.1 cities that belong to state 'SP' (filter is the same as 'like' sql command here)
if(
db
.get('cities')
.filter({state: 'SP'})
.value()
){
console.log( '2.1 = ');
console.log(
db
.get('cities')
.filter({state: 'SP'})
.value()
);
}
//2.2 retrieve the FIRST object with the State = SP
console.log( '2.2 = ');
console.log(db
.get('cities')
.find({state : 'SP'})
.value()
);
break;
// option = 3 : query all records from cities 'table'
case 3:
result = db
.get('cities')
.filter({})
.value()
console.log('3 = ');
console.log(result);
break;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment