UNPKG

1.93 kBJavaScriptView Raw
1 /**
2 * LokiNativescriptAdapter
3 * @author Stefano Falda <stefano.falda@gmail.com>
4 *
5 * Lokijs adapter for nativescript framework (http://www.nativescript.org)
6 *
7 * The db file is created in the app documents folder.
8
9 * How to use:
10 * Just create a new loki db and your ready to go:
11 *
12 * let db = new loki('loki.json',{autosave:true});
13 *
14 */
15
16function LokiNativescriptAdapter() {
17 this.fs = require("file-system");
18 }
19
20LokiNativescriptAdapter.prototype.loadDatabase = function(dbname, callback){
21 var documents = this.fs.knownFolders.documents();
22 var myFile = documents.getFile(dbname);
23 //Read from filesystem
24 myFile.readText()
25 .then(function (content) {
26 //The file is empty or missing
27 if (content===""){
28 callback(new Error("DB file does not exist"));
29 } else {
30 callback(content);
31 }
32 }, function (error) {
33 console.log("Error opening db "+dbname+": "+ error);
34 callback(new Error(error));
35 });
36};
37
38LokiNativescriptAdapter.prototype.saveDatabase = function(dbname, serialized, callback){
39 var documents = this.fs.knownFolders.documents();
40 var myFile = documents.getFile(dbname);
41 myFile.writeText(serialized)
42 .then(function () {
43 callback();
44 }, function (error) {
45 console.log("Error saving db "+dbname+": "+ error);
46 });
47
48};
49
50LokiNativescriptAdapter.prototype.deleteDatabase = function deleteDatabase(dbname, callback) {
51 var documents = this.fs.knownFolders.documents();
52 var file = documents.getFile(dbname);
53 file.remove()
54 .then(function (result) {
55 callback();
56 }, function (error) {
57 callback(error);
58 });
59 };
60
61module.exports = LokiNativescriptAdapter;
\No newline at end of file