Commit ea446b38 authored by Sven Franck's avatar Sven Franck

localstorage dumb post

parent b008e2eb
...@@ -73,6 +73,16 @@ ...@@ -73,6 +73,16 @@
}, 100); // 100 ms, for jiotests simple job waiting }, 100); // 100 ms, for jiotests simple job waiting
}; // end put }; // end put
that.putAttachment = function (command) {
setTimeout (function () {
that.success ({
ok:true,
id:command.getDocId(),
rev:generateRevision(command, "putAttachment", true)
});
}, 100); // 100 ms, for jiotests simple job waiting
}; // end put
that.get = function (command) { that.get = function (command) {
setTimeout(function () { setTimeout(function () {
that.success ({ that.success ({
......
/** /**
* JIO Local Storage. Type = 'local'. * JIO Local Storage. Type = 'local'.
* It is a database located in the browser local storage. * Local browser "database" storage.
*/ */
var newLocalStorage = function ( spec, my ) { var newLocalStorage = function (spec, my) {
spec = spec || {}; spec = spec || {};
var that = my.basicStorage( spec, my ), priv = {}; var that = my.basicStorage(spec, my),
priv = {},
/* /*
* Wrapper for the localStorage used to simplify instion of any kind of * Wrapper for the localStorage used to simplify instion of any kind of
* values * values
*/ */
var localstorage = { localstorage = {
getItem: function (item) { getItem: function (item) {
return JSON.parse (localStorage.getItem(item)); return JSON.parse(localStorage.getItem(item));
}, },
setItem: function (item,value) { setItem: function (item, value) {
return localStorage.setItem(item,JSON.stringify (value)); return localStorage.setItem(item, JSON.stringify(value));
}, },
deleteItem: function (item) { deleteItem: function (item) {
delete localStorage[item]; delete localStorage[item];
} }
}; },
storage_user_array_name,
storage_file_array_name;
// attributes
priv.username = spec.username || ''; priv.username = spec.username || '';
priv.secured_username = utilities.secureString(priv.username);
priv.applicationname = spec.applicationname || 'untitled'; priv.applicationname = spec.applicationname || 'untitled';
priv.secured_applicationname = utilities.secureString(priv.applicationname);
var storage_user_array_name = 'jio/local_user_array';
var storage_file_array_name = 'jio/local_file_name_array/' +
priv.secured_username + '/' + priv.secured_applicationname;
// Overriding serialized()
var super_serialized = that.serialized;
that.serialized = function() {
var o = super_serialized();
o.applicationname = priv.applicationname;
o.username = priv.username;
return o;
};
// Overrinding validateState() storage_user_array_name = 'jio/local_user_array';
that.validateState = function() { storage_file_array_name = 'jio/local_file_name_array/' +
if (priv.secured_username) { priv.username + '/' + priv.applicationname;
return '';
}
return 'Need at least one parameter: "username".';
};
/** /**
* Returns a list of users. * Returns a list of users.
...@@ -65,7 +51,7 @@ var newLocalStorage = function ( spec, my ) { ...@@ -65,7 +51,7 @@ var newLocalStorage = function ( spec, my ) {
priv.addUser = function (user_name) { priv.addUser = function (user_name) {
var user_array = priv.getUserArray(); var user_array = priv.getUserArray();
user_array.push(user_name); user_array.push(user_name);
localstorage.setItem(storage_user_array_name,user_array); localstorage.setItem(storage_user_array_name, user_array);
}; };
/** /**
...@@ -101,7 +87,7 @@ var newLocalStorage = function ( spec, my ) { ...@@ -101,7 +87,7 @@ var newLocalStorage = function ( spec, my ) {
priv.addFileName = function (file_name) { priv.addFileName = function (file_name) {
var file_name_array = priv.getFileNameArray(); var file_name_array = priv.getFileNameArray();
file_name_array.push(file_name); file_name_array.push(file_name);
localstorage.setItem(storage_file_array_name,file_name_array); localstorage.setItem(storage_file_array_name, file_name_array);
}; };
/** /**
...@@ -116,7 +102,7 @@ var newLocalStorage = function ( spec, my ) { ...@@ -116,7 +102,7 @@ var newLocalStorage = function ( spec, my ) {
new_array.push(array[i]); new_array.push(array[i]);
} }
} }
localstorage.setItem(storage_file_array_name,new_array); localstorage.setItem(storage_file_array_name, new_array);
}; };
/** /**
...@@ -135,7 +121,7 @@ var newLocalStorage = function ( spec, my ) { ...@@ -135,7 +121,7 @@ var newLocalStorage = function ( spec, my ) {
obj.revs_info = doc._revs_info; obj.revs_info = doc._revs_info;
} }
if (command.getOption('conflicts')) { if (command.getOption('conflicts')) {
obj.conflicts = {total_rows:0,rows:[]}; obj.conflicts = {total_rows:0, rows:[]};
} }
return obj; return obj;
}; };
...@@ -165,101 +151,54 @@ var newLocalStorage = function ( spec, my ) { ...@@ -165,101 +151,54 @@ var newLocalStorage = function ( spec, my ) {
}; };
/** /**
* runDocumentUpdate - run the whole update process for localstorage * Create a new document
* @param {object} doc - the original document object. * @param {object} command Command object
* @param {object} docTree - the document tree
* @param {object} command - command object
* @param {string} docId - document id
* @param {string} attachmentId - attachmentId
* @param {string} docPath - document paths
* @param {string} prev_rev- previous revision
* @param {string} treePath- document tree paths
* @param {boolean} sync - whether this is an update or sync operation!
* @returns {object} success- success object
*/ */
priv.runDocumentUpdate = function ( doc, docTree, command, docId, attachmentId, priv.runDocumenCreate = function (docid, command){
docPath, prev_rev, treePath, sync ){
var docPathRev,
newRevision,
revs_info,
deletedLeaf;
// update ...I don't know what this is doing?
priv.documentObjectUpdate(doc,command.cloneDoc());
// update document - not when put sync-ing
if ( sync === false ){
// create a new revision
doc = utilities.updateDocument(doc, docPath, prev_rev, attachmentId);
docPathRev = docPath+'/'+doc._rev;
newRevision = doc._rev;
revs_info = undefined;
// delete old doc (.../DOCID/old_REVISION)
localstorage.deleteItem(docPath+'/'+prev_rev);
} else { var docId = command.getDocId(),
docPathRev = docPath +'/'+doc._revs_info[0].rev; docPath = 'jio/local/'+priv.username+'/'+
newRevision = null; priv.applicationname+'/'+docId,
revs_info = doc._revs_info; doc = priv.createDocument( docId, docPath );
if ( revs_info[0].status === 'deleted' ){
deletedLeaf = true;
}
}
if ( deletedLeaf === undefined ){
// store new doc (.../DOCID/new_REVISION)
localstorage.setItem(docPathRev, doc);
}
// update tree and store
localstorage.setItem(treePath, utilities.updateDocumentTree(
docTree, prev_rev, newRevision,
revs_info, deletedLeaf)
);
// return SUCCESS
return priv.manageOptions({ok:true,id:docId,rev:doc._rev}, command, doc);
};
/**
* runDocumentCreate - run the whole create process for localstorage
* @param {string} docId - document id
* @param {object} command - command object
* @returns {object} success- success object
*/
priv.runDocumenCreate = function (docId, command){
// create new document and tree
var docPath = 'jio/local/'+priv.secured_username+'/'+
priv.secured_applicationname+'/'+docId,
doc = utilities.createDocument( docId, docPath ),
tree = utilities.createDocumentTree( doc ),
treePath = docPath+'/revision_tree';
// store document // store document
localstorage.setItem(docPath + '/' + doc._rev, doc); localstorage.setItem(docPath + '/' + doc._rev, doc);
// store tree
localstorage.setItem(treePath, tree);
// add user // add user
if (!priv.doesUserExist(priv.secured_username)) { if (!priv.doesUserExist(priv.username)) {
priv.addUser(priv.secured_username); priv.addUser(priv.username);
} }
// add fileName // add fileName
priv.addFileName(docId); priv.addFileName(docId);
// return SUCCESS // return SUCCESS
return priv.manageOptions({ok:true,id:docId,rev:doc._rev}, command, doc); return priv.manageOptions(
{ok:true,id:docId,rev:doc._rev}, command, doc);
}; };
// =============================== METHODS ====================== // ================== storage overrides =====================
// Overriding serialized()
var super_serialized = that.serialized;
that.serialized = function() {
var o = super_serialized();
o.applicationname = priv.applicationname;
o.username = priv.username;
return o;
};
// Overrinding validateState()
that.validateState = function() {
if (priv.username) {
return '';
}
return 'Need at least one parameter: "username".';
};
// Overriding storage post
/** /**
* @method post - Create a document in local storage. * @method _post - Create a document in local storage.
* @stored - 'jio/local/USR/APP/FILE_NAME/REVISION'. * @stored - 'jio/local/USR/APP/FILE_NAME/REVISION'.
* *
* Available options: * Available options:
...@@ -268,36 +207,26 @@ var newLocalStorage = function ( spec, my ) { ...@@ -268,36 +207,26 @@ var newLocalStorage = function ( spec, my ) {
* - {boolean} revs_info - Add revisions informations * - {boolean} revs_info - Add revisions informations
* *
*/ */
that.post = function (command) { that._post = function (command) {
setTimeout (function () { setTimeout (function () {
var docId = command.getDocId(),
reg = utilities.isUUID(docId);
// 403 - no attachments allowed // 403 - no attachments allowed
if (command.getAttachmentId()) { if (command.getAttachmentId()) {
that.error( utilities.throwError( 403, that.error( that.createErrorObject( 403, 'Forbidden',
'Attachment cannot be added with a POST request') 'Attachment cannot be added with a POST request')
); );
return; return;
}
// 403 id was supplied, use PUT
if (reg !== true) {
that.error( utilities.throwError( 403,
'ID cannot be supplied with a POST request. Please use PUT')
);
return;
// ok
} else { } else {
that.success( that.success(
priv.runDocumenCreate(docId, command) priv.runDocumenCreate(command)
); );
} }
}); });
}; };
// Overriding storage put
/** /**
* @method put - Create or Update a document in local storage. * @method put - Create or Update a document in local storage.
* @stored - 'jio/local/USR/APP/FILE_NAME/REVISION'. * @stored - 'jio/local/USR/APP/FILE_NAME/REVISION'.
...@@ -307,124 +236,15 @@ var newLocalStorage = function ( spec, my ) { ...@@ -307,124 +236,15 @@ var newLocalStorage = function ( spec, my ) {
* - {boolean} revs - Add the revisions history of the document * - {boolean} revs - Add the revisions history of the document
* - {boolean} revs_info - Add revisions informations * - {boolean} revs_info - Add revisions informations
*/ */
that.put = function (command) { that._put = function (command) {
setTimeout (function () { setTimeout (function () {
var docId = command.getDocId(),
prev_rev = command.getDocInfo('_rev'),
docPath ='jio/local/'+priv.secured_username+'/'+
priv.secured_applicationname+'/'+docId,
treePath = docPath+'/revision_tree',
docTree = localstorage.getItem(treePath),
doc,
docPathRev,
activeLeaves,
reg = utilities.isUUID(docId);
// no tree = create document or error
if (!docTree) {
// 404 id/revision provided = update, incorrect revision
if ( prev_rev !== undefined && reg === false ){
that.error( utilities.throwError( 404,
'Document not found, please check revision and/or ID')
);
return;
}
// 409 no revision and UUID = create, no id provided
if ( prev_rev === undefined && reg === true){
that.error( utilities.throwError( 409,
'Missing Document ID and or Revision')
);
return;
}
// if passed here, we create.
// it could be create (id+content) or update (sans revision)
// but since no tree was found we end here with a NEW id only
// (otherwise tree would be have been found).
that.success(
priv.runDocumenCreate(docId, command)
);
} else {
// found a tree
activeLeaves = utilities.getActiveLeaves( docTree );
// check if revision is on doc-tree and if it is an active leaf
if ( !utilities.isInObject( prev_rev, activeLeaves ) ) {
// check if it's a dead leaf (wrong revision)
if ( utilities.isDeadLeaf( prev_rev, docTree ) ){
// 409 deleted leaf/branch = wrong revision
that.error( utilities.throwError( 409,
'Revision supplied is not the latest revision')
);
return;
}
// maybe a sync-PUT from another storage, we must
// have revs_info option, otherwise we cannot know
// where to put the file and update the storage tree
if ( !utilities.isDeadLeaf( prev_rev, docTree ) &&
command.getDocInfo('_revs_info') === undefined ){
// 409 no revs_info provided
that.error( utilities.throwError( 409,
'Missing revs_info required for sync-put')
);
return;
} else {
// SYNC PUT
// revs_info is provided, this is a new version
// store this document and merge
// NOTE: we also have to SYNC PUT deleted versions
// otherwise the tree will not be the same AND
// other storages will not know which versions of a
// document have been deleted!!!!
// get the new document
doc = command.getDoc();
// ok
that.success(
priv.runDocumentUpdate(doc, docTree, command,
docId, undefined, docPath, prev_rev,
treePath, true)
);
}
} else {
// revision matches a currently active leaf
// = update of an existing document version
// get doc
docPathRev = docPath +'/'+prev_rev;
doc = localstorage.getItem(docPathRev);
if (!doc ){
// 404 document not available, should not happen!
that.error( utilities.throwError( 404,
'Referenced document not found')
);
return;
} else {
// ok
that.success(
priv.runDocumentUpdate(doc, docTree, command,
docId, undefined, docPath, prev_rev,
treePath, false)
);
}
}
}
}); });
}; };
// Overriding storage putAttachment
/** /**
* @method putAttachment - Saves/updates an attachment of a document * @method putAttachment - Saves/updates an attachment of a document
* @stored at - 'jio/local/USR/APP/FILE_NAME/REVISION/ATTACHMENTID'. * @stored at - 'jio/local/USR/APP/FILE_NAME/REVISION/ATTACHMENTID'.
...@@ -434,256 +254,56 @@ var newLocalStorage = function ( spec, my ) { ...@@ -434,256 +254,56 @@ var newLocalStorage = function ( spec, my ) {
* - {boolean} revs - Add the revisions history of the document * - {boolean} revs - Add the revisions history of the document
* - {boolean} revs_info - Add revisions informations * - {boolean} revs_info - Add revisions informations
*/ */
that.putAttachment = function (command) { that._putAttachment = function (command) {
setTimeout( function () {
var docId = command.getDocId(),
docPath ='jio/local/'+priv.secured_username+'/'+
priv.secured_applicationname+'/'+docId,
prev_rev = command.getDocInfo('_rev'),
treePath = docPath+'/revision_tree',
docTree = localstorage.getItem(treePath),
doc,
docPathRev,
activeLeaves,
attachmentId,
attachment,
attachmentPath;
if (!docTree) {
// 404 document wasn't found = wrong id or revision
that.error( utilities.throwError( 404,
'Document not found, please check document ID')
);
return;
} else {
// found a tree
activeLeaves = utilities.getActiveLeaves( docTree );
// check if revision is on tree
if ( utilities.isInObject( prev_rev, activeLeaves ) ) {
// check if dead leaf
if ( utilities.isDeadLeaf( prev_rev, docTree ) ){
// 409 deleted leaf/branch = wrong revision
that.error( utilities.throwError( 409,
'Trying to update on a previous document version')
);
return;
} else { setTimeout (function () {
// revision is ok
attachmentId = command.getAttachmentId();
// 409 missing attachment id
if ( !attachmentId ){
that.error( utilities.throwError( 409,
'No attachment id specified')
);
return;
} else {
// set attachment
attachmentPath = docPath+'/'+prev_rev+'/'+attachmentId;
attachment = localstorage.getItem(attachmentPath);
// store/update attachment
localstorage.setItem(attachmentPath,command.getContent());
// get doc
docPathRev = docPath +'/'+prev_rev;
doc = localstorage.getItem(docPathRev);
// ok
that.success(
priv.runDocumentUpdate(doc, docTree, command,
docId, attachmentId, docPath, prev_rev,
treePath, false)
);
}
}
} else {
// 404 revision supplied is not on tree
that.error( utilities.throwError( 404,
'Document not found, please check revision')
);
return;
}
}
}); });
}; // end putAttachment
};
// Overriding storage get
/** /**
* Loads a document from the local storage. * Loads a document from the local storage.
* It will load file in 'jio/local/USR/APP/FILE_NAME'. * It will load file in 'jio/local/USR/APP/FILE_NAME'.
* @method get * @method get
*/ */
that.get = function (command) { that._get = function (command) {
setTimeout(function () {
var docid, doc, docpath, attmtid, attmt;
docid = command.getDocId();
docpath = 'jio/local/'+priv.secured_username+'/'+
priv.secured_applicationname+'/'+docid;
attmtid = command.getAttachmentId();
if (attmtid) {
// this is an attachment
attmt = localstorage.getItem(docpath+'/'+attmtid);
if (!attmt) {
// there is no attachment to get
that.error({
status:404,statusText:'Not found',error:'not_found',
message:'Document is missing attachment.',
reason:'document is missing attachment'
});
return;
}
// send the attachment content
that.success(attmt);
} else {
// this is a document
doc = localstorage.getItem(docpath);
if (!doc) {
// the document does not exist
that.error ({
status:404,statusText:'Not Found.',
error:'not_found',
message:'Document "'+ docid + '" not found.',
reason:'missing'
});
} else {
if (!command.getDocInfo('revs')) {
delete doc._revisions;
}
if (!command.getDocInfo('revs_info')) {
delete doc._revs_info;
}
if (command.getDocInfo('conflicts')) {
doc._conflicts = {total_rows:0,rows:[]};
}
that.success (doc);
}
}
});
}; // end get
/** setTimeout (function () {
* Gets a document list from the local storage.
* It will retreive an array containing files meta data owned by
* the user.
* @method allDocs
*/
// ============== NOT MODIFIED YET ===============
that.allDocs = function (command) {
setTimeout(function () {
var new_array = [], array = [], i, l, k = 'key',
path = 'jio/local/'+priv.secured_username+'/'+
priv.secured_applicationname, file_object = {};
array = priv.getFileNameArray();
for (i = 0, l = array.length; i < l; i += 1) {
file_object =
localstorage.getItem(path+'/'+array[i]);
if (file_object) {
if (command.getOption('metadata_only')) {
new_array.push ({
id:file_object._id,key:file_object._id,value:{
_creation_date:file_object._creation_date,
_last_modified:file_object._last_modified}});
} else {
new_array.push ({
id:file_object._id,key:file_object._id,value:{
content:file_object.content,
_creation_date:file_object._creation_date,
_last_modified:file_object._last_modified}});
}
}
}
that.success ({total_rows:new_array.length,rows:new_array});
}); });
}; // end allDocs
};
// Overriding storage remove
/** /**
* Removes a document or attachment from the local storage. * Removes a document or attachment from the local storage.
* It will also remove the path from the local file array. * It will also remove the path from the local file array.
* @method remove * @method remove
*/ */
// ============== FILES WON'T BE DELETED YET =============== that._remove = function (command) {
that.remove = function (command) {
// wait a little in order to simulate asynchronous saving
setTimeout (function () { setTimeout (function () {
var docid, doc, docpath, prev_rev, attmtid, attmt, attpath;
docid = command.getDocId(),
docpath = 'jio/local/'+priv.secured_username+'/'+
priv.secured_applicationname+'/'+docid;
prev_rev = command.getDocInfo('_rev');
attmtid = command.getAttachmentId();
// xxx remove attachment if exists
if( attmtid ){
attpath = docpath+'/'+attmtid;
attmt = localstorage.getItem(attpath);
if ( attmt ){
// deleting
localstorage.deleteItem(attpath);
priv.removeFileName(attpath);
// xxx add new revision to tree here
that.success ({ok:true,id:command.getDocId()});
} else {
// the document does not exist
that.error ({
status:404,statusText:'Not Found.',
error:'not_found',
message:'Document "'+ docid + '" not found.',
reason:'missing'
}); });
}
// xxx remove document if exists
} else {
doc = localstorage.getItem(docpath);
// document exists };
if (doc){
// check for wrong revision
if ( doc._rev === prev_rev ){
localstorage.deleteItem(docpath); // Overriding storage allDocs
priv.removeFileName(docid); /**
* Gets a document list from the local storage.
* It will retreive an array containing files meta data owned by
* the user.
* @method allDocs
*/
that.allDocs = function (command) {
// xxx add new revision to tree here setTimeout (function () {
that.success ({ok:true,id:command.getDocId()});
} else {
// the document does not exist
that.error ({
status:409,statusText:'Conflict',error:'conflict',
message:'Document update conflict.',
reason:'Trying to update an outdated revision'
}); });
}
} else {
// the document does not exist
that.error ({
status:404,statusText:'Not Found.',
error:'not_found',
message:'Document "'+ docid + '" not found.',
reason:'missing'
});
}
}
}); };
}; // end remove
return that; return that;
}; };
......
...@@ -26,6 +26,10 @@ var command = function(spec, my) { ...@@ -26,6 +26,10 @@ var command = function(spec, my) {
// xxx fixed spec.content to spec.doc.content for PUTATTACHMENT // xxx fixed spec.content to spec.doc.content for PUTATTACHMENT
// xxx need extra check for GET, otherwise spec.doc is undefined // xxx need extra check for GET, otherwise spec.doc is undefined
console.log("COMMAND");
console.log( spec );
console.log( spec.doc );
console.log( spec.doc.content );
priv.content = spec.doc === undefined ? undefined : priv.content = spec.doc === undefined ? undefined :
typeof spec.doc.content === 'string'? typeof spec.doc.content === 'string'?
spec.doc.content: spec.doc.content:
...@@ -80,8 +84,6 @@ var command = function(spec, my) { ...@@ -80,8 +84,6 @@ var command = function(spec, my) {
* @return {object} the document. * @return {object} the document.
*/ */
that.getDoc = function() { that.getDoc = function() {
console.log("where is my doc");
console.log( priv.doc );
return priv.doc; return priv.doc;
}; };
......
...@@ -11,7 +11,8 @@ var putAttachmentCommand = function(spec, my) { ...@@ -11,7 +11,8 @@ var putAttachmentCommand = function(spec, my) {
that.executeOn = function (storage) { that.executeOn = function (storage) {
storage.putAttachment (that); storage.putAttachment (that);
}; };
console.log("putAttachmentCommand");
console.log( typeof that.getContent() );
that.validateState = function () { that.validateState = function () {
if (typeof that.getContent() !== 'string') { if (typeof that.getContent() !== 'string') {
that.error({ that.error({
......
...@@ -147,6 +147,11 @@ ...@@ -147,6 +147,11 @@
}; };
priv.parametersToObject = function (list, default_options) { priv.parametersToObject = function (list, default_options) {
console.log("aloha");
console.log("what do we have");
console.log( list );
console.log( default_options );
var k, i = 0, callbacks = [], param = {options:{}}; var k, i = 0, callbacks = [], param = {options:{}};
for (i = 0; i < list.length; i += 1) { for (i = 0; i < list.length; i += 1) {
if (typeof list[i] === 'object') { if (typeof list[i] === 'object') {
......
...@@ -57,6 +57,7 @@ basic_test_function_generator = function(o,res,value,message) { ...@@ -57,6 +57,7 @@ basic_test_function_generator = function(o,res,value,message) {
}; };
}, },
basic_spy_function = function(o,res,value,message,fun) { basic_spy_function = function(o,res,value,message,fun) {
fun = fun || 'f'; fun = fun || 'f';
o[fun] = basic_test_function_generator(o,res,value,message); o[fun] = basic_test_function_generator(o,res,value,message);
o.t.spy(o,fun); o.t.spy(o,fun);
...@@ -65,6 +66,7 @@ basic_tick_function = function (o) { ...@@ -65,6 +66,7 @@ basic_tick_function = function (o) {
var tick, fun, i = 1; var tick, fun, i = 1;
tick = 1000; tick = 1000;
fun = fun || 'f'; fun = fun || 'f';
if (typeof arguments[i] === 'number') { if (typeof arguments[i] === 'number') {
tick = arguments[i]; i++; tick = arguments[i]; i++;
} }
...@@ -663,12 +665,14 @@ test ('Post', function(){ ...@@ -663,12 +665,14 @@ test ('Post', function(){
o.spy = basic_spy_function; o.spy = basic_spy_function;
o.clean = clean_up_local_storage_function(); o.clean = clean_up_local_storage_function();
o.username = 'MrPost'; o.username = 'MrPost';
o.testBuildTree = [];
o.testRevisionStorage = []; o.testRevisionStorage = [];
// let's go // let's go
o.jio = JIO.newJio({ type:'local', username:o.username, o.jio = JIO.newJio({ type:'local', username:o.username,
applicationname:'jiotests' }); applicationname:'jiotests' });
// ========================================
// 1) POST with id
o.jio.post({"_id":'file',"content":'content'},function(err, response){
o.spy (o,'value',{ o.spy (o,'value',{
"error": 'forbidden', "error": 'forbidden',
"message": 'Forbidden', "message": 'Forbidden',
...@@ -676,12 +680,14 @@ test ('Post', function(){ ...@@ -676,12 +680,14 @@ test ('Post', function(){
"status": 403, "status": 403,
"statusText": 'Forbidden' "statusText": 'Forbidden'
},'POST with id = 403 forbidden'); },'POST with id = 403 forbidden');
o.f(err);
o.jio.post({"_id":'file',"content":'content'},o.f); });
// TEST 1) POST with id
checkReply(o,null,true); checkReply(o,null,true);
o.clock.tick(base_tick);
// ========================================
// 2) POST attachment
o.jio.post({"_id":'file/ABC', "mimetype":'text/html',
"content":'<b>hello</b>'},function(err, response){
o.spy (o,'value',{ o.spy (o,'value',{
"error": 'forbidden', "error": 'forbidden',
"message": 'Forbidden', "message": 'Forbidden',
...@@ -689,15 +695,12 @@ test ('Post', function(){ ...@@ -689,15 +695,12 @@ test ('Post', function(){
"status": 403, "status": 403,
"statusText": 'Forbidden' "statusText": 'Forbidden'
},'POST attachment = 403 forbidden'); },'POST attachment = 403 forbidden');
o.f(err);
o.jio.post({ });
"_id":'file/ABC',
"mimetype":'text/html',
"content":'<b>hello</b>'},o.f);
// TEST 2) POST attachment
checkReply(o,null,true); checkReply(o,null,true);
o.clock.tick(base_tick);
// ========================================
// 3) POST content
o.jio.post({"content":'content'}, o.jio.post({"content":'content'},
function(err, response) { function(err, response) {
o.spy(o,'value',{"ok":true,"id":response.id,"rev":response.rev}, o.spy(o,'value',{"ok":true,"id":response.id,"rev":response.rev},
...@@ -712,13 +715,14 @@ test ('Post', function(){ ...@@ -712,13 +715,14 @@ test ('Post', function(){
o.buildTestTree = {"kids":[],"rev":o.testRevisionStorage[0], o.buildTestTree = {"kids":[],"rev":o.testRevisionStorage[0],
"status":'available',"type":'leaf'}; "status":'available',"type":'leaf'};
// TEST 4) check if document is created and correct // 4) check if document is created and correct
checkFile(response, o, null, true); checkFile(response, o, null, true);
// TEST 5) check if document tree is created and correct // 5) check if document tree is created and correct
checkTreeNode(response, o, null, true); checkTreeNode(response, o, null, true);
}); });
// 3) TEST POST content
checkReply(o,null,true); checkReply(o,null,true);
o.clock.tick(base_tick);
// END POST
o.jio.stop(); o.jio.stop();
o.clean; o.clean;
}); });
...@@ -775,14 +779,15 @@ test ('Put', function(){ ...@@ -775,14 +779,15 @@ test ('Put', function(){
o.spy = basic_spy_function; o.spy = basic_spy_function;
o.clean = clean_up_local_storage_function(); o.clean = clean_up_local_storage_function();
o.username = 'MrPutt'; o.username = 'MrPutt';
o.testBuildTree = [];
o.testRevisionStorage = []; o.testRevisionStorage = [];
// let's go // let's go
o.jio = JIO.newJio({ type:'local', username:o.username, o.jio = JIO.newJio({ type:'local', username:o.username,
applicationname:'jiotests' }); applicationname:'jiotests' });
// ========================================
// 1) PUT without ID
o.jio.put({"content":'content'},function(err, response){
// TEST 1) PUT without ID
o.spy (o,'value',{ o.spy (o,'value',{
"error": 'conflict', "error": 'conflict',
"message": 'Document update conflict.', "message": 'Document update conflict.',
...@@ -790,10 +795,14 @@ test ('Put', function(){ ...@@ -790,10 +795,14 @@ test ('Put', function(){
"status": 409, "status": 409,
"statusText": 'Conflict' "statusText": 'Conflict'
},'PUT without id = 409 Conflict'); },'PUT without id = 409 Conflict');
o.jio.put({"content":'content'},o.f); o.f(err);
});
checkReply(o,null,true); checkReply(o,null,true);
o.clock.tick(base_tick);
// TEST 2) PUT wrong id/rev // ========================================
// 2) PUT wrong id/rev
o.jio.put({"content":'content', "_id":'myDoc',
"_rev":'1-ABCDEFG'}, function(err, response){
o.spy (o,'value',{ o.spy (o,'value',{
"error": 'not found', "error": 'not found',
"message": 'Document not found.', "message": 'Document not found.',
...@@ -801,43 +810,37 @@ test ('Put', function(){ ...@@ -801,43 +810,37 @@ test ('Put', function(){
"status": 404, "status": 404,
"statusText": 'Not found' "statusText": 'Not found'
},'PUT with wrong id/revision = 404 Not found'); },'PUT with wrong id/revision = 404 Not found');
o.jio.put({"content":'content',"_id":'myDoc', o.f(err);
"_rev":'1-ABCDEFG'},o.f); });
checkReply(o,null,true); checkReply(o,null,true);
o.clock.tick(base_tick); o.clock.tick(base_tick);
// ========================================
// start adding content // 3) PUT content
o.jio.put({"content":'content',"_id":'myDoc'}, o.jio.put({"content":'content',"_id":'myDoc'},
function(err, response) { function(err, response) {
o.spy(o,'value',{"ok":true,"id":response.id,"rev":response.rev}, o.spy(o,'value',{"ok":true,"id":response.id,"rev":response.rev},
'PUT content = ok'); 'PUT content = ok');
o.f(response); o.f(response);
// store falseRevision
o.falseRevision = response.rev; o.falseRevision = response.rev;
// build tree manually
o.testRevisionStorage.unshift(response.rev); o.testRevisionStorage.unshift(response.rev);
o.buildTestTree = {"kids":[],"rev":o.testRevisionStorage[0], o.buildTestTree = {"kids":[],"rev":o.testRevisionStorage[0],
"status":'available',"type":'leaf'}; "status":'available',"type":'leaf'};
// ========================================
// TEST 4) check file was created // 4) check file was created
checkFile(response, o, null, true); checkFile(response, o, null, true);
// TEST 5) check tree was created // ========================================
// 5) check tree was created
checkTreeNode(response, o, null, true); checkTreeNode(response, o, null, true);
}); });
// 3) TEST PUT content
checkReply(o,null,true); checkReply(o,null,true);
o.clock.tick(base_tick); o.clock.tick(base_tick);
// ========================================
// update document // 6) PUT UPDATE (modify content)
o.jio.put({"content":'content_modified',"_id":'myDoc', o.jio.put({"content":'content_modified',"_id":'myDoc',
"_rev":o.testRevisionStorage[0]}, "_rev":o.testRevisionStorage[0]},
function(err, response) { function(err, response) {
o.spy(o,'value',{"ok":true,"id":response.id,"rev":response.rev}, o.spy(o,'value',{"ok":true,"id":response.id,"rev":response.rev},
'PUT content = ok'); 'PUT content = ok');
o.f(response); o.f(response);
...@@ -847,23 +850,20 @@ test ('Put', function(){ ...@@ -847,23 +850,20 @@ test ('Put', function(){
o.testRevisionStorage[0],"status":'available', o.testRevisionStorage[0],"status":'available',
"type":'leaf'}],"rev":o.testRevisionStorage[1], "type":'leaf'}],"rev":o.testRevisionStorage[1],
"status":'deleted',"type":'branch'}; "status":'deleted',"type":'branch'};
// ========================================
// TEST 7) check document was replaced // 7) check document was replaced
checkFile(response, o, null, true); checkFile(response, o, null, true);
// TEST 8) check tree was updated // ========================================
// 8) check tree was updated
checkTreeNode(response, o, null, true); checkTreeNode(response, o, null, true);
}); });
// 6) TEST PUT UPDATE
checkReply(o,null,true); checkReply(o,null,true);
o.clock.tick(base_tick); o.clock.tick(base_tick);
// ========================================
// update document 2nd time // 9. update document (modify again)
o.jio.put({"content":'content_modified_again', o.jio.put({"content":'content_modified_again',
"_id":'myDoc', "_id":'myDoc', "_rev":o.testRevisionStorage[0]},
"_rev":o.testRevisionStorage[0]},
function(err, response) { function(err, response) {
o.spy(o,'value',{"ok":true,"id":response.id, o.spy(o,'value',{"ok":true,"id":response.id,
"rev":response.rev}, 'PUT content = ok'); "rev":response.rev}, 'PUT content = ok');
o.f(response); o.f(response);
...@@ -876,18 +876,19 @@ test ('Put', function(){ ...@@ -876,18 +876,19 @@ test ('Put', function(){
"rev":o.testRevisionStorage[2],"status":'deleted', "rev":o.testRevisionStorage[2],"status":'deleted',
"type":'branch'}; "type":'branch'};
// TEST 10) check document was replaced // 10) check document was replaced
checkFile(response, o, null, true); checkFile(response, o, null, true);
// TEST 11) check tree was updated // 11) check tree was updated
checkTreeNode(response, o, null, true); checkTreeNode(response, o, null, true);
}); });
// 9) TEST PUT UPDATE
checkReply(o,null,true); checkReply(o,null,true);
o.clock.tick(base_tick); o.clock.tick(base_tick);
// ========================================
// TEST 12) PUT false revision // 12) PUT false revision
o.jio.put({"content":'content_modified_false',
"_id":'myDoc',
"_rev":o.falseRevision},function(err, response){
o.spy (o,'value',{ o.spy (o,'value',{
"error": 'conflict', "error": 'conflict',
"message": 'Document update conflict.', "message": 'Document update conflict.',
...@@ -896,15 +897,15 @@ test ('Put', function(){ ...@@ -896,15 +897,15 @@ test ('Put', function(){
"status": 409, "status": 409,
"statusText": 'Conflict' "statusText": 'Conflict'
},'PUT false revision = 409 Conflict'); },'PUT false revision = 409 Conflict');
o.f(err);
o.jio.put({"content":'content_modified_false', });
"_id":'myDoc',
"_rev":o.falseRevision},o.f);
checkReply(o,null,true); checkReply(o,null,true);
o.clock.tick(base_tick); o.clock.tick(base_tick);
// ========================================
// TEST 13) SYNC-PUT no revs_info // 13) SYNC-PUT no revs_info
o.jio.put({"content":'content_modified_false',
"_id":'myDoc',
"_rev":'1-abcdefg'},function(err, response){
o.spy (o,'value',{ o.spy (o,'value',{
"error": 'conflict', "error": 'conflict',
"message": 'Document update conflict.', "message": 'Document update conflict.',
...@@ -913,12 +914,9 @@ test ('Put', function(){ ...@@ -913,12 +914,9 @@ test ('Put', function(){
"status": 409, "status": 409,
"statusText": 'Conflict' "statusText": 'Conflict'
},'PUT no sync info = 409 Conflict'); },'PUT no sync info = 409 Conflict');
o.f(err);
o.jio.put({"content":'content_modified_false', });
"_id":'myDoc',
"_rev":'1-abcdefg'},o.f);
checkReply(o,null,true); checkReply(o,null,true);
o.clock.tick(base_tick); o.clock.tick(base_tick);
// add a new document version with fake revs_info // add a new document version with fake revs_info
...@@ -935,8 +933,8 @@ test ('Put', function(){ ...@@ -935,8 +933,8 @@ test ('Put', function(){
fake_id_2 = o.testRevisionStorage[2].split('-')[1]; fake_id_2 = o.testRevisionStorage[2].split('-')[1];
fake_id_1 = o.testRevisionStorage[1].split('-')[1]; fake_id_1 = o.testRevisionStorage[1].split('-')[1];
fake_id_0 = o.testRevisionStorage[0].split('-')[1]; fake_id_0 = o.testRevisionStorage[0].split('-')[1];
// ========================================
// put a new document version // 14) PUT UPDATE A TREE using revs_info
o.jio.put({ o.jio.put({
"content":'a_new_version', "content":'a_new_version',
"_id":'myDoc', "_id":'myDoc',
...@@ -957,8 +955,6 @@ test ('Put', function(){ ...@@ -957,8 +955,6 @@ test ('Put', function(){
]} ]}
}, },
function(err, response) { function(err, response) {
//o.testRevisionStorage.unshift(response.rev);
o.buildTestTree = { o.buildTestTree = {
"kids":[ "kids":[
{ {
...@@ -975,23 +971,18 @@ test ('Put', function(){ ...@@ -975,23 +971,18 @@ test ('Put', function(){
"rev":o.testRevisionStorage[1],"status":'deleted',"type":'branch'}], "rev":o.testRevisionStorage[1],"status":'deleted',"type":'branch'}],
"rev":o.testRevisionStorage[2],"status":'deleted',"type":'branch' "rev":o.testRevisionStorage[2],"status":'deleted',"type":'branch'
}; };
o.spy(o,'value',{"ok":true,"id":response.id, o.spy(o,'value',{"ok":true,"id":response.id,
"rev":response.rev}, 'PUT SYNC = ok'); "rev":response.rev}, 'PUT SYNC = ok');
o.f(response); o.f(response);
// 15) check document was stored
// TEST 15) check document was stored
checkFile(response, o, null, true); checkFile(response, o, null, true);
// TEST 16) check tree was updated // 16) check tree was updated
checkTreeNode(response, o, null, true); checkTreeNode(response, o, null, true);
}); });
// 14) TEST PUT UPDATE
checkReply(o,null,true); checkReply(o,null,true);
o.clock.tick(base_tick); o.clock.tick(base_tick);
/* // ========================================
// put a new deleted version // 17) PUT UPDATE (deleted tree)
o.jio.put({ o.jio.put({
"content":'a_deleted_version', "content":'a_deleted_version',
"_id":'myDoc', "_id":'myDoc',
...@@ -1008,11 +999,9 @@ test ('Put', function(){ ...@@ -1008,11 +999,9 @@ test ('Put', function(){
"67ac10df5b7e2582f2ea2344b01c68d461f44b98fef2c5cba5073cc3bdb5a844", "67ac10df5b7e2582f2ea2344b01c68d461f44b98fef2c5cba5073cc3bdb5a844",
fake_id_2 fake_id_2
]} ]}
}, },
function(err, response) { function(err, response) {
//o.testRevisionStorage.unshift(response.rev);
o.buildTestTree = { o.buildTestTree = {
"kids":[{ "kids":[{
"kids":[ "kids":[
...@@ -1049,24 +1038,84 @@ test ('Put', function(){ ...@@ -1049,24 +1038,84 @@ test ('Put', function(){
"status":'deleted', "status":'deleted',
"type":'branch' "type":'branch'
}; };
o.spy(o,'value',{"ok":true,"id":response.id, o.spy(o,'value',{"ok":true,"id":response.id,
"rev":response.rev}, 'PUT SYNC dead leaf = ok'); "rev":response.rev}, 'PUT SYNC dead leaf = ok');
o.f(response); o.f(response);
// 18) check document was stored
checkFile(response, o, null, true);
// 19) check tree was updated
checkTreeNode(response, o, null, true);
});
checkReply(o,null,true);
o.clock.tick(base_tick);
// END PUT
o.jio.stop();
o.clean;
});
// TEST 18) check document was stored // ====================== PUTATTACHMENT ==========================
//checkFile(response, o, null, true); test ('PutAttachment', function(){
// TEST 19) check tree was updated
//checkTreeNode(response, o, null, true);
// runs following assertions
// 1) PUTATTACHMENT with wrong id/rev1
// 2) PUTATTACHMENT without id/rev1
var o = {};
o.t = this;
o.clock = o.t.sandbox.useFakeTimers();
o.falseRevision;
localstorage = {
getItem: function (item) {
return JSON.parse (localStorage.getItem(item));
},
setItem: function (item,value) {
return localStorage.setItem(item,JSON.stringify (value));
},
deleteItem: function (item) {
delete localStorage[item];
}
};
o.clock.tick(base_tick);
o.spy = basic_spy_function;
o.clean = clean_up_local_storage_function();
o.username = 'MrPuttAttachment';
o.testRevisionStorage = [];
// let's go
o.jio = JIO.newJio({ type:'local', username:o.username,
applicationname:'jiotests' });
// ========================================
// 1) PUTATTACHMENT with wrong id/rev
o.jio.putAttachment("ABC/DEF","A-1aaa","<b>hello</b>","text/html",function(err, response){
o.spy (o,'value',{
"error": 'not found',
"message": 'Document not found.',
"reason": 'Document not found, please check document ID',
"status": 404,
"statusText": 'Not found'
},'PUTATTACHMENT without id = 404 NOT FOUND');
o.f(err);
});
checkReply(o,null,true);
// ========================================
// 2) PUTATTACHMENT with wrong id/rev
/*
o.jio.putAttachment("ABC/DEF","text/html","<b>hello</b>",function(err, response){
o.spy (o,'value',{
"error": 'not found',
"message": 'Document not found.',
"reason": 'Document not found, please check document ID',
"status": 404,
"statusText": 'Not found'
},'PUTATTACHMENT without id = 404 NOT FOUND');
o.f(err);
}); });
// 17) TEST PUT UPDATE checkReply(o,null,true);
//checkReply(o,null,true);
*/ */
}); });
/* /*
test ('Document load', function () { test ('Document load', function () {
// Test if LocalStorage can load documents. // Test if LocalStorage can load documents.
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment