[P-JIO-Logo]
Javascript Input/Output
Documentation Index
• Introduction
□ What is jIO?
□ How does it work?
□ Getting started
• How to manage documents?
□ What is a document?
□ Basic Methods
☆ Promises
□ Method Options and Callback Responses
□ Example: How to store a video on localStorage
• Revision Storages: Conflicts and Resolution
□ Why Conflicts can Occur
□ How to solve conflicts
□ Simple Conflict Example
• List of Available Storages
□ Connectors
☆ LocalStorage
☆ DavStorage
☆ S3Storage
☆ XWikiStorage
□ Handlers
☆ IndexStorage
☆ GIDStorage
☆ SplitStorage
☆ Replicate Storage
□ Revision Based Handlers
☆ Revision Storage
☆ Replicate Revision Storage
• JIO Complex Queries
□ What are Complex Queries?
□ Why use Complex Queries?
□ How to use Complex Queries with jIO?
□ How to use Complex Queries outside jIO?
□ Complex Queries in storage connectors
□ Matching properties
□ Should default search types be defined in jIO or in user interface
components?
□ Convert Complex Queries into another type
□ JSON Schemas and Grammar
• For developers
□ Quick start
□ Naming Conventions
□ How to design your own jIO Storage Library
□ Job rules
□ Create Job Condition
□ Add job rules
□ Clear/Replace default job rules
• Authors
• Copyright and license
Introduction
What is jIO?
JIO is a JavaScript library that allows to manage JSON documents on local or
remote storages in asynchronous fashion. jIO is an abstracted API mapped after
CouchDB, that offers connectors to multiple storages, special handlers to
enhance functionality (replication, revisions, indexing) and a query module to
retrieve documents and specific information across storage trees.
How does it work?
JIO is separated into three parts - jIO core and storage library(ies). The core
is using storage libraries (connectors) to interact with the accociated remote
storage servers. Some queries can be used on top of the jIO allDocs method to
query documents based on defined criteria.
JIO uses a job management system, so every method called adds a job into a
queue. The queue is copied in the browsers local storage (by default), so it
can be restored in case of a browser crash. Jobs are being invoked
asynchronously with ongoing jobs not being able to re-trigger to prevent
conflicts.
Getting started
This walkthrough is designed to get you started using a basic jIO instance.
1. Download jIO core, the storages you want to use as well as the
complex-queries scripts as well as the dependencies required for the
storages you intend to use. [Download & Fork]
2. Add the scripts to your HTML page in the following order:
What are Complex Queries?
In jIO, a complex query can tell a storage server to select, filter, sort, or
limit a document list before sending it back. If the server is not able to do
so, the complex query tool can act on the retreived list by itself. Only the
allDocs method can use complex queries.
A query can either be a string (using a specific language useful for writing
queries), or it can be a tree of objects (useful to browse queries). To handle
complex queries, jIO uses a parsed grammar file which is complied using JSCC [
link].
Why use Complex Queries?
Complex queries can be used similar to database queries. So they are useful to:
• search a specific document
• sort a list of documents in a certain order
• avoid retreiving a list of ten thousand documents
• limit the list to show only xy documents by page
For some storages (like localStorage), complex queries can be a powerful tool
to query accessible documents. When querying documents on a distant storage,
some server-side logic should be run to avoid having to request large amount of
documents to run a query on the client. If distant storages are static, an
alternative would be to use an indexStorage with appropriate indices as complex
queries will always try to run the query on the index before querying documents
itself.
How to use Complex Queries with jIO?
Complex queries can be triggered by including the option named query in the
allDocs method call. An example would be:
var options = {};
// search text query
options['query'] = '(creator:"John Doe") AND (format:"pdf")';
// OR query tree
options['query'] = {
type:'complex',
operator:'AND',
query_list: [{
"type": "simple",
"key": "creator",
"value": "John Doe"
}, {
"type": "simple",
"key": "format",
"value": "pdf"
}]
};
// FULL example using filtering criteria
options = {
query: '(creator:"% Doe") AND (format:"pdf")',
limit: [0, 100],
sort_on: [['last_modified', 'descending'], ['creation_date', 'descending']],
select_list: ['title'],
wildcard_character: '%'
};
// execution
jio_instance.allDocs(options, callback);
How to use Complex Queries outside jIO?
Complex Queries provides an API - which namespace is complex_queries. Please
also refer to the Complex Queries sample page on how to use these methods in-
and outside jIO. The module provides:
{
parseStringToObject: [Function: parseStringToObject],
stringEscapeRegexpCharacters: [Function: stringEscapeRegexpCharacters],
select: [Function: select],
sortOn: [Function: sortOn],
limit: [Function: limit],
convertStringToRegExp: [Function: convertStringToRegExp],
QueryFactory: { [Function: QueryFactory] create: [Function] },
Query: [Function: Query],
SimpleQuery: { [Function: SimpleQuery] super_: [Function: Query] },
ComplexQuery: { [Function: ComplexQuery] super_: [Function: Query] }
}
(Reference API comming soon.)
Basic example:
// object list (generated from documents in storage or index)
var object_list = [
{"title": "Document number 1", "creator": "John Doe"},
{"title": "Document number 2", "creator": "James Bond"}
];
// the query to run
var query = 'title: "Document number 1"';
// running the query
complex_queries.QueryFactory.create(query).exec(object_list).then(function (result) {
// here: object_list and result are the same object. It means that object_list has been modified.
// console.log(result);
// [ { "title": "Document number 1", "creator": "John Doe"} ]
});
Other example:
complex_queries.QueryFactory.create(query).exec(
object_list,
{
"select": ['title', 'year'],
"limit": [20, 20], // from 20th to 40th document
"sort_on": [['title', 'ascending'], ['year', 'descending']],
"other_keys_and_values": "are_ignored"
}
).then(operateResult);
// this case is equal to:
complex_queries.QueryFactory.create(query).exec(object_list).then(function (result) {
complex_queries.sortOn([['title', 'ascending'], ['year', 'descending']], result);
complex_queries.limit([20, 20], result);
complex_queries.select(['title', 'year'], result);
return result;
}).then(operateResult);
Complex Queries in storage connectors
The query exec method must only be used if the server is not able to pre-select
documents. As mentioned before, you could use an indexStorage to maintain
indices with key information on all documents in a storage. This index file
will then be used to run queries on if all fields, required in the query answer
are available in the index.
Matching properties
Complex Queries select items which exactly match with the value given in the
query. You can use wildcards ('%' is the default wildcard character), and you
can change the wildcard character in the query options object. If you don't
want to use a wildcard, just set the wildcard character to an empty string.
var query = {
"query": 'creator:"* Doe"',
"wildcard_character": "*"
};
Should default search types be defined in jIO or in user interface components?
Default search types should be defined in the application's user interface
components because criteria like filters will be changed frequently by the
component (change limit: [0, 10] to limit: [10, 10] or sort_on: [['title',
'ascending']] to sort_on: [['creator', 'ascending']]) and each component must
have their own default properties to keep their own behavior.
Convert Complex Queries into another type
Example, convert Query object into human readable string:
var query = complex_queries.QueryFactory.create('year: < 2000 OR title: "*a"'),
option = {
"wildcard_character": "*",
"limit": [0, 10]
},
human_read = {
"<": "is lower than ",
"<=": "is lower or equal than ",
">": "is greater than ",
">=": "is greater or equal than ",
"=": "matches ",
"!=": "doesn't match "
};
query.onParseStart = function (object, option) {
object.start = "The wildcard character is '" +
(option.wildcard_character || "%") +
"' and we need only the " + option.limit[1] + " elements from the numero " +
option.limit[0] + ". ";
};
query.onParseSimpleQuery = function (object, option) {
object.parsed = object.parsed.key + " " + human_read[object.parsed.operator] +
object.parsed.value;
};
query.onParseComplexQuery = function (object, option) {
object.parsed = "I want all document where " +
object.parsed.query_list.join(" " + object.parsed.operator.toLowerCase() +
" ") + ". ";
};
query.onParseEnd = function (object, option) {
object.parsed = object.start + object.parsed + "Thank you!";
};
console.log(query.parse(option));
// logged: "The wildcard character is '*' and we need only the 10 elements
// from the numero 0. I want all document where year is lower than 2000 or title
// matches *a. Thank you!"
JSON Schemas and Grammar
Below you can find schemas for constructing complex queries
• Complex Queries JSON Schema
• Simple Queries JSON Schema
• Complex Queries Grammar
For developers
Quick start
To get started with jIO, clone one of the repositories link in Download & Fork
tab.
To build your library you have to:
• Install NodeJS (including NPM)
• Install Grunt command line with npm. # npm -g install grunt-cli
• Install dev dependencies. $ npm install
• Compile JS/CC parser. $ make (until we found how to compile it with grunt)
• And run build. $ grunt
The repository also includes the built ready-to-use files, so in case you do
not want to build jIO yourself, just use jio.js as well as complex_queries.js
plus the storages and dependencies you need and you will be good to go.
Naming Conventions
All the code follows this Javascript Naming Conventions.
How to design your own jIO Storage Library
Create a constructor:
function MyStorage(storage_description) {
this._value = storage_description.value;
if (typeof this._value !== 'string') {
throw new TypeError("'value' description property is not a string");
}
}
Create 10 methods: post, put, putAttachment, get, getAttachment, remove,
removeAttachment, allDocs, check and repair.
MyStorage.prototype.post = function (command, metadata, option) {
var document_id = metadata._id;
// [...]
};
MyStorage.prototype.get = function (command, param, option) {
var document_id = param._id;
// [...]
};
MyStorage.prototype.putAttachment = function (command, param, option) {
var document_id = param._id;
var attachment_id = param._attachment;
var attachment_data = param._blob;
// [...]
};
// [...]
(To help you to design your methods, some tools are provided by jIO.util.)
The first parameter command provides some methods to act on the JIO job:
• success, to tell JIO that the job is successfully terminated
command.success(status[Text], [{custom key to add to the response}]);
• resolve, is equal to success
• error, to tell JIO that the job cannot be done
command.error(status[Text], [reason], [message], [{custom key to add to the response}])
• retry, to tell JIO that the job cannot be done now, but can be retried
later. (same API than error)
• reject, to tell JIO that the job cannot be done, let JIO to decide to retry
or not. (same API than error)
The second parameter metadata or param is the first parameter given by the JIO
user.
The third parameter option is the option parameter given by the JIO user.
Detail of what should return a method:
• post --> success("created", {"id": new_generated_id})
• put, remove, putAttachment or removeAttachment --> success(204)
• get --> success("ok", {"data": document_metadata})
• getAttachment -->
success("ok", {"data": binary_string, "content_type": content_type})
// or
success("ok", {"data": new Blob([data], {"type": content_type})})
• allDocs --> success("ok", {"data": row_object})
• check -->
// if metadata provides "_id" -> check document state
// if metadata doesn't promides "_id" -> check storage state
success("no_content")
// or
error("conflict", "corrupted", "incoherent document or storage")
• repair -->
// if metadata provides "_id" -> repair document state
// if metadata doesn't promides "_id" -> repair storage state
success("no_content")
// or
error("conflict", "corrupted", "impossible to repair document or storage")
// DON'T DESIGN STORAGES IF THEIR IS NO WAY TO REPAIR INCOHERENT STATES
After setting up all methods, your storage must be added to jIO. This is done
using the jIO.addStorage() method, which requires two parameters: the storage
type (string) add a constructor (function). It is called like this:
// add custom storage to jIO
jIO.addStorage('mystoragetype', MyStorage);
Please refer to localstorage.js implementation for a good example on how to
setup a storage and what methods are required. Also keep in mind, that jIO is a
job-based library, so whenever you trigger a method, a job is created, which
after being processed returns a response.
Job rules
jIO job manager will follow several rules set at the creation of a new jIO
instance. When you try to call a method, jIO will create a job and will make
sure the job is really necessary and will be executed. Thanks to these job
rules, jIO knows what to do with the new job before adding it to the queue. You
can add your own rules like this:
These are the jIO default rules:
var jio_instance = jIO.createJIO(storage_description, {
"job_rules": [{
"code_name": "readers update",
"conditions": [
"sameStorageDescription",
"areReaders",
"sameMethod",
"sameParameters",
"sameOptions"
],
"action": "update"
}, {
"code_name": "metadata writers update",
"conditions": [
"sameStorageDescription",
"areWriters",
"useMetadataOnly",
"sameMethod",
"haveDocumentIds",
"sameParameters"
],
"action": "update"
}, {
"code_name": "writers wait",
"conditions": [
"sameStorageDescription",
"areWriters",
"haveDocumentIds",
"sameDocumentId"
],
"action": "wait"
}]
});
The following actions can be used:
• ok - accept the job
• wait - wait until the end of the selected job
• update - bind the selected job to this one
• deny - reject the job
The following condition function can be used:
• sameStorageDescription - check if the storage descriptions are different.
• areWriters - check if the commands are post, put, putAttachment, remove,
removeAttachment, or repair.
• areReaders - check if the commands are get, getAttachment, allDocs or
check.
• useMetadataOnly - check if the commands are post, put, get, remove or
allDocs.
• sameMethod - check if the commands are equal.
• sameDocumentId - check if the document ids are equal.
• sameParameters - check if the metadata or param are equal in deep.
• sameOptions - check if the command options are equal.
• haveDocumentIds - test if the two commands contain document ids
Create Job Condition
You can create 2 types of function: job condition, and job comparison.
// Job Condition
// Check if the job is a get command
jIO.addJobRuleCondition("isGetMethod", function (job) {
return job.method === 'get';
});
// Job Comparison
// Check if the jobs have the same 'title' property only if they are strings
jIO.addJobRuleCondition("sameTitleIfString", function (job, selected_job) {
if (typeof job.kwargs.title === 'string' &&
typeof selected_job.kwargs.title === 'string') {
return job.kwargs.title === selected_job.kwargs.title;
}
return false;
});
Add job rules
You just have to define job rules in the jIO options:
// Do not accept to post or put a document which title is equal to another
// already running post or put document title
var jio_instance = jIO.createJIO(storage_description, {
"job_rules": [{
"code_name": "avoid similar title",
"conditions": [
"sameStorageDescription",
"areWriters",
"sameTitleIfString"
],
"action": "deny",
"before": "writers update" // optional
// "after": also exists
}]
});
Clear/Replace default job rules
If a job which code_name is equal to readers update, then add this rule will
replace it:
var jio_instance = jIO.createJIO(storage_description, {
"job_rules": [{
"code_name": "readers update",
"conditions": [
"sameStorageDescription",
"areReaders",
"sameMethod",
"haveDocumentIds"
"sameParameters"
// sameOptions is removed
],
"action": "update"
}]
});
Or you can just clear all rules before adding other ones:
var jio_instance = jIO.createJIO(storage_description, {
"clear_job_rules": true,
"job_rules": [{
// ...
}]
});
Authors
• Francois Billioud
• Tristan Cavelier
• Sven Franck
Copyright and license
jIO is an open-source library and is licensed under the LGPL license. More
information on LGPL can be found here
Last update: Thu Oct 31 2013