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 || {};
var that = my.basicStorage( spec, my ), priv = {};
/* spec = spec || {};
* Wrapper for the localStorage used to simplify instion of any kind of var that = my.basicStorage(spec, my),
* values priv = {},
*/
var localstorage = { /*
getItem: function (item) { * Wrapper for the localStorage used to simplify instion of any kind of
return JSON.parse (localStorage.getItem(item)); * values
}, */
setItem: function (item,value) { localstorage = {
return localStorage.setItem(item,JSON.stringify (value)); 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];
}
}, },
deleteItem: function (item) { storage_user_array_name,
delete localStorage[item]; 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 {
docPathRev = docPath +'/'+doc._revs_info[0].rev;
newRevision = null;
revs_info = doc._revs_info;
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 var docId = command.getDocId(),
localstorage.setItem(treePath, utilities.updateDocumentTree( docPath = 'jio/local/'+priv.username+'/'+
docTree, prev_rev, newRevision, priv.applicationname+'/'+docId,
revs_info, deletedLeaf) doc = priv.createDocument( docId, docPath );
);
// 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,383 +236,74 @@ var newLocalStorage = function ( spec, my ) { ...@@ -307,383 +236,74 @@ 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'.
* *
* Available options: * Available options:
* - {boolean} conflicts - Add a conflicts object to the response * - {boolean} conflicts - Add a conflicts object to the response
* - {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 () { 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 {
// 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 () { 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
};
// Overriding storage remove
/** /**
* Gets a document list from the local storage. * Removes a document or attachment from the local storage.
* It will retreive an array containing files meta data owned by * It will also remove the path from the local file array.
* the user. * @method remove
* @method allDocs
*/ */
that._remove = function (command) {
// ============== NOT MODIFIED YET =============== setTimeout (function () {
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 allDocs
/** /**
* Removes a document or attachment from the local storage. * Gets a document list from the local storage.
* It will also remove the path from the local file array. * It will retreive an array containing files meta data owned by
* @method remove * the user.
* @method allDocs
*/ */
// ============== FILES WON'T BE DELETED YET =============== that.allDocs = 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);
priv.removeFileName(docid);
// xxx add new revision to tree here
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,41 +665,42 @@ test ('Post', function(){ ...@@ -663,41 +665,42 @@ 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' });
o.spy (o,'value',{ // ========================================
"error": 'forbidden', // 1) POST with id
"message": 'Forbidden', o.jio.post({"_id":'file',"content":'content'},function(err, response){
"reason": 'ID cannot be supplied with a POST request. Please use PUT', o.spy (o,'value',{
"status": 403, "error": 'forbidden',
"statusText": 'Forbidden' "message": 'Forbidden',
"reason": 'ID cannot be supplied with a POST request. Please use PUT',
"status": 403,
"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);
o.spy (o,'value',{ // ========================================
"error": 'forbidden', // 2) POST attachment
"message": 'Forbidden', o.jio.post({"_id":'file/ABC', "mimetype":'text/html',
"reason": 'Attachment cannot be added with a POST request', "content":'<b>hello</b>'},function(err, response){
"status": 403, o.spy (o,'value',{
"statusText": 'Forbidden' "error": 'forbidden',
},'POST attachment = 403 forbidden'); "message": 'Forbidden',
"reason": 'Attachment cannot be added with a POST request',
o.jio.post({ "status": 403,
"_id":'file/ABC', "statusText": 'Forbidden'
"mimetype":'text/html', },'POST attachment = 403 forbidden');
"content":'<b>hello</b>'},o.f); o.f(err);
});
// 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;
}); });
...@@ -755,7 +759,7 @@ test ('Put', function(){ ...@@ -755,7 +759,7 @@ test ('Put', function(){
fake_id_1, fake_id_1,
fake_id_2, fake_id_2,
o = {}; o = {};
o.t = this; o.t = this;
o.clock = o.t.sandbox.useFakeTimers(); o.clock = o.t.sandbox.useFakeTimers();
o.falseRevision; o.falseRevision;
...@@ -775,69 +779,68 @@ test ('Put', function(){ ...@@ -775,69 +779,68 @@ 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' });
// ========================================
// TEST 1) PUT without ID // 1) PUT without ID
o.spy (o,'value',{ o.jio.put({"content":'content'},function(err, response){
"error": 'conflict',
"message": 'Document update conflict.', o.spy (o,'value',{
"reason": 'Missing Document ID and or Revision', "error": 'conflict',
"status": 409, "message": 'Document update conflict.',
"statusText": 'Conflict' "reason": 'Missing Document ID and or Revision',
},'PUT without id = 409 Conflict'); "status": 409,
o.jio.put({"content":'content'},o.f); "statusText": 'Conflict'
},'PUT without id = 409 Conflict');
o.f(err);
});
checkReply(o,null,true); checkReply(o,null,true);
o.clock.tick(base_tick);
// TEST 2) PUT wrong id/rev // ========================================
o.spy (o,'value',{ // 2) PUT wrong id/rev
"error": 'not found', o.jio.put({"content":'content', "_id":'myDoc',
"message": 'Document not found.', "_rev":'1-ABCDEFG'}, function(err, response){
"reason": 'Document not found, please check revision and/or ID', o.spy (o,'value',{
"status": 404, "error": 'not found',
"statusText": 'Not found' "message": 'Document not found.',
"reason": 'Document not found, please check revision and/or ID',
"status": 404,
"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,49 +876,47 @@ test ('Put', function(){ ...@@ -876,49 +876,47 @@ 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.spy (o,'value',{
"error": 'conflict',
"message": 'Document update conflict.',
"reason":
'Revision supplied is not the latest revision',
"status": 409,
"statusText": 'Conflict'
},'PUT false revision = 409 Conflict');
o.jio.put({"content":'content_modified_false', o.jio.put({"content":'content_modified_false',
"_id":'myDoc', "_id":'myDoc',
"_rev":o.falseRevision},o.f); "_rev":o.falseRevision},function(err, response){
o.spy (o,'value',{
"error": 'conflict',
"message": 'Document update conflict.',
"reason":
'Revision supplied is not the latest revision',
"status": 409,
"statusText": 'Conflict'
},'PUT false revision = 409 Conflict');
o.f(err);
});
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.spy (o,'value',{
"error": 'conflict',
"message": 'Document update conflict.',
"reason":
'Missing revs_info required for sync-put',
"status": 409,
"statusText": 'Conflict'
},'PUT no sync info = 409 Conflict');
o.jio.put({"content":'content_modified_false', o.jio.put({"content":'content_modified_false',
"_id":'myDoc', "_id":'myDoc',
"_rev":'1-abcdefg'},o.f); "_rev":'1-abcdefg'},function(err, response){
o.spy (o,'value',{
"error": 'conflict',
"message": 'Document update conflict.',
"reason":
'Missing revs_info required for sync-put',
"status": 409,
"statusText": 'Conflict'
},'PUT no sync info = 409 Conflict');
o.f(err);
});
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',
...@@ -946,7 +944,7 @@ test ('Put', function(){ ...@@ -946,7 +944,7 @@ test ('Put', function(){
{"rev":"3-a9dac9ff5c8e1b2fce58e5397e9b6a8de729d5c6eff8f26a7b71df6348986123","status":"deleted"}, {"rev":"3-a9dac9ff5c8e1b2fce58e5397e9b6a8de729d5c6eff8f26a7b71df6348986123","status":"deleted"},
{"rev":fake_rev_1,"status":"deleted"}, {"rev":fake_rev_1,"status":"deleted"},
{"rev":fake_rev_0,"status":"deleted"} {"rev":fake_rev_0,"status":"deleted"}
], ],
"_revisions":{ "_revisions":{
"start":4, "start":4,
"ids":[ "ids":[
...@@ -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',
...@@ -1000,19 +991,17 @@ test ('Put', function(){ ...@@ -1000,19 +991,17 @@ test ('Put', function(){
{"rev":"3-05210795b6aa8cb5e1e7f021960d233cf963f1052b1a41777ca1a2aff8fd4b61","status":"deleted"}, {"rev":"3-05210795b6aa8cb5e1e7f021960d233cf963f1052b1a41777ca1a2aff8fd4b61","status":"deleted"},
{"rev":"2-67ac10df5b7e2582f2ea2344b01c68d461f44b98fef2c5cba5073cc3bdb5a844","status":"deleted"}, {"rev":"2-67ac10df5b7e2582f2ea2344b01c68d461f44b98fef2c5cba5073cc3bdb5a844","status":"deleted"},
{"rev":fake_rev_2,"status":"deleted"} {"rev":fake_rev_2,"status":"deleted"}
], ],
"_revisions":{ "_revisions":{
"start":3, "start":3,
"ids":[ "ids":[
"05210795b6aa8cb5e1e7f021960d233cf963f1052b1a41777ca1a2aff8fd4b61", "05210795b6aa8cb5e1e7f021960d233cf963f1052b1a41777ca1a2aff8fd4b61",
"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,23 +1038,83 @@ test ('Put', function(){ ...@@ -1049,23 +1038,83 @@ 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
// TEST 18) check document was stored checkFile(response, o, null, true);
//checkFile(response, o, null, true); // 19) check tree was updated
// TEST 19) check tree was updated checkTreeNode(response, o, null, true);
//checkTreeNode(response, o, null, true);
}); });
// 17) TEST PUT UPDATE checkReply(o,null,true);
//checkReply(o,null,true); o.clock.tick(base_tick);
*/ // END PUT
o.jio.stop();
o.clean;
}); });
// ====================== PUTATTACHMENT ==========================
test ('PutAttachment', function(){
// 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);
});
checkReply(o,null,true);
*/
});
/* /*
test ('Document load', function () { test ('Document load', function () {
......
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