fipamo/brain/tools/utilities/DBUtils.js

200 lines
5.1 KiB
JavaScript

"use strict";
import DataUtils,
{
REQUEST_TYPE_GET,
REQUEST_TYPE_PUT,
REQUEST_TYPE_POST,
REQUEST_TYPE_DELETE,
CONTENT_TYPE_JSON,
CONTENT_TYPE_FORM
}
from '../utilities/DataUtils';
import Dexie from 'dexie';
import * as DataEvent from '../events/DataEvent';
export var COUNT;
export var FINAL_KEY;
export default class DBUtils
{
//--------------------------
// constructor
//--------------------------
constructor()
{
this.dataUtils = new DataUtils();
this.db = new Dexie("fipamo_posts");
this.db.version(1).stores(
{
postList: 'id,post'
});
this.db.postList.toArray(array =>
{
COUNT = array.length;
FINAL_KEY = array[COUNT - 1].id;
})
}
//--------------------------
// methods
//--------------------------
modify(id, postData)
{
let self = this;
let freshID;
return new Promise(function(resolve, reject)
{
if (id == null)
{
self.db.postList.put(postData).then(fresh =>
{
freshID = fresh;
}).catch(e =>
{
let err = {
message: "PUT ERROR",
error: e
}
});
}
else
{
self.db.postList.update(Number(id),
{
post: postData
}).then(updated =>
{}).catch(e =>
{
consol.log("ERROR", e)
let err = {
message: "UPDATE ERROR",
error: e
}
});
}
self.db.postList.toArray(array =>
{
self.syncRemote(array, freshID).then(response =>
{
resolve(
{
response
})
}).catch(err =>
{
reject(
{
err
});
});
})
})
}
syncLocal(array)
{
let self = this;
return new Promise(function(resolve, reject)
{
self.db.postList.clear().then(result =>
{
self.db.postList.bulkAdd(array).then(key =>
{
self.db.postList.toArray(array =>
{
let event = DataEvent.LOCAL_DB_READY
resolve(
{
event
})
})
}).catch(Dexie.BulkError, e =>
{
reject(
{
e
})
})
})
})
}
syncRemote(db, newPostId)
{
let self = this;
return new Promise(function(resolve, reject)
{
self.dataUtils.request('/api/post/sync', DataEvent.POSTS_SYNCED, REQUEST_TYPE_POST, CONTENT_TYPE_JSON, db).then((response) =>
{
let bounce = {
message: response,
newPost: newPostId
}
resolve(bounce)
}).catch((err) =>
{
reject(err);
})
})
}
getPost(id)
{
let self = this;
if (id == null)
{
return new Promise(function(resolve, reject)
{
self.db.postList.toArray(array =>
{
resolve(array)
}).catch(err =>
{
reject(err)
})
})
}
else
{
return new Promise(function(resolve, reject)
{
self.db.postList.get(Number(id)).then(obj =>
{
resolve(obj)
}).catch(err =>
{
reject(err)
})
})
}
}
archivePost(id, archive)
{
let self = this;
return new Promise(function(resolve, reject)
{
self.db.postList.update(Number(id),
{
post: archive
}).then(deleted =>
{
self.db.postList.toArray(array =>
{
self.syncRemote(array, null).then(response =>
{
resolve(
{
response
})
}).catch(err =>
{
reject(
{
err
});
});
})
}).catch(e =>
{
console.log("ERROR", e)
});
})
}
//--------------------------
// event handlers
//--------------------------
}