Page MenuHomeSealhub

No OneTemporary

Authored By
Unknown
Size
193 KB
Referenced Files
None
Subscribers
None
diff --git a/.jscsrc b/.jscsrc
new file mode 100644
index 00000000..7ed03497
--- /dev/null
+++ b/.jscsrc
@@ -0,0 +1,36 @@
+{
+ "validateIndentation": "\t",
+ "disallowSpacesInAnonymousFunctionExpression": {
+ "beforeOpeningRoundBrace": true,
+ "beforeOpeningCurlyBrace": true
+ },
+ "requireSpacesInNamedFunctionExpression": {
+ "beforeOpeningRoundBrace": true,
+ "beforeOpeningCurlyBrace": true
+ },
+ "disallowSpacesInCallExpression": true,
+ "requireSpacesInFunctionDeclaration": {
+ "beforeOpeningRoundBrace": true,
+ "beforeOpeningCurlyBrace": true
+ },
+ "requireSpacesInForStatement": true,
+ "requireSpaceBeforeKeywords": [
+ "else",
+ "while",
+ "catch"
+ ],
+ "requireSpaceAfterKeywords": [
+ "do",
+ "for",
+ "if",
+ "else",
+ "switch",
+ "case",
+ "try",
+ "catch",
+ "while",
+ "with",
+ "return",
+ "typeof"
+ ]
+}
\ No newline at end of file
diff --git a/.jshintrc b/.jshintrc
deleted file mode 100644
index 68d99c38..00000000
--- a/.jshintrc
+++ /dev/null
@@ -1,4 +0,0 @@
-{
- "asi":true,
- "supernew": true
-}
\ No newline at end of file
diff --git a/docs/reference.md b/docs/reference.md
index cee029cd..8e899b6c 100644
--- a/docs/reference.md
+++ b/docs/reference.md
@@ -1,497 +1,553 @@
# Reference
## Chip Types
### Access Strategy
Access strategies are functions that take a context as an argument and based on it either allow or deny access to certain resources or operations.
#### Simple access strategy example:
```js
var Public = new Sealious.ChipTypes.AccessStrategy({
name: "public",
checker_function: function(context){
return true;
}
});
```
This access strategy accepts any context.
#### AccessStrategy: Constructor
The `AccessStrategy` constructor takes one argument, which is an object with attributes:
* `name` - string, **required**. The name of the access strategy - it has to be a string unique amongst any other access strategies in your application.
* `checker_function` - function, **required**. It's a function that takes a context instance as an argument and implements the logic of the access strategy. Its return values can be:
- `boolean` - `true` for granting the access and `false` for denying.
- a `Promise` - that resolves when the access is granted and rejects otherwise. Use promises only when the decision depends on a result of an asynchronous function.
* `item_sensitive` - boolean, defaults to `false`. If set to `true`, the `checker_function` is provided with a second argument, which contains an object representing the resource being requested.
#### A more advanced example
```js
var _is_number = /^[0-9]/;
new Sealious.ChipTypes.AccessStrategy({
name: "id_starts_with_digit",
checker_function: function(context, item){
return new Promise(function(resolve, reject){
if(_is_number.test(item.id)){
resolve("id ok!");
}else{
reject("bad id");
}
});
},
item_sensitive: true,
});
```
It's a slightly more complex access strategy, that allows access only if given resource's id starts with a digit. Note that it was not necessary to use a Promise in the above `checker_function`, but it was included for example's sake.
TODO: example of a checker_function that uses contexts.
TODO: example of how ResourceTypes use access strategies.
### Channel
A channel's responsibility is to take any input it wants to (keyboard, http request, open socket, anything) and translate it to Sealious resource method calls.
Considering it's structure, it's the most flexible of all chip types.
You don't need a channel to create an application in Sealious, as Sealious gives you a programmatic API for CRUD operations on all of the resources (see ResourceManager), though channels are good for abstracting out the workings of an external API (such as REST, SMTP, XMPP etc.) and turning it into a reusable plugin.
The only method that Sealious will invoke on a channel is the optional `start` method, called on `Sealious.start()`.
#### Existing channels
Some noteworthy plugins that contain useful channels are:
* [sealious-www-server](https://github.com/Sealious/sealious-www-server) - it can also automatically generate high-quality REST API.
#### Channel: Constructor
```js
var Sealious = require("sealious");
var CliChannel = new Sealious.ChipTypes.Channel("cli");
```
The constructor takes only one argument, which is a string that represents the channel's name and has to be unique amongst all other channels.
The constructor returns an object (which has a Chip as its prototype). This object can be extended with any desired methods.
#### Simple Channel example: command-line-interface
We're going to create a simple channel, that reads from standard input and listens for a simple command:
> `list [resource_type_name]` - lists all resources of given type
We'll be using the `readline` module, which is built-in into node.
Consider following code:
```js
var Sealious = require("sealious");
var readline = require("readline");
var CliChannel = new Sealious.ChipTypes.Channel("cli");
CliChannel.start = function(){
console.log("Welcome to Sealious CLI Channel. Your wish is my command.")
console.log("Please enter your wish:");
var rl = readline.createInterface({
input: process.stdin,
});
function process_line(line){
var words = line.split(" ");
switch(words[0]){
case "list":
var resource_type_name = words[1];
var context = new Sealious.Context();
Sealious.ResourceManager.list_by_type(context, resource_type_name)
.then(function(list){
console.log(list);
})
break;
}
}
rl.on("line", process_line);
}
```
The main functionality of the channel is contained within the line:
```js
Sealious.ResourceManager.list_by_type(context, resource_type_name)
```
`ResourceManager.list_by_type` is an asynchronous method that returns a Promise that resolves to an array of objects representing all of the resources of a given type that are accessible in presence of a given `context`. We're using a simple, empty context, that can be thought of as representing an unauthorized user. You can read more about contexts [here](# context)
### Datastore
Datastores are chips responsible for all the data storage for your application. Currently Sealious supports only one active datastore at a time, but it's subject to change in future versions.
#### Datastore: Constructor
```
var my_datastore = new Sealious.ChipTypes.Datastore("my_datastore");
```
In above code snippet the `my_datastore` variable contains a Datastore object, that needs to be extended with methods which signatures are described below.
IMPORTANT! All these methods need to return a promise that resolves on success.
* `find` - Retrieves documents from datastore. Its promise has to resolve with an array of documents (objects). A function with signature
```
find : function(collection_name: String, query: Object, options: Object, output_options: Object) => Object
```
where:
* `collection_name` (string) - the name of the desired collection.
* `query` (object) - an object containing db-query in [MongoDB query syntax](http://docs.mongodb.org/manual/tutorial/query-documents/)
* `options` - optional argument. In MongoDB datastore it is passed as `projection` argument to `find` method. Currently no core Sealious code uses that parameter
* `output_options` (object) - allows to further filter or sort the query result. It can contain the following properties:
* `sort` (object) - uses [MongoDB Sort syntax](http://docs.mongodb.org/manual/reference/method/cursor.sort/). Allows to sort the query results using any amount of attributes (fields);
* `skip` (number) - how many documents from the beginning to omit (analogous to the first argument in SQL's "LIMIT" statement)
* `amount` (number) - how many documents to return at most (analogous to to the second argument in SQL's "LIMIT" statement)
* `insert` - Inserts a document to a datastore. **Resolves with the inserted document.** A function with signature
```
insert: function(collection_name: String, to_insert: Object, options: Object) => void
```
where:
* `collection_name` (string) - the name of the desired collection
* `to_insert` (object) - an object containing key-value pairs describing what to insert
* `options` (object) - currently not used
* `update` - Updates a document in datastore. A function with signature
```
update: function(collection_name: String, query: Object, new_value: Object) => void
```
where:
* `collection_name` (string) - the name of the desired collection
* `query` (object) - datastore query, which defines which document to update. Uses [MongoDB find query syntax](http://docs.mongodb.org/manual/reference/method/db.collection.find/)
* `new_value` (object) - what changes to apply to the document. Uses [MongoDB update syntax](http://docs.mongodb.org/manual/reference/method/db.collection.update/# example-update-specific-fields)
* `remove` - removes a specified document from the datastore. A function with signature
```
remove : function(collection_name: String, query: Object, just_one: Boolean) => void
```
where:
* `collection_name` (string) - the name of the desired collection
* `query` (object) - datastore query, which defines which document to remove. Uses [MongoDB find query syntax](http://docs.mongodb.org/manual/reference/method/db.collection.find/)
* `just_one` (boolean) - if set to true, datastore has to remove only one element matching the `query`. It might need to be removed in future versions.
#### Built-in datastore methods
As all [chips](https://github.com/Sealious/Sealious#structure), initiated datastores have two default methods:
* `start` - takes no arguments and is meant to be called automatically by Sealious. Usually of no concern for a developer.
* `test` - perfoms unit tests on the datastore.
#### Multiple Datastores
Because of the fact that Sealious currently supports only one active datastore at a time, you have the ability to manually select which one it is. You can do so by invoking
```js
Sealious.ConfigManager.set_config("datastore_chip_name", "my_datastore")
```
before calling `Sealious.start()`;
There's no need to specify which datastore to use if there's only one datastore available.
#### Example Datastore
We've created a simple file-based datastore for demonstratory purposes:
> [Sealious-datastore-file](https://github.com/Sealious/sealious-datastore-file)
It's not the most efficient one (for any real-life applications the currently default datastore-mongo is recommended), but it highlights all the necessary inner workings of a Datastore, so it makes a good starting point if you want to create your own Datastore.
### Field-type
Each "field" in a [ResourceType](#resource-type) must be assigned a field-*type*.
Field-types describe which values can and which cannot be assigned to a field.
Field-type's behaviour can be adjusted using field-type parameters.
A field-type can accept or reject a value, with appropriate error message.
It's a field-type's responsibility to describe how to store it's values in a datatore.
Some field-types that come bundled with Sealious:
* text - for storing strings of chars.
* email - like text, but accepts only valid email addresses as values
* int - for storing integer numbers
* float - for storing real numbers
* file - for storing managed user-submitted files
* reference - for storing a reference to a resource. This field-type can be adjusted to only accept references to certain resource types.
You can find out more about built-in field-types and other chips in the "Chips that come bundled with Sealious" section.
#### Creating a field-type
-Field types are a little bit different from other chips, as they are to be instantiated multiple times for different fields in multiple resource types. This means that:
- * field-types are never *started* - they just contain some logic that Sealious uses when validating user input and encoding/decoding data to/from datastores.
- * methods of a field-type reside in its *prototype* (as technically speaking field-types are constructor functions), as you can see in the example below
+Field types are a little bit different from other chips, as they are to be instantiated multiple times for different fields in multiple resource types.
##### A simple Field-Type example
Let's review a simple code sample:
```js
var Sealious = require("sealious");
var Promise = require("bluebird");
var Color = require("color");
-var field_type_color = new Sealious.ChipTypes.FieldType("color");
-
-field_type_color.prototype.isProperValue = function(context, new_value){
- try{
- Color(value_in_code.toLowerCase());
- } catch(e){
- return Promise.reject("Value `" + value_in_code + "` could not be parsed as a color.");
+var field_type_color = new Sealious.ChipTypes.FieldType({
+ name: "color",
+ get_description: fnction(context, params){
+ return "Accepts colors, in various formats - rgb, hex, hsl, rgba, and html color name. Example correct values: `#ff0000`, `red`, `rgba(255, 0, 0, 1)`, `hsl(0, 100%, 50%)`."
+ },
+ is_proper_value: function(context, new_value){
+ try{
+ Color(value_in_code.toLowerCase());
+ } catch(e){
+ return Promise.reject("Value `" + value_in_code + "` could not be parsed as a color.");
+ }
+ return true;
+ },
+ encode: function(context, new_value){
+ var color = Color(value_in_code);
+ return Promise.resolve(color.hexString())
}
- return true;
-}
-
-field_type_color.prototype.encode = function(context, new_value){
- var color = Color(value_in_code);
- return Promise.resolve(color.hexString())
-}
+});
```
-This is a simple field-type that accepts color values in various notations (html color names, hex, rgba, hsl...). It will reject any value that does not name a color.
+The above is a simple field-type that accepts color values in various notations (html color names, hex, rgba, hsl...). It will reject any value that does not name a color.
-This field-type uses the very useful [color package](https://www.npmjs.com/package/color).
+This field-type uses the very useful [color](https://www.npmjs.com/package/color) package.
-What's important to note here is the `encode` method - it takes any value already validated by `isProperValue` and converts it to hex - that way all the color values in the database are uniform and easily searchable.
+What's important to note here is the `encode` method - it takes any value already validated by `is_proper_value` and converts it to hex - that way all the color values in the database are uniform and easily searchable.
#### Field-type methods and attributes
##### The constructor
To create a field-type, call the FieldType constructor function:
+```
+Sealious.ChipTypes.FieldType: (declaration: FieldTypeDeclaration)
+```
+
+Usage:
+
```js
-var my_field_type = new Sealious.ChipTypes.FieldType("my_field_type");
+new Sealiuos.ChipTypes.FieldType({
+ //...
+})
```
-the return value of the constructor function is itself a function, whose `prototype` we're interested in extending.
-##### isProperValue
+##### FieldTypeDeclaration
```
-my_field_type.prototype.isProperValue:
- (context: Context, new_value : any, old_value: any) => Promise|Boolean
+type fieldTypeDeclaration: {
+ get_description?: (
+ context: Context,
+ params: Object
+ ) => String|FieldTypeDescription,
+ is_proper_value?: (
+ accept: ()=>void,
+ reject: (error_message: String)=>void,
+ context: Context,
+ params: Object,
+ new_value: Any,
+ old_value: Any
+ ) => void,
+ encode?: (context: Context, params: Object, value_in_code: Any),
+ decode?: (context: Context, params: Object, value_in_database: Any)
+}
```
-This method should either return a boolean value (`true` for valid values and `false` for invalid), or a [Promise](#accessstrategy-constructor) that `resolve`s for correct values and `reject`s for incorrect ones.
-Simply returning `false` is discouraged. It's better to `Promise.reject` with an error message (a string). The error message is then supposed to be shown to user as a part of the validation error message. Example:
+##### is_proper_value
-```js
-my_field_type.isProperValue = function(context, new_value){
- if(new_value=="good"){
- return true;
- }else{
- return Promise.reject("I will only accept `good` as value for this field.");
- }
-}
+```
+is_proper_value: (
+ accept: ()=>void,
+ reject: (error_message: String)=>void,
+ context: Context,
+ params: Object,
+ new_value: Any,
+ old_value: Any
+) => void,
```
+This method should check if the `new_value` variable contains a value that is correct for the field-type. If the value is correct, the method should call `accept`, otherwise it should call `reject`, passing the error message.
+
Specifying this method is **optional**. If this method is not defined in a field-type, a default one is used - one that accepts any value.
-It takes the following arguments:
- * `context` - a Context object representing the context in which the value was submitted. The field-type may or may not take context into consideration.
- * `new_value` - can be of any type. Represents the value to be checked. Usually directly represents user input.
- * `old_value` - represents the value previously residing in in a field that this field-type is assigned to. This argument can be used e. g. for creating a field type that accepts only values that are higher than the current value.
+A simple example of `is_proper_value` method:
+
+```js
+new Sealious.ChipTypes.FieldTypes({
+ name: "only_event_numbers",
+ is_proper_value: function(accept, reject, context, params, new_value){
+ if(new_value%2==0){
+ accept();
+ }else{
+ reject("Only even numbers are accepted.");
+ }
+ }
+})
+```
+
+This method wil be given the following arguments:
+ * `accept: ()=>void` - call it if the `new_value` is a correct value
+ * `reject: (error_message: String)=>void` - call it if the `new_value` is not a correct value.
+ * `context: Context` - a Context object representing the context in which the value was submitted. The field-type may or may not take context into consideration.
+ * `params: Object` - an object representing the params given to the FieldDeclaration which referenced our current field-type
+ * `new_value: Any` - Represents the value to be checked. Usually directly represents user input.
+ * `old_value: Any` - represents the value previously residing in in a field that this field-type is assigned to. This argument can be used e. g. for creating a field type that accepts only values that are higher than the current value.
+
**Important!** For performance reasons, this argument is automatically set to `undefined`, unless Sealious is specifically instructed to provide this field-type with previous values. See `old_value_sensitive` section below for more details
##### encode
```
-my_field_type.prototype.encode:
- (context: Context, new_value: Any, old_value: Any) => Promise<Any>|Any
+my_field_type.prototype.encode: (
+ context: Context,
+ params: Object,
+ new_value: Any,
+ old_value: Any
+) => Promise<Any>|Any
```
This method takes a field value (usually coming from user input) and encodes it in something that the datastore can understand. There's no set restrictions on how the encoding process works. What this method returns will be stored in the datastore and passed on to `decode` when reading the resource's contents.
Specifying this method is **optional**. If this method is not defined in a field-type, a default one is used - one that returns `new_value` unchanged.
It takes the following arguments:
- * `context` - a Context object representing the context in which the value was submitted. The field-type may or may not take context into consideration.
- * `new_value` - can be of any type. Represents the value to be encoded. Usually directly represents user input.
- * `old_value` - represents the value previously residing in in a field that this field-type is assigned to.
+ * `context: Context` - a Context object representing the context in which the value was submitted. The field-type may or may not take context into consideration.
+ * `params: Object` - an object representing the params passed to the field declaration referencing this field type
+ * `new_value: Any` - can be of any type. Represents the value to be encoded. Usually directly represents user input.
+ * `old_value: Any` - represents the value previously residing in in a field that this field-type is assigned to.
+
**Important!** For performance reasons, this argument is automatically set to `undefined`, unless Sealious is specifically instructed to provide this field-type with previous values. See `old_value_sensitive` section below for more details
##### decode
```
-my_field_type.prototype.decode:
- (context: Context, value_in_datastore: Any) => Promise<Any>|Any
+my_field_type.prototype.decode: (
+ context: Context,
+ params: Object,
+ value_in_datastore: Any
+) => Promise<Any>|Any
```
This method is used to transform a value stored in a datastore(encoded by calling the `encode` method of the field-type) into something more readable or user-friendly. It's return value is usually what the users of the API will see. It can be thought of as the reverse of `encode` function, but that doesn't have to be the case.
In most cases the return value of this method should be the same as the value passed to the `encode` method for that particular field/value combination.
Specifying this method is **optional**. If this method is not defined in a field-type, a default one is used - one that returns `value_in_datstore` unchanged.
It takes the following arguments:
* `context` - a `Context` object representing the context in which the value is read. The field-type may or may not take context into consideration.
+ * `params: Object` - an object representing the params passed to the field declaration referencing this field type
* `value_in_datastore` - a raw value that the datastore returned. Encoded by calling the field-type's `encode` method.
##### old_value_sensitive
```
-my_field_type.prototype.old_value_sensitive: bool
+old_value_sensitive_methods: Boolean|{
+ is_proper_value: Boolean,
+ encode: Boolean
+}
```
Set to `false` for each field-type by default, for performance reasons.
-When it's set to true, Sealious will provide the `isProperValue` and `encode` methods with the current value of the requested/modified field by passing it as `old_value` argument.
+When it's set to `true`, Sealious will provide the `is_proper_value` and `encode` methods with the current value of the requested/modified field by passing it as `old_value` argument.
#### Field-type parameters
Each field has to have a field-type assigned.
Optionally, a field declaration can contain parameters that will be accessible from within the fiel-type methods.
These parameters can affect which values for the field are considered correct, how the values are encoded, etc.
##### Passing parameters to field-type instance
Parameters are passed from the field declaration, like so:
```js
//a single field declaration in ResourceType constructor:
{
name: "article_content",
type: "text",
params: {
strip_html: true
}
}
```
Note the `params` attribute.
Text entered in the field described by the above snippet will have any html tags stripped on user submission.
##### Accessing field-type parameters
Parameters are accessible as `this.params` in every field-type method, like so:
```js
-my_field_type.isProperValue = function(context, new_value){
+my_field_type.is_proper_value = function(context, new_value){
if(this.params.max_length){
if(new_value.length>this.params.max_length){
return false;
}
}else{
return true;
}
}
```
### Resource-type
Every time a user interacts with a Sealious application, they interact with resources. A Resource in Sealious can be thought of as an equivalent of a row in a SQL database table. A Resource-type would be the columns for said table - a list of fields, each with its name and type.
A Resource-type is construted based on a Resource-type description.
#### Creating a resource-type
Creating a resource-type is very straightforward - you only have to provide the constructor with a proper resource-type description.
##### A simple resource-type example
```js
var Sealious = require("sealious");
new Sealious.ChipTypes.ResourceType({
name: "person",
fields: [
{name: "first-name", type: "text", required: true},
{name: "age", type: "int"}
]
})
```
There's not much to analyze here, except for the syntax of the resource-type description, which is discussed below.
#### Resource-type description syntax
Every resource type is described by a hashmap:
```js
{
name: String,
- fields: Array<FieldDescription>,
+ fields: Array<FieldDeclaration>,
access_strategy?: AccessStrategyDescription
}
```
* `name`, **required** - the name of the resource-type. It becomes the name of the [chip](https://github.com/Sealious/Sealious/blob/dev/README.md#structure) representing the resource type, as well. It has to be unique amongst all other resource-types.
* `fields`, **required** - an array of field descriptions. You can read about field description syntax below.
* `access_strategy`, optional. A hashmap or string compatible with access strategy description syntax, described below. **Defaults to `public`**.
-#### Field description syntax
+#### FieldDeclaration
A field-type description is a hashmap, as well. It looks like this:
```js
{
name: String,
type: FieldTypeName,
human_readable_name?: String,
params?: Object
}
```
* `name`, **required** - a string representing the machine-readable name for the field. Should be short. No spaces allowed. All lower-case letters, the `_` and `-` symbols are allowed.
* `human_readable_name`, optional - a string representing a human-readable version of the field's name. No restrictions on what is and what is not allowed here. **When not specified, the value of 'name' attribute is used instead**.
* `type`, **required** - a string representing a resource-type name that is already registred in your Sealious application.
* `params`, optional - a hashmap of parameters that will be passed to the field-type. These parameters are also a part of the field's signature. **Defaults to `{}`.**
#### Resource-type methods and attributes
##### The constructor
## Plugins
Plugins are npm modules that can be required and used within a Sealious application. Usually a plugin just registers some new [chips](https://github.com/Sealious/Sealious/blob/dev/README.md#structure) in Sealious' ChipManager.
### Creating a plugin
In order for Sealious to recognize an npm module as a plugin, the plugin has to contain a `"sealious-plugin"` keyword in it's `package.json`.
Example `package.json` content:
```json
{
"name": "sealious-cli-channel",
"version": "0.1.0",
"description": "",
"main": "index.js",
"keywords": [
"sealious-plugin"
],
/* other usual package.json fields here */
}
```
### Installing an existing plugin
In order for Sealious to detect a plugin, the plugin has to be installed in your application's `node_modules` directory and it has to be present in your application's `package.json`'s `dependencies` attribute. It's usually achievable by running `npm install [plugin-name]` in your application's directory.
## Chips that come bundled with Sealious
diff --git a/lib/base-chips/_base-chips.js b/lib/base-chips/_base-chips.js
index c2bfa570..89735ca6 100644
--- a/lib/base-chips/_base-chips.js
+++ b/lib/base-chips/_base-chips.js
@@ -1,28 +1,26 @@
-
-
/*
var fs = require("fs");
var path = require("path");
fs.readdirSync(__dirname).forEach(function(filename){
if(filename[0]!="_"){
require("./" + filename);
}
})
*/
require("./access_strategy.id_starts_with_digit.js");
require("./access_strategy.noone.js");
require("./access_strategy.public.js");
require("./access_strategy.just_owner.js");
require("./field_type.date.js");
require("./field_type.datetime.js");
+require("./field_type.boolean.js");
require("./field_type.email.js");
-require("./field_type.file.js");
-require("./field_type.float.js");
require("./field_type.int.js");
-require("./field_type.reference.js");
+require("./field_type.float.js");
require("./field_type.text.js");
-require("./field_type.boolean.js");
-require("./resource_type.user.js");
+require("./field_type.file.js");
+require("./field_type.reference.js");
+require("./resource_type.user.js");
\ No newline at end of file
diff --git a/lib/base-chips/access_strategy.id_starts_with_digit.js b/lib/base-chips/access_strategy.id_starts_with_digit.js
index 50b368d1..dccf4c9f 100644
--- a/lib/base-chips/access_strategy.id_starts_with_digit.js
+++ b/lib/base-chips/access_strategy.id_starts_with_digit.js
@@ -1,18 +1,18 @@
-var Sealious = require("../main.js");
+var Sealious = require("sealious");
var Promise = require("bluebird");
var is_number = /^[0-9]/;
var IDStartsWithDigit = new Sealious.ChipTypes.AccessStrategy({
name: "id_starts_with_digit",
checker_function: function(context, item){
return new Promise(function(resolve, reject){
- if(is_number.test(item.id)){
- resolve("id ok!");
- }else{
+ if (is_number.test(item.id)) {
+ resolve("id ok!");
+ } else {
reject("bad id");
}
});
},
item_sensitive: true,
});
\ No newline at end of file
diff --git a/lib/base-chips/access_strategy.just_owner.js b/lib/base-chips/access_strategy.just_owner.js
index f6e53a09..94f9c77f 100644
--- a/lib/base-chips/access_strategy.just_owner.js
+++ b/lib/base-chips/access_strategy.just_owner.js
@@ -1,14 +1,14 @@
var Sealious = require("../main.js");
var Promise = require("bluebird");
var JustOwner = new Sealious.ChipTypes.AccessStrategy({
- name: "just_owner",
- checker_function: function(context, item) {
- if (context.get("user_id") === item.created_context.user_id) {
- return Promise.resolve();
- } else {
- return Promise.reject("Only the owner of this resource can perform this operation on this item.");
- };
- },
- item_sensitive: true
+ name: "just_owner",
+ checker_function: function(context, item){
+ if (context.get("user_id") === item.created_context.user_id) {
+ return Promise.resolve();
+ } else {
+ return Promise.reject("Only the owner of this resource can perform this operation on this item.");
+ };
+ },
+ item_sensitive: true
});
\ No newline at end of file
diff --git a/lib/base-chips/field_type.boolean.js b/lib/base-chips/field_type.boolean.js
index 6e4f7187..6de57264 100644
--- a/lib/base-chips/field_type.boolean.js
+++ b/lib/base-chips/field_type.boolean.js
@@ -1,32 +1,35 @@
var Sealious = require("../main.js");
var Promise = require("bluebird");
-var field_type_boolean = new Sealious.ChipTypes.FieldType("boolean");
-
-field_type_boolean.prototype.isProperValue = function(context, value) {
- if(typeof value == "boolean"){
- return true;
- }else if(value==1 || value==0){
- return true;
- }else if(typeof value=="string" && (value.toLowerCase()=="true" || value.toLowerCase()=="false")){
- return true;
- }else{
- return false
- }
-}
-
-field_type_boolean.prototype.encode = function(value) {
- if(typeof value == "boolean"){
- return value;
- }else if(value==1){
- return true;
- }else if(value==0){
- return false;
- }else if(typeof value=="string"){
- if(value.toLowerCase()=="true"){
+var field_type_boolean = new Sealious.ChipTypes.FieldType({
+ name: "boolean",
+ get_description: function(context, params){
+ return "Boolean value. True or false. Can be a string: \"true\" or \"false\".";
+ },
+ is_proper_value: function(accept, reject, context, value){
+ if (typeof value == "boolean") {
+ accept();
+ } else if (value == 1 || value == 0) {
+ accept();
+ } else if (typeof value == "string" && (value.toLowerCase() == "true" || value.toLowerCase() == "false")) {
+ accept();
+ } else {
+ reject("Value `" + value + "`" + " is not boolean format.");
+ }
+ },
+ encode: function(value){
+ if (typeof value == "boolean") {
+ return value;
+ } else if (value == 1) {
return true;
- }else if(value.toLowerCase()=="false"){
- return false
+ } else if (value == 0) {
+ return false;
+ } else if (typeof value == "string") {
+ if (value.toLowerCase() == "true") {
+ return true;
+ } else if (value.toLowerCase() == "false") {
+ return false
+ }
}
}
-}
+});
\ No newline at end of file
diff --git a/lib/base-chips/field_type.date.js b/lib/base-chips/field_type.date.js
index 284a971b..497bc9f7 100644
--- a/lib/base-chips/field_type.date.js
+++ b/lib/base-chips/field_type.date.js
@@ -1,27 +1,24 @@
var Sealious = require("../main.js");
-
var Promise = require("bluebird");
-var field_type_date = new Sealious.ChipTypes.FieldType("date");
-
-field_type_date.prototype.isProperValue = function(context, date) {
- return new Promise(function(resolve, reject) {
-
- var date_in_string = date.toString();
-
- var regex = /^([0-9]{4})-(0?[1-9]|1[0-2])-([0-2]?[0-9]|30|31)$/; //granulation_per_day
+var field_type_date = new Sealious.ChipTypes.FieldType({
+ name: "date",
+ get_description: function(context, params){
+ return "Date standard ISO 8601 (YYYY-MM-DD)";
+ },
+ is_proper_value: function(accept, reject, context, date){
+ var date_in_string = date.toString();
- if (regex.test(date_in_string) === false || Date.parse(date_in_string) === NaN) {
- reject("Value `"+date+"`" + " is not date calendar format. Expected value standard IS0 8601 (YYYY-MM-DD)");
- } else {
- resolve();
- }
- })
-}
+ var regex = /^([0-9]{4})-(0?[1-9]|1[0-2])-([0-2]?[0-9]|30|31)$/; //granulation_per_day
-field_type_date.prototype.encode = function(date) {
- return new Promise(function(resolve, reject) {
- var date_in_string = date.toString();
- resolve(Date.parse(date_in_string));
- })
-}
\ No newline at end of file
+ if (regex.test(date_in_string) === false || Date.parse(date_in_string) === NaN) {
+ reject("Value `" + date + "`" + " is not date calendar format. Expected value standard IS0 8601 (YYYY-MM-DD)");
+ } else {
+ accept();
+ }
+ },
+ encode: function(value_in_code){
+ var date_in_string = date.toString();
+ return Date.parse(date_in_string);
+ }
+});
\ No newline at end of file
diff --git a/lib/base-chips/field_type.datetime.js b/lib/base-chips/field_type.datetime.js
index f01f8c18..bad171ab 100644
--- a/lib/base-chips/field_type.datetime.js
+++ b/lib/base-chips/field_type.datetime.js
@@ -1,24 +1,20 @@
var Sealious = require("../main.js");
-
var Promise = require("bluebird");
-
-var field_type_datetime = new Sealious.ChipTypes.FieldType("datetime");
-
-field_type_datetime.prototype.isProperValue = function(context, datetime) {
- return new Promise(function(resolve, reject) {
-
- if (isNaN(datetime) === true || parseInt(datetime) === NaN) {
- reject("Value `" + datetime + "`" + " is not datetime format. Only timestamps are accepted.");
- } else {
- resolve();
- }
- })
-}
-
-field_type_datetime.prototype.encode = function(datetime) {
- return new Promise(function(resolve, reject) {
- var parsed_datetime = parseInt(datetime);
- resolve(parsed_datetime);
- })
-}
\ No newline at end of file
+var field_type_datetime = new Sealious.ChipTypes.FieldType({
+ name: "datetime",
+ get_description: function(context, params){
+ return "Timestamp - amount of miliseconds since epoch."
+ },
+ is_proper_value: function(accept, reject, context, datetime){
+ if (isNaN(datetime) === true || parseInt(datetime) === NaN) {
+ reject("Value `" + datetime + "`" + " is not datetime format. Only timestamps are accepted.");
+ } else {
+ accept();
+ }
+ },
+ encode: function(datetime){
+ var parsed_datetime = parseInt(datetime);
+ return parsed_datetime;
+ }
+});
\ No newline at end of file
diff --git a/lib/base-chips/field_type.email.js b/lib/base-chips/field_type.email.js
index 4dba2d36..5c794f6d 100644
--- a/lib/base-chips/field_type.email.js
+++ b/lib/base-chips/field_type.email.js
@@ -1,20 +1,20 @@
var Sealious = require("../main.js");
-
var Promise = require("bluebird");
-var field_type_email = new Sealious.ChipTypes.FieldType("email");
-
-field_type_email.prototype.isProperValue = function(context, value){
-
- return new Promise(function(resolve, reject){
+var field_type_email = new Sealious.ChipTypes.FieldType({
+ name: "email",
+ get_description: function(context, params){
+ return "Email address, like something@something.sth"
+ },
+ is_proper_value: function(accept, reject, context, value){
var address = value;
var regex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
- if(!regex.test(address)){
+ if (!regex.test(address)) {
reject(address + " is not valid e-mail address.");
} else {
- resolve();
+ accept();
}
- })
-}
\ No newline at end of file
+ }
+});
\ No newline at end of file
diff --git a/lib/base-chips/field_type.file.js b/lib/base-chips/field_type.file.js
index 03681a9e..14de2b74 100644
--- a/lib/base-chips/field_type.file.js
+++ b/lib/base-chips/field_type.file.js
@@ -1,46 +1,44 @@
var Sealious = require("../main.js");
var Promise = require("bluebird");
-var FieldFileType = new Sealious.ChipTypes.FieldType("file");
-
-FieldFileType.prototype.handles_large_data = true;
-
-FieldFileType.prototype.isProperValue = function(context, value){
- if(value===undefined){
- return undefined;
- }
- if((value instanceof Sealious.File) || (value.filename!==undefined && value.data instanceof Buffer)){
- return Promise.resolve();
- }else{
- var type;
- if(value instanceof Array){
- type = "<Array>. If you want to upload multiple files, use array field types.";
- }else{
- type = typeof data;
- }
- return Promise.reject("Wrong file data format. Shoudl be <Buffer>, but received " + type);
- }
-}
-
-FieldFileType.prototype.encode = function(value_in_code){
- if(value_in_code){
- return Sealious.Dispatcher.files.save_file(value_in_code);
- }else{
- return null;
- }
-}
-
-
-FieldFileType.prototype.decode = function(context, value_in_database){
- if(value_in_database){
- return Promise.resolve(new Sealious.File.Reference(value_in_database.id, value_in_database.filename));
- }else{
- if(this.params.no_file_value){
- return this.params.no_file_value;
- }else{
+var FieldFileType = new Sealious.ChipTypes.FieldType({
+ name: "file",
+ handles_large_data: true,
+ is_proper_value: function(accept, reject, context, value){
+ if (value === undefined) {
return undefined;
}
+ if ((value instanceof Sealious.File) || (value.filename !== undefined && value.data instanceof Buffer)) {
+ accept();
+ } else {
+ var type;
+ if (value instanceof Array) {
+ type = "<Array>. If you want to upload multiple files, use array field types.";
+ } else {
+ type = typeof data;
+ }
+ reject("Wrong file data format. Shoudl be <Buffer>, but received " + type);
+ }
+ },
+ encode: function(value_in_code){
+ if (value_in_code) {
+ return Sealious.Dispatcher.files.save_file(value_in_code);
+ } else {
+ return null;
+ }
+ },
+ decode: function(context, value_in_database){
+ if (value_in_database) {
+ return Promise.resolve(new Sealious.File.Reference(value_in_database.id, value_in_database.filename));
+ } else {
+ if (this.params.no_file_value) {
+ return this.params.no_file_value;
+ } else {
+ return undefined;
+ }
+ }
+ },
+ decode: {
+ uses_context: true
}
-}
-
-FieldFileType.prototype.decode.uses_context = true;
\ No newline at end of file
+});
\ No newline at end of file
diff --git a/lib/base-chips/field_type.float.js b/lib/base-chips/field_type.float.js
index 9eae062e..b1deb223 100644
--- a/lib/base-chips/field_type.float.js
+++ b/lib/base-chips/field_type.float.js
@@ -1,19 +1,21 @@
var Sealious = require("../main.js");
var Promise = require("bluebird");
-var field_type_float = new Sealious.ChipTypes.FieldType("float");
-
-field_type_float.prototype.isProperValue = function(context, number) {
- var test = parseFloat(number);
- if (test === null || test === NaN || isNaN(number) === true) {
- return new Sealious.Errors.ValidationError("Value `" + number + "` is not a float number format.");
- } else {
- return true;
- }
-}
-
-field_type_float.prototype.encode = function(number) {
- return new Promise(function(resolve, reject) {
- resolve(parseFloat(number));
- })
-}
+var field_type_float = new Sealious.ChipTypes.FieldType({
+ name: "float",
+ get_description: function(context, params){
+ return "Float number."
+ },
+ is_proper_value: function(accept, reject, context, number){
+ var test = parseFloat(number);
+ if (test === null || test === NaN || isNaN(number) === true) {
+ reject("Value `" + number + "` is not a float number format.");
+ } else {
+ accept();
+ }
+ },
+ encode: function(number){
+ var parsed_float = parseFloat(number);
+ return parsed_float;
+ }
+});
\ No newline at end of file
diff --git a/lib/base-chips/field_type.int.js b/lib/base-chips/field_type.int.js
index 2b0e6866..12c2f7f8 100644
--- a/lib/base-chips/field_type.int.js
+++ b/lib/base-chips/field_type.int.js
@@ -1,8 +1,21 @@
var Sealious = require("../main.js");
var Promise = require("bluebird");
-field_type_int = new Sealious.ChipTypes.FieldType("int");
-
-field_type_int.prototype.encode = function(value_in_code){
- return Promise.resolve(parseInt(value_in_code));
-}
\ No newline at end of file
+var field_type_int = new Sealious.ChipTypes.FieldType({
+ name: "int",
+ get_description: function(context, params){
+ return "An integer number."
+ },
+ is_proper_value: function(accept, reject, context, params, new_value){
+ var test = parseInt(new_value);
+ if (test === null || test === NaN || isNaN(new_value) === true) {
+ reject("Value `" + new_value + "` is not a int number format.");
+ } else {
+ accept();
+ }
+ },
+ encode: function(context, params, value_in_code){
+ var parsed_int = parseInt(value_in_code);
+ return parsed_int;
+ }
+});
\ No newline at end of file
diff --git a/lib/base-chips/field_type.reference.js b/lib/base-chips/field_type.reference.js
index c20fe8e6..33a81e01 100644
--- a/lib/base-chips/field_type.reference.js
+++ b/lib/base-chips/field_type.reference.js
@@ -1,100 +1,90 @@
var Sealious = require("../main.js");
var Promise = require("bluebird");
var clone = require("clone");
-var field_type_reference = new Sealious.ChipTypes.FieldType("reference");
-
-field_type_reference.prototype.validate_declaration = function(declaration){
- var required_declaration_fields = {
- "name": "string",
- "allowed_types": "array"
- }
- for(var attribute_name in required_declaration_fields){
- if(declaration[attribute_name]===undefined){
- throw new Sealious.Errors.DeveloperError("Missing `" + attribute_name + "` attribute in reference declaration.");
+var field_type_reference = new Sealious.ChipTypes.FieldType({
+ name: "reference",
+ is_proper_declaration: function(declaration){
+ var required_declaration_fields = {
+ "name": "string",
+ "allowed_types": "array"
+ };
+ for (var attribute_name in required_declaration_fields) {
+ if (declaration[attribute_name] === undefined) {
+ throw new Sealious.Errors.DeveloperError("Missing `" + attribute_name + "` attribute in reference declaration.");
+ }
}
- }
- for(var i in declaration.allowed_types){
- var type_name = declaration.allowed_types[i];
- if(!Sealious.ChipManager.chip_exists("resource_type", type_name)){
- throw new Sealious.Errors.DeveloperError("Unknown allowed type in declaration of reference: " + type_name);
+ for (var i in declaration.allowed_types) {
+ var type_name = declaration.allowed_types[i];
+ if (!Sealious.ChipManager.chip_exists("resource_type", type_name)) {
+ throw new Sealious.Errors.DeveloperError("Unknown allowed type in declaration of reference: " + type_name);
+ }
}
- }
-}
+ },
+ is_proper_value: function(accept, reject, context, value){
+ if (typeof value == "object") {
+ //validate object's values as values for new resource
+ var type = value.type;
+ if (type === undefined) {
+ reject("Reference resource type undefined. `type` attribute should be set to one of these values: " + this.params.allowed_types.join(", ") + ".");
+ } else if (this.params.allowed_types.indexOf(type) == -1) {
+ reject("Incorrect reference resource type: `" + type + "`. Allowed resource types for this reference are:" + this.params.allowed_types.join(", ") + ".");
+ } else {
+ var resource_type_object = Sealious.ChipManager.get_chip("resource_type", type);
+ var access_strategy = resource_type_object.get_access_strategy();
-field_type_reference.prototype.isProperValue = function(context, value){
- if(typeof value == "object"){
- //validate object's values as values for new resource
- var type = value.type;
- if(type===undefined){
- return Promise.reject("Reference resource type undefined. `type` attribute should be set to one of these values: " + this.params.allowed_types.join(", ") + ".");
- }else if(this.params.allowed_types.indexOf(type)==-1){
- return Promise.reject("Incorrect reference resource type: `" + type + "`. Allowed resource types for this reference are:" + this.params.allowed_types.join(", ") + ".");
- }else{
- var resource_type_object = Sealious.ChipManager.get_chip("resource_type", type);
- var access_strategy = resource_type_object.get_access_strategy();
-
- return access_strategy.check(context, value.type, value.data)
- .then(function(){
- return resource_type_object.validate_field_values(context, true, value.data);
+ return access_strategy.check(context, value.type, value.data)
+ .then(function(){
+ return resource_type_object.validate_field_values(context, true, value.data);
+ })
+ }
+ } else {
+ //value is uid. Check if it is proper
+ var supposed_resource_id = value;
+ return Sealious.Dispatcher.resources.get_by_id(context, supposed_resource_id)
+ .then(function(resource){
+ if (this.params.allowed_types.indexOf(resource.type) >= 0) {
+ accept(resource);
+ } else {
+ reject("Resource of id `" + supposed_resource_id + "` is not of allowed type. Allowed types are: [" + this.params.allowed_types.join(", ") + "]");
+ }
+ }.bind(this))
+ .catch(function(error){
+ if (error.type == "not_found") {
+ reject(error.status_message);
+ } else {
+ reject(error);
+ }
+ }.bind(this));
+ }
+ },
+ encode: function(context, params, value_in_code){
+ //decide whether to create a new resource (if so, do create it). Resolve with id of referenced resource.
+ if (value_in_code instanceof Object) {
+ return Sealious.Dispatcher.resources.create(context, value_in_code.type, value_in_code.data).then(function(resource){
+ return Promise.resolve(resource.id);
})
+ } else {
+ //assuming the provided id already exists
+ return Promise.resolve(value_in_code);
+ }
+ },
+ get_description: function(context, params){
+ var params_copy = clone(params, false);
+ params_copy.allowed_types = {};
+ for (var i in params.allowed_types) {
+ var type_name = params.allowed_types[i];
+ var type_object = Sealious.ChipManager.get_chip("resource_type", type_name);
+ var type_schema = Sealious.ChipManager.get_chip("resource_type", type_name).get_signature();
+ params_copy.allowed_types[type_name] = type_schema;
+ }
+ return params_copy;
+ },
+ decode: function(context, value_in_db){
+ if (value_in_db == undefined) {
+ return Promise.resolve(undefined);
+ } else {
+ return Sealious.Dispatcher.resources.get_by_id(context, value_in_db);
}
- }else{
- //value is uid. Check if it is proper
- var supposed_resource_id = value;
- return Sealious.Dispatcher.resources.get_by_id(context, supposed_resource_id)
- .then(function(resource){
- if(this.params.allowed_types.indexOf(resource.type)>=0){
- return Promise.resolve(resource);
- }else{
- return Promise.reject("Resource of id `" + supposed_resource_id + "` is not of allowed type. Allowed types are: [" + this.params.allowed_types.join(", ") +"]");
- }
- }.bind(this))
- .catch(function(error){
- if(error.type=="not_found"){
- return Promise.reject(error.status_message);
- }else{
- return Promise.reject(error);
- }
- }.bind(this));
- }
-}
-
-field_type_reference.prototype.isProperValue.has_byproducts = true;
-
-field_type_reference.prototype.encode = function(context, value_in_code){
- //decide whether to create a new resource (if so, do create it). Resolve with id of referenced resource.
- if(value_in_code instanceof Object){
- return Sealious.Dispatcher.resources.create(context, value_in_code.type, value_in_code.data).then(function(resource){
- return Promise.resolve(resource.id);
- })
- }else{
- //assuming the provided id already exists
- return Promise.resolve(value_in_code);
- }
-}
-
-field_type_reference.prototype.encode.uses_context = true;
-
-field_type_reference.prototype.get_params = function(context){
- var params_copy = clone(this.params, false);
- params_copy.allowed_types = {};
- for(var i in this.params.allowed_types){
- var type_name = this.params.allowed_types[i];
- var type_object = Sealious.ChipManager.get_chip("resource_type", type_name);
- var type_schema = Sealious.ChipManager.get_chip("resource_type", type_name).get_signature();
- params_copy.allowed_types[type_name] = type_schema;
- }
- return params_copy;
-
-}
-
-field_type_reference.prototype.decode = function(context, value_in_db){
- if(value_in_db==undefined){
- return Promise.resolve(undefined);
- }else{
- return Sealious.Dispatcher.resources.get_by_id(context, value_in_db);
}
-}
-
-field_type_reference.prototype.decode.uses_context = true;
\ No newline at end of file
+});
\ No newline at end of file
diff --git a/lib/base-chips/field_type.text.js b/lib/base-chips/field_type.text.js
index ff856199..800c6f64 100644
--- a/lib/base-chips/field_type.text.js
+++ b/lib/base-chips/field_type.text.js
@@ -1,36 +1,37 @@
var Sealious = require("../main.js");
var Promise = require("bluebird");
var sanitizeHtml = require("sanitize-html");
-var field_type_text = Sealious.ChipTypes.FieldType("text");
-
-field_type_text.prototype.isProperValue = function(context, value){
- if(this.params==undefined || this.params.max_length===undefined){
- return true;
- }else{
- if(value.length<=this.params.max_length){
- return true;
- }else{
- return Sealious.Errors.ValidationError("Text '" + value + "' has exceeded max length of " + this.params.max_length + " chars.");
+var field_type_text = new Sealious.ChipTypes.FieldType({
+ name: "text",
+ get_description: function(context, params){
+ return "Text with a maximum length " + params.max_length
+ },
+ is_proper_value: function(accept, reject, context, params, new_value){
+ if (params == undefined || params.max_length === undefined) {
+ accept()
+ } else {
+ if (new_value.length <= params.max_length) {
+ accept()
+ } else {
+ reject("Text '" + new_value + "' has exceeded max length of " + params.max_length + " chars.");
+ }
}
- }
-}
-
-field_type_text.prototype.encode = function(value_in_code){
- return new Promise(function(resolve, reject){
- if(this.params && this.params.strip_html === true){
+ },
+ encode: function(context, params, value_in_code){
+ if (params && params.strip_html === true) {
var stripped = sanitizeHtml(value_in_code.toString(), {
- allowedTags: []
+ allowedTags: []
})
- resolve(stripped);
- }else{
- if(value_in_code instanceof Object){
- resolve(JSON.stringify(value_in_code));
- }else if(value_in_code==null){
- resolve("");
- }else{
- resolve(value_in_code.toString());
+ return Promise.resolve(stripped);
+ } else {
+ if (value_in_code instanceof Object) {
+ return Promise.resolve(JSON.stringify(value_in_code));
+ } else if (value_in_code == null) {
+ return Promise.resolve(null);
+ } else {
+ return Promise.resolve(value_in_code.toString());
}
- }
- }.bind(this))
-}
\ No newline at end of file
+ }
+ }
+});
\ No newline at end of file
diff --git a/lib/base-chips/resource_type.user.js b/lib/base-chips/resource_type.user.js
index 9793b1a6..b586ca09 100644
--- a/lib/base-chips/resource_type.user.js
+++ b/lib/base-chips/resource_type.user.js
@@ -1,11 +1,19 @@
var Sealious = require("../main.js");
var user = new Sealious.ChipTypes.ResourceType({
name: "user",
- fields:[
- {name: "username", type: "text", required: true},
- {name: "email", type: "email"},
- {name: "password", type: "text", required: true},
- {name: "status", type: "text"},
- ]
-});
-
+ fields: [{
+ name: "username",
+ type: "text",
+ required: true
+ }, {
+ name: "email",
+ type: "email"
+ }, {
+ name: "password",
+ type: "text",
+ required: true
+ }, {
+ name: "status",
+ type: "text"
+ }, ]
+});
\ No newline at end of file
diff --git a/lib/chip-types/access-strategy.js b/lib/chip-types/access-strategy.js
index c7350efa..1054980f 100644
--- a/lib/chip-types/access-strategy.js
+++ b/lib/chip-types/access-strategy.js
@@ -1,45 +1,45 @@
var Sealious = require("../main.js");
var Promise = require("bluebird");
var Chip = require("./chip.js");
-function AccessStrategy(parent_module_path, declaration){
- if(typeof declaration.name!="string"){
+function AccessStrategy (declaration) {
+ if (typeof declaration.name != "string") {
throw new Sealious.Errors.DeveloperError("Access strategy declaration has an invalid or missing `name` attribute");
}
- Chip.call(this, parent_module_path, true, "access_strategy", declaration.name);
+ Chip.call(this, true, "access_strategy", declaration.name);
this.checker_function = null;
this.item_sensitive = false;
- if(declaration) this._process_declaration(declaration);
+ if (declaration) this._process_declaration(declaration);
}
-AccessStrategy.prototype = new function(){
+AccessStrategy.prototype = new function(){
this._process_declaration = function(declaration){
- this.checker_function = declaration.checker_function===undefined? null : declaration.checker_function;
- if(declaration.item_sensitive!==undefined){
+ this.checker_function = declaration.checker_function === undefined ? null : declaration.checker_function;
+ if (declaration.item_sensitive !== undefined) {
this.item_sensitive = declaration.item_sensitive;
}
}
this.set_checker_function = function(checker_function){
this.checker_function = checker_function;
}
this.check = function(context, item){
var arguments_to_check_function = arguments;
return this.checker_function.apply(this, arguments_to_check_function)
- .then(function(){
- return Promise.resolve(item);
- }).catch(function(error_message){
- if(typeof error_message == "string"){
- return Promise.reject(new Sealious.Errors.BadContext(error_message));
- }else{
- return Promise.reject(error_message);
- }
- });
+ .then(function(){
+ return Promise.resolve(item);
+ }).catch(function(error_message){
+ if (typeof error_message == "string") {
+ return Promise.reject(new Sealious.Errors.BadContext(error_message));
+ } else {
+ return Promise.reject(error_message);
+ }
+ });
}
}
AccessStrategy.type_name = "access_strategy";
module.exports = AccessStrategy;
\ No newline at end of file
diff --git a/lib/chip-types/association-interface.js b/lib/chip-types/association-interface.js
index d8a42f19..22212d72 100644
--- a/lib/chip-types/association-interface.js
+++ b/lib/chip-types/association-interface.js
@@ -1,42 +1,42 @@
/**
* An interface for module developers that makes it easy to create a new association.
* @alias AssociationInterface
* @class
* @static
*/
-var AssociationInterface = new function(){
+var AssociationInterface = new function(){
/**
* Creates an association with given options
* @alias AssociationInterface.create
* @param {object} options
*/
this.create = function(options){
var from_type_name = options.left_type;
var to_type_name = options.right_type;
var bidirectional = options.bidirectional || false;
var from_field_name = options.name_ltr;
var to_field_name = options.name_rtl;
ResourceTypeManager.enforce_correct_type_name(from_type_name);
ResourceTypeManager.enforce_correct_type_name(to_type_name);
var from_type = ResourceTypeManager.getByName(from_type_name);
var to_type = ResourceTypeManager.getByName(to_type_name);
-
+
var from_field_options = {
type: "association",
required: options.left_required || false
};
var field_type_arguments = {
from_type_name: from_type_name,
to_type_name: to_type_name
}
- var from_field = new ResourceTypeField(from_field_name, from_field_options, field_type_arguments);
+ var from_field = new ResourceTypeField(from_field_name, from_field_options, field_type_arguments);
from_type.addField(from_field);
- }
+ }
}
module.exports = AssociationInterface;
\ No newline at end of file
diff --git a/lib/chip-types/channel.js b/lib/chip-types/channel.js
index c45cc353..7ded20ed 100644
--- a/lib/chip-types/channel.js
+++ b/lib/chip-types/channel.js
@@ -1,13 +1,13 @@
var Sealious = require("../main.js");
var chip = require("./chip.js");
-function channel(parent_module_path, name){
+function channel (name) {
this.name = name;
- this.longid = "channel."+name;
+ this.longid = "channel." + name;
this.default_configuration = {};
- Sealious.ChipManager.add_chip("channel", this.name, this, parent_module_path);
+ Sealious.ChipManager.add_chip("channel", this.name, this);
}
-channel.prototype = new chip();
+channel.prototype = new chip();
module.exports = channel;
\ No newline at end of file
diff --git a/lib/chip-types/chip-manager.js b/lib/chip-types/chip-manager.js
index 97d5cd55..bf93bac5 100644
--- a/lib/chip-types/chip-manager.js
+++ b/lib/chip-types/chip-manager.js
@@ -1,131 +1,126 @@
var Sealious = require("../main.js");
var fs = require("fs");
var path = require('path')
var Set = require('Set');
var Promise = require("bluebird");
var ConfigurationManager = require("../config/config-manager.js");
var chip_type_functions = {
- channel: require("./channel.js"),
- resource_type: require("./resource-type.js"),
- field_type: require("./field-type.js"),
- datastore: require("./datastore.js")
+ channel: require("./channel.js"),
+ resource_type: require("./resource-type.js"),
+ field_type: require("./field-type.js"),
+ datastore: require("./datastore.js")
}
chips_by_module = {};
var started_chips_longids = new Set();
var chips = {};
var chip_type_start_order = ["datastore", "field_type", "resource_type", "access_strategy", "channel"];
var registred_chips_longids = new Set();
var ChipManager = new function(){
this.start_chips = function(chip_types_to_start){
Sealious.Logger.info("Starting all chips:");
var promises = [];
- for(var i in chip_type_start_order){
+ for (var i in chip_type_start_order) {
var type = chip_type_start_order[i];
- if(chips[type] && chip_types_to_start.indexOf(type)!==-1){
+ if (chips[type] && chip_types_to_start.indexOf(type) !== -1) {
Sealious.Logger.info(" " + type + ":");
- for(var name in chips[type]){
+ for (var name in chips[type]) {
var chip = chips[type][name];
Sealious.Logger.info("\t \u2713 " + name);
- try{
- if(chip.start){
+ try {
+ if (chip.start) {
var promise = chip.start();
promises.push(promise);
}
- }catch(error){
+ } catch (error) {
Sealious.Logger.error("\t " + "couldn't start `" + name + "`");
return Promise.reject(error);
}
}
}
}
return Promise.all(promises);
}
- this.add_chip = function(type, name, chip, module_path){
- if(chips[type]==undefined){
- chips[type]=[];
+ this.add_chip = function(type, name, chip){
+ if (chips[type] == undefined) {
+ chips[type] = [];
}
- chips[type][name]=chip;
- if(chips_by_module[module_path]==undefined){
- chips_by_module[module_path]=[];
- }
- chips_by_module[module_path].push(chip);
+ chips[type][name] = chip;
}
this.get_all_resource_types = function(){
var names = [];
for (resource_type in chips.resource_type) {
- names.push(resource_type);
+ names.push(resource_type);
}
return names;
}
this.chip_exists = function(type, name){
- if(chips[type] && chips[type][name]){
+ if (chips[type] && chips[type][name]) {
return true;
- }else{
+ } else {
return false;
}
}
this.get_chip = function(type, name){
- try{
+ try {
return chips[type][name]
- }catch(e){
+ } catch (e) {
throw new Sealious.Errors.Error("ChipManager was asked to return a chip of type `" + type + "` and name `" + name + "`, but it was not found");
}
}
this.get_chip_by_longid = function(longid){
var type = longid.split(".")[0];
var name = longid.split(".")[1];
return this.get_chip(type, name);
}
this.chip_is_registred = function(longid){
return this.get_chip_by_longid(longid) != undefined;
}
this.get_chip_amount_by_type = function(type){
- if(chips[type]){
+ if (chips[type]) {
return Object.keys(chips[type]).length;
- }else{
+ } else {
return 0;
}
}
this.get_datastore_chip = function(){
var datastore_chip_amount = this.get_chip_amount_by_type("datastore");
- if(datastore_chip_amount===0){
+ if (datastore_chip_amount === 0) {
throw new Sealious.Errors.Error("Chip manager was requested to return the datastore chip, but no chips of type `datastore` have been registered.")
- }else if(datastore_chip_amount===1){
+ } else if (datastore_chip_amount === 1) {
return chips["datastore"][Object.keys(chips["datastore"])[0]]
- }else{
- var datastore_chip_name = ConfigurationManager.get_config().datastore_chip_name;
- if(datastore_chip_name===undefined){
- throw new Sealious.Errors.Error("Chip manager was requested to return a datastore chip. Multiple chips of type `datastore` have been registered, and no default provided in configuration.")
- }else{
+ } else {
+ var datastore_chip_name = ConfigurationManager.get_config().datastore_chip_name;
+ if (datastore_chip_name === undefined) {
+ throw new Sealious.Errors.Error("Chip manager was requested to return a datastore chip. Multiple chips of type `datastore` have been registered, and no default provided in configuration.")
+ } else {
return this.get_chip("datastore", datastore_chip_name);
- }
+ }
}
}
this.get_chips_by_type = function(chip_type){
return chips[chip_type];
}
}
-module.exports = ChipManager;
-
+module.exports = ChipManager;
\ No newline at end of file
diff --git a/lib/chip-types/chip.js b/lib/chip-types/chip.js
index 3d39d99b..7d71d022 100644
--- a/lib/chip-types/chip.js
+++ b/lib/chip-types/chip.js
@@ -1,54 +1,54 @@
var Promise = require("bluebird");
var ChipManager = null;
-var chip = function(parent_module_path, add_to_chip_manager, type, name){
+var chip = function(add_to_chip_manager, type, name){
this.configuration = {};
Object.defineProperty(this, "default_configuration", {
set: this.apply_default_settings
- })
+ })
this.type = type;
this.name = name;
this.longid = type + "." + name;
- if(add_to_chip_manager){
+ if (add_to_chip_manager) {
var ChipManager = ChipManager || require("./chip-manager.js");
- ChipManager.add_chip(type, name, this, parent_module_path);
+ ChipManager.add_chip(type, name, this);
}
}
chip.prototype = new function(){
this.apply_default_settings = function(default_config){
- for(var i in default_config){
- if(!this.configuration[i]){
- this.configuration[i]=default_config[i];
+ for (var i in default_config) {
+ if (!this.configuration[i]) {
+ this.configuration[i] = default_config[i];
}
}
}
this.configure = function(config){
config = config || {};
this.configuration = config;
- }
+ }
this.start = function(){
//to be overwritten
return Promise.resolve();
}
this.test = function(){
- if(this.test_compatibility){
+ if (this.test_compatibility) {
console.log("Starting compatibility tests for chip: `" + this.name + "`");
this.test_compatibility().then(function(){
- console.log("\t✓ Compatibility test successfull!");
+ console.log("\t✓ Compatibility test successfull!");
})
}
}
}
module.exports = chip;
\ No newline at end of file
diff --git a/lib/chip-types/datastore.js b/lib/chip-types/datastore.js
index 86531e93..ad8ffa2f 100644
--- a/lib/chip-types/datastore.js
+++ b/lib/chip-types/datastore.js
@@ -1,183 +1,239 @@
var assert = require("assert");
var Sealious = require("../main.js");
var Chip = require("./chip.js");
-var Datastore = function(parent_module_path, name){
+var Datastore = function(name){
this.name = name;
- this.longid = "datastore."+name;
+ this.longid = "datastore." + name;
this.default_configuration = {};
- Sealious.ChipManager.add_chip("datastore", this.name, this, parent_module_path);
+ Sealious.ChipManager.add_chip("datastore", this.name, this);
}
-Datastore.is_a_constructor = false;
-
Datastore.prototype = new Chip();
Datastore.prototype.return_not_implemented = function(fn_name){
return function(){
- throw new Sealious.Errors.DeveloperError("Function ", fn_name, "not implemented in ", this.longid, ", aborting.");
+ throw new Sealious.Errors.DeveloperError("Function ", fn_name, "not implemented in ", this.longid, ", aborting.");
}
}
var needs_to_implement = ["find", "insert", "update", "remove"]
-for(var i in needs_to_implement){
+for (var i in needs_to_implement) {
var fn_name = needs_to_implement[i];
Datastore.prototype[fn_name] = Datastore.prototype.return_not_implemented(fn_name)
}
Datastore.prototype.test_compatibility = function(){
var self = this;
this.start();
var rand = Math.random();
- var test_collection_name ="_test";
+ var test_collection_name = "_test";
return Promise.resolve()
- .then(function(){
- //.insert method should respond with the created document
- var to_insert = {value: 1, random: rand};
- return self.insert(test_collection_name, to_insert)
- .then(function(response){
- assert.deepEqual(to_insert, response, ".insert method should respond with the created document");
- return Promise.resolve();
- });
-
- }).then(function(){
- //check if find resolves with an array
-
- return self.find(test_collection_name, {}, {})
- .then(function(documents){
- assert(documents instanceof Array, "datastore." + self.name + ".find should resolve with an array");
- return Promise.resolve();
- });
-
- }).then(function(){
- //check if amount of created documents checks out
- var creates = [
- self.insert(test_collection_name, {value: 2, random: rand}),
- self.insert(test_collection_name, {value: 3, random: rand}),
- self.insert(test_collection_name, {value: 4, random: -rand}),
- ]
-
- var created_so_far = 4;
- return Promise.all(creates)
.then(function(){
- return self.find(test_collection_name, {}, {});
- }).then(function(documents){
- assert(documents.length == created_so_far, "Inserted " + created_so_far + " documents so far, but " + documents.length + " were returned on .find()");
- return Promise.resolve(created_so_far);
- });
-
- }).then(function(created_so_far){
- //check if there is a proper amount of documents with random value set to rand
- var documents_with_rand = created_so_far-1;
- return self.find(test_collection_name, {random: rand}, {})
- .then(function(documents){
- assert(documents.length == documents_with_rand, "Inserted " + documents_with_rand + " documents with `random` set to `" + rand + "` so far, but " + documents.length + " were returned on .find({random: " + rand + "})");
- return Promise.resolve();
- });
-
- }).then(function(){
- //Should store a complex object
- var complex_object = {id: "aseoifaoeina", body: {name: "Anna", surname: "Fontanna"}};
- return self.insert(test_collection_name, complex_object)
- .then(function(response){
- assert.deepEqual(complex_object, response, ".insert with complex object should resolve with that complex object.");
- return self.find(test_collection_name, {id: complex_object.id})
- }).then(function(response){
- assert.deepEqual(complex_object, response[0], ".insert with complex object should store that complex object.");
- return Promise.resolve(complex_object);
- });
-
- }).then(function(complex_object){
- //Should handle dot-notation nested queries
- return self.find(test_collection_name, {"body.name": complex_object.body.name})
- .then(function(response){
- assert.deepEqual(complex_object, response[0], ".find method should handle dot notation queries");
- return Promise.resolve(complex_object);
- });
-
- }).then(function(complex_object){
- return self.find(test_collection_name, {body: {name: complex_object.body.name}})
- .then(function(response){
- assert.deepEqual(complex_object, response[0], ".find method should handle nested object queries");
- return Promise.resolve(complex_object);
- });
+ //.insert method should respond with the created document
+ var to_insert = {
+ value: 1,
+ random: rand
+ };
+ return self.insert(test_collection_name, to_insert)
+ .then(function(response){
+ assert.deepEqual(to_insert, response, ".insert method should respond with the created document");
+ return Promise.resolve();
+ });
- }).then(function(complex_object){
- //.update should modify document values with dot notation
- complex_object.body.name = "Hanna";
- return self.update(test_collection_name, {id: complex_object.id}, {"body.name": complex_object.body.name})
- .then(function(){
- return self.find(test_collection_name, {id: complex_object.id});
- }).then(function(results){
- assert.deepEqual(complex_object, results[0], ".update should modify document values with dot notation");
- return Promise.resolve(complex_object);
- });
+ }).then(function(){
+ //check if find resolves with an array
- }).then(function(complex_object){
- //.update should modify document values using nested object as a query
- complex_object.body.name = "Marzanna";
- return self.update(test_collection_name, {id: complex_object.id}, {body: {name: complex_object.body.name}})
- .then(function(){
- return self.find(test_collection_name, {id: complex_object.id});
- }).then(function(results){
- assert.deepEqual(complex_object, results[0], ".update should modify document values using nested object as a query ");
- return Promise.resolve(complex_object);
- });
+ return self.find(test_collection_name, {}, {})
+ .then(function(documents){
+ assert(documents instanceof Array, "datastore." + self.name + ".find should resolve with an array");
+ return Promise.resolve();
+ });
- }).then(function(complex_object){
- //.update should insert new value to a field that previously had no value (undefined)
- complex_object.body.other = "Focca";
- return self.update(test_collection_name, {id: complex_object.id}, {body: {other: complex_object.body.other}})
- .then(function(){
- return self.find(test_collection_name, {id: complex_object.id});
- }).then(function(results){
- assert.deepEqual(complex_object, results[0], ".update should insert new value to a field that previously had no value (undefined)");
- return Promise.resolve(complex_object);
- });
+ }).then(function(){
+ //check if amount of created documents checks out
+ var creates = [
+ self.insert(test_collection_name, {
+ value: 2,
+ random: rand
+ }),
+ self.insert(test_collection_name, {
+ value: 3,
+ random: rand
+ }),
+ self.insert(test_collection_name, {
+ value: 4,
+ random: -rand
+ }),
+ ]
+
+ var created_so_far = 4;
+ return Promise.all(creates)
+ .then(function(){
+ return self.find(test_collection_name, {}, {});
+ }).then(function(documents){
+ assert(documents.length == created_so_far, "Inserted " + created_so_far + " documents so far, but " + documents.length + " were returned on .find()");
+ return Promise.resolve(created_so_far);
+ });
+
+ }).then(function(created_so_far){
+ //check if there is a proper amount of documents with random value set to rand
+ var documents_with_rand = created_so_far - 1;
+ return self.find(test_collection_name, {
+ random: rand
+ }, {})
+ .then(function(documents){
+ assert(documents.length == documents_with_rand, "Inserted " + documents_with_rand + " documents with `random` set to `" + rand + "` so far, but " + documents.length + " were returned on .find({random: " + rand + "})");
+ return Promise.resolve();
+ });
- }).then(function(complex_object){
- //.remove should remove only one document when "just_one" is set to true
- return Promise.all([
- self.insert(test_collection_name, complex_object),
- self.insert(test_collection_name, complex_object),
- self.insert(test_collection_name, complex_object),
- ]).then(function(){
- //all the "complex_object" documents have the same id
- return self.remove(test_collection_name, {id: complex_object.id}, true);
}).then(function(){
- return self.find(test_collection_name, {id: complex_object.id});
- }).then(function(results){
- assert(results.length==3, ".remove should remove only *one* document when `just_one` argument is set to true");
- return Promise.resolve(complex_object);
- });
+ //Should store a complex object
+ var complex_object = {
+ id: "aseoifaoeina",
+ body: {
+ name: "Anna",
+ surname: "Fontanna"
+ }
+ };
+ return self.insert(test_collection_name, complex_object)
+ .then(function(response){
+ assert.deepEqual(complex_object, response, ".insert with complex object should resolve with that complex object.");
+ return self.find(test_collection_name, {
+ id: complex_object.id
+ })
+ }).then(function(response){
+ assert.deepEqual(complex_object, response[0], ".insert with complex object should store that complex object.");
+ return Promise.resolve(complex_object);
+ });
+
+ }).then(function(complex_object){
+ //Should handle dot-notation nested queries
+ return self.find(test_collection_name, {
+ "body.name": complex_object.body.name
+ })
+ .then(function(response){
+ assert.deepEqual(complex_object, response[0], ".find method should handle dot notation queries");
+ return Promise.resolve(complex_object);
+ });
+
+ }).then(function(complex_object){
+ return self.find(test_collection_name, {
+ body: {
+ name: complex_object.body.name
+ }
+ })
+ .then(function(response){
+ assert.deepEqual(complex_object, response[0], ".find method should handle nested object queries");
+ return Promise.resolve(complex_object);
+ });
+
+ }).then(function(complex_object){
+ //.update should modify document values with dot notation
+ complex_object.body.name = "Hanna";
+ return self.update(test_collection_name, {
+ id: complex_object.id
+ }, {
+ "body.name": complex_object.body.name
+ })
+ .then(function(){
+ return self.find(test_collection_name, {
+ id: complex_object.id
+ });
+ }).then(function(results){
+ assert.deepEqual(complex_object, results[0], ".update should modify document values with dot notation");
+ return Promise.resolve(complex_object);
+ });
+
+ }).then(function(complex_object){
+ //.update should modify document values using nested object as a query
+ complex_object.body.name = "Marzanna";
+ return self.update(test_collection_name, {
+ id: complex_object.id
+ }, {
+ body: {
+ name: complex_object.body.name
+ }
+ })
+ .then(function(){
+ return self.find(test_collection_name, {
+ id: complex_object.id
+ });
+ }).then(function(results){
+ assert.deepEqual(complex_object, results[0], ".update should modify document values using nested object as a query ");
+ return Promise.resolve(complex_object);
+ });
+
+ }).then(function(complex_object){
+ //.update should insert new value to a field that previously had no value (undefined)
+ complex_object.body.other = "Focca";
+ return self.update(test_collection_name, {
+ id: complex_object.id
+ }, {
+ body: {
+ other: complex_object.body.other
+ }
+ })
+ .then(function(){
+ return self.find(test_collection_name, {
+ id: complex_object.id
+ });
+ }).then(function(results){
+ assert.deepEqual(complex_object, results[0], ".update should insert new value to a field that previously had no value (undefined)");
+ return Promise.resolve(complex_object);
+ });
+
+ }).then(function(complex_object){
+ //.remove should remove only one document when "just_one" is set to true
+ return Promise.all([
+ self.insert(test_collection_name, complex_object),
+ self.insert(test_collection_name, complex_object),
+ self.insert(test_collection_name, complex_object),
+ ]).then(function(){
+ //all the "complex_object" documents have the same id
+ return self.remove(test_collection_name, {
+ id: complex_object.id
+ }, true);
+ }).then(function(){
+ return self.find(test_collection_name, {
+ id: complex_object.id
+ });
+ }).then(function(results){
+ assert(results.length == 3, ".remove should remove only *one* document when `just_one` argument is set to true");
+ return Promise.resolve(complex_object);
+ });
+
+ }).then(function(complex_object){
+ //.remove should remove all matching documents when "just_one" is falsy
+ return Promise.all([
+ self.insert(test_collection_name, complex_object),
+ self.insert(test_collection_name, complex_object),
+ self.insert(test_collection_name, complex_object),
+ ]).then(function(){
+ //all the "complex_object" documents have the same id
+ return self.remove(test_collection_name, {
+ id: complex_object.id
+ }, false);
+ }).then(function(){
+ return self.find(test_collection_name, {
+ id: complex_object.id
+ });
+ }).then(function(results){
+ assert(results.length == 0, ".remove should remove all matching documents when 'just_one' is falsy");
+ return Promise.resolve(complex_object);
+ });
- }).then(function(complex_object){
- //.remove should remove all matching documents when "just_one" is falsy
- return Promise.all([
- self.insert(test_collection_name, complex_object),
- self.insert(test_collection_name, complex_object),
- self.insert(test_collection_name, complex_object),
- ]).then(function(){
- //all the "complex_object" documents have the same id
- return self.remove(test_collection_name, {id: complex_object.id}, false);
}).then(function(){
- return self.find(test_collection_name, {id: complex_object.id});
- }).then(function(results){
- assert(results.length==0, ".remove should remove all matching documents when 'just_one' is falsy");
- return Promise.resolve(complex_object);
- });
-
- }).then(function(){
- self.clear_collection(test_collection_name);
- }).catch(function(err){
- self.clear_collection(test_collection_name);
- console.log(err.stack);
- return Promise.reject("Compatibility test unsuccesfull")
- });
+ self.clear_collection(test_collection_name);
+ }).catch(function(err){
+ self.clear_collection(test_collection_name);
+ console.log(err.stack);
+ return Promise.reject("Compatibility test unsuccesfull")
+ });
};
module.exports = Datastore;
\ No newline at end of file
diff --git a/lib/chip-types/field-type.js b/lib/chip-types/field-type.js
index fd85de21..74fbbac2 100644
--- a/lib/chip-types/field-type.js
+++ b/lib/chip-types/field-type.js
@@ -1,68 +1,414 @@
var Sealious = require("../main.js");
var Promise = require("bluebird");
var merge = require("merge");
var Chip = require("./chip.js");
+var FieldTypeDescription = require("../data-structures/field-type-description.js");
+
/**
* Stores field type metadata, as well as validation methods
* @class
*/
-
-function FieldType(parent_module_path, name){
- var instance = function(){};
- Chip.call(instance, parent_module_path, true, "field_type", name);
+function FieldType (declaration) {
+ Chip.call(this, true, "field_type", declaration.name);
- instance.prototype = Object.create(FieldType.prototype);
+ this.old_value_sensitive_methods = declaration.old_value_sensitive_methods || false;
- return instance;
+ this.process_declaration(declaration);
}
-FieldType.prototype = new function(){
+FieldType.prototype = new function(){
+
+ this.process_declaration = function(declaration){
+ this.declaration = declaration;
+ this.name = declaration.name;
+
+ if (declaration.extends) {
+ this.parent_field_type = Sealious.ChipManager.get_chip("field_type", declaration.extends);
+ } else {
+ this.parent_field_type = null;
+ }
+
+ // var method_names = ["is_proper_value", "valudate_declaration", "encode", "decode", ""];
+
+ // method_names.forEach(function(method_name){
+ // if(declaration[method_name]){
+ // this[method_name] = declaration[method_name];
+ // }else{
+ // this[method_name] = this["_"+method_name];
+ // }
+ // });
+ }
+
+ this.is_old_value_sensitive = function(method_name){
+ if (method_name == undefined) {
+ if (typeof this.old_value_sensitive_methods == "boolean") {
+ return this.old_value_sensitive_methods;
+ } else {
+ for (var i in this.old_value_sensitive_methods) {
+ if (this.old_value_sensitive_methods[i]) {
+ return true;
+ }
+ }
+ return false;
+ }
+ } else {
+ if (typeof this.old_value_sensitive_methods == "boolean") {
+ return this.old_value_sensitive_methods;
+ } else {
+ return this.old_value_sensitive_methods[method_name];
+ }
+ }
+ }
+
+
+ this.get_method = function(method_name){
+ var ret;
+ if (this.declaration[method_name]) {
+ ret = this.declaration[method_name];
+ } else {
+ ret = this["_" + method_name].bind(this);
+ }
+ return Promise.method(ret);
+ }
+
/**
* Whether a given value can be stored in this field type instance
* @memberOf FieldType
* @abstract
* @param {any} value value of this variable will be tested for compatibility with this field
* @return {Promise}
*/
- this.isProperValue = function(value){
- return Promise.resolve();
+ //to be decorated
+ this._is_proper_value = function(accept){
+ accept();
}
- this.validate_declaration = function(declaration){
- return Promise.resolve();
+
+ //to be decorated
+ this.is_proper_declaration = function(declaration){
+ return true;
+ }
+
+ //to be decorated
+ this._encode = function(context, params, value_in_code){
+ return value_in_code;
}
- this.encode = function(value_in_code){
- return Promise.resolve(value_in_code);
+ //to be decorated
+ this._get_description = function(){
+ return new FieldTypeDescription(this.name);
}
- this.encode.uses_context = false;
+ this._encode.uses_context = false;
- this.decode = function(value_in_database, formatting_options){
- return Promise.resolve(value_in_database);
+ //to be decorated
+ this._decode = function(value_in_database, formatting_options){
+ return value_in_database;
}
- this.set_params = function(param_map){
- if(this.params==undefined){
- this.params = param_map;
+ this._decode.uses_context = false;
+
+ this.is_proper_value = function(context, params, new_value, old_value){
+ var self = this;
+ var validate_in_parent;
+ if (this.declaration.extends) {
+ validate_in_parent = this.parent_field_type.is_proper_value(context, params, new_value, old_value);
+ } else {
+ validate_in_parent = Promise.resolve();
}
- this.params = merge(this.params, param_map);
+ return validate_in_parent.then(function(){
+ return new Promise(function(resolve, reject){
+ var new_reject = function(error_message){
+ reject(new Sealious.Errors.ValidationError(error_message));
+ }
+ self.get_method("is_proper_value")(resolve, new_reject, context, params, new_value, old_value);
+ });
+ });
}
- this.set_fieldname = function(fieldname){
- this.fieldname = fieldname;
+ /**
+ * If a field-type has defined .decode method, use it. Otherwise use it's parent's or the default one
+ **/
+ this.decode = function(value_in_database, params, formatting_options){
+ if (this.declaration.extends && this.declaration.decode == undefined) {
+ return this.parent_field_type.decode(value_in_database, params, formatting_options);
+ } else {
+ return this.get_method("decode")(value_in_database, params, formatting_options);
+ }
}
- this.get_params = function(context){
- return this.params;
+ /**
+ * If a field-type has defined .decode method, use it. Otherwise use it's parent's or the default one
+ **/
+ this.encode = function(context, params, value_in_code){
+ if (this.declaration.extends && this.declaration.encode == undefined) {
+ return this.parent_field_type.encode(context, params, value_in_code);
+ } else {
+ return this.get_method("encode")(context, params, value_in_code);
+ }
}
+
+ this.get_description = function(params){
+ if (this.declaration.extends && this.declaration.get_description == undefined) {
+ return this.parent_field_type.get_description(params)
+ } else {
+ return this.get_method("get_description")(params)
+ .then(function(description){
+ if (typeof description == "string") {
+ return Promise.resolve(new FieldTypeDescription(description));
+ } else {
+ return Promise.resolve(description);
+ }
+ });
+ }
+ }
+}
+
+FieldType.test_init = function(){
+ new Sealious.ChipTypes.FieldType({
+ name: "test_field_type"
+ });
+
+ new Sealious.ChipTypes.FieldType({
+ name: "rejecting_father",
+ is_proper_value: function(accept, reject){
+ reject("Rejected by the father");
+ },
+ encode: function(){
+ return "from_father"
+ },
+ decode: function(){
+ return "from_father"
+ },
+ get_description: function(){
+ return "from_father"
+ }
+ })
+
+ new Sealious.ChipTypes.FieldType({
+ name: "accepting_son",
+ extends: "rejecting_father",
+ is_proper_value: function(accept){
+ accept();
+ },
+ encode: function(){
+ return "from_son";
+ },
+ decode: function(){
+ return "from_son";
+ }
+ })
+
+ new Sealious.ChipTypes.FieldType({
+ name: "hesitant_daughter",
+ extends: "rejecting_father"
+ })
}
-FieldType.is_a_constructor = true;
+FieldType.test_start = function(){
+ describe("FieldType", function(){
+ var test_field_type = Sealious.ChipManager.get_chip("field_type", "test_field_type");
+
+ var but_it_didnt = new Error("But it didn't");
+
+ describe("default methods", function(){
+ describe("when not overwritten", function(){
+ it("should use default .is_proper_value", function(done){
+ var return_value = test_field_type.is_proper_value("any_value")
+ .then(function(){
+ done();
+ }).catch(function(error){
+ done(new Error("But it rejected."));
+ })
+ })
+
+ it("should use default .is_proper_declaration", function(done){
+ var return_value = test_field_type.is_proper_declaration({});
+ if (typeof return_value != "boolean" || return_value != true) {
+ done(but_it_didnt);
+ } else {
+ done();
+ }
+ });
+
+ it("should use default .encode", function(done){
+ var what_its_been_fed = "dogfood";
+ test_field_type.encode(new Sealious.Context(), {}, what_its_been_fed)
+ .then(function(encoded){
+ if (encoded == what_its_been_fed) {
+ done();
+ } else {
+ done(new Error("But it returnet something else"));
+ }
+ }).catch(function(error){
+ console.error(error);
+ done(new Error("but it threw an error"));
+ })
+ });
+
+ it("should use default .decode", function(done){
+ var what_its_been_fed = "dogfood";
+ test_field_type.decode(what_its_been_fed)
+ .then(function(decoded){
+ if (decoded == what_its_been_fed) {
+ done();
+ } else {
+ done(new Error("But it returnet something else"));
+ }
+ }).catch(function(error){
+ console.error(error);
+ done(new Error("but it threw an error"));
+ })
+ });
+
+ it("should use default .get_description", function(done){
+ test_field_type.get_description()
+ .then(function(description){
+ if (description.summary == "test_field_type") {
+ done();
+ } else {
+ done(new Error("But it didn't"));
+ }
+ });
+ })
+ })
+
+
+ describe("when overwritten", function(){
+
+ var rejecting_father = Sealious.ChipManager.get_chip("field_type", "rejecting_father");
+
+ it("should use the custom .is_proper_value method", function(done){
+ rejecting_father.is_proper_value("any_value")
+ .then(function(){
+ done(new Error("But it didn't (should have been rejected in this case, but wasn't)"));
+ }).catch(function(){
+ done();
+ });
+ });
+
+ it("should use the custom .encode method", function(done){
+ rejecting_father.encode(new Sealious.Context(), {}, "anything")
+ .then(function(encoded_value){
+ if (encoded_value == "from_father") {
+ done();
+ } else {
+ done(new Error("But it didn't"));
+ }
+ })
+ });
+
+ it("should use the custom .decode method", function(done){
+ rejecting_father.decode("anything")
+ .then(function(decoded_value){
+ if (decoded_value == "from_father") {
+ done();
+ } else {
+ done(new Error("But it didn't"));
+ }
+ })
+ });
+
+ it("should use the custom .get_description method", function(done){
+ rejecting_father.get_description()
+ .then(function(description){
+ if (description.summary == "from_father") {
+ done();
+ } else {
+ done(new Error("But it didn't"));
+ }
+ });
+ });
+ })
+ })
+
+
+
+ describe("inheritance", function(){
+
+ var accepting_son = Sealious.ChipManager.get_chip("field_type", "accepting_son");
+ var hesitant_daughter = Sealious.ChipManager.get_chip("field_type", "hesitant_daughter");
+
+ it("should inherit is_proper_value", function(done){
+ accepting_son.is_proper_value(new Sealious.Context(), {}, "any")
+ .then(function(){
+ done(new Error("accepting_son accepted the value, which should have been rejected by his rejecting_father"));
+ }).catch(function(error){
+ if (error.message == "Rejected by the father") {
+ done();
+ } else {
+ done(new Error("But it didn't - it returned `" + error + "but should have returned \"Rejected by the father\""));
+ }
+ })
+ });
+
+ it("should use parent's is_proper_value when not having its own", function(done){
+ hesitant_daughter.is_proper_value(new Sealious.Context(), {}, "any")
+ .then(function(){
+ done(new Error("But it accepted value, which should have been rejected by rejecting_father"));
+ }).catch(function(error){
+ if (error.message == "Rejected by the father") {
+ done();
+ } else {
+ done(new Error("But it didn't"));
+ }
+ });
+ });
+
+ it("should use child's .encode method when a child has it's own encode method", function(done){
+ accepting_son.encode(new Sealious.Context(), {}, "anything")
+ .then(function(encoded_value){
+ if (encoded_value == "from_son") {
+ done();
+ } else {
+ done(new Error("But it didn't"));
+ }
+ });
+ });
+
+ it("should use parent's .encode method when a child does not have it's own", function(done){
+ hesitant_daughter.encode(new Sealious.Context(), {}, "anything")
+ .then(function(encoded_value){
+ if (encoded_value == "from_father") {
+ done();
+ } else {
+ done(new Error("But it didn't"));
+ }
+ })
+ });
+
+ it("should use child's .decode method when a child has it's own decode method", function(done){
+ accepting_son.decode("anything")
+ .then(function(decoded_value){
+ if (decoded_value == "from_son") {
+ done();
+ } else {
+ done(new Error("But it didn't"));
+ }
+ });
+ });
+
+ it("should use parent's .decode method when a child does not have it's own", function(done){
+ hesitant_daughter.decode("anything")
+ .then(function(decoded_value){
+ if (decoded_value == "from_father") {
+ done();
+ } else {
+ done(new Error("But it didn't"));
+ }
+ })
+ });
+
+ });
+
+ //sprawdzanie get_description
+ });
+}
FieldType.type_name = "field_type";
+
module.exports = FieldType;
\ No newline at end of file
diff --git a/lib/chip-types/resource-representation.js b/lib/chip-types/resource-representation.js
index 811fadca..12bb67da 100644
--- a/lib/chip-types/resource-representation.js
+++ b/lib/chip-types/resource-representation.js
@@ -1,40 +1,40 @@
/**
* Represents a particular resource in database. Constructed by database entry.
* @class
* @param {object} database_entry
*/
-function ResourceRepresentation(database_entry){
+function ResourceRepresentation (database_entry) {
this.database_entry = database_entry;
}
ResourceRepresentation.prototype = new function(){
/**
* Returns an object representing the resource, ready to be output for the public, e.g. as JSON
* @alias Resource#getData
* @return {object}
*/
this.getData = function(){
var data = this.database_entry.body || {};
data.owner_id = this.database_entry.owner;
data.id = this.database_entry.sealious_id;
data.access_mode = this.database_entry.access_mode;
data.type = this.database_entry.type;
-
+
return data;
}
/**
* Encodes Resource's data into JSON
* @alias Resource#toString
* @return {string} contains the json-encoded data
*/
this.toString = function(){
return JSON.stringify(this.getData());
}
this.get_access_mode = function(){
return this.database_entry.access_mode;
}
}
-module.exports = ResourceRepresentation;
+module.exports = ResourceRepresentation;
\ No newline at end of file
diff --git a/lib/chip-types/resource-type-field.js b/lib/chip-types/resource-type-field.js
index acf8c388..444fe82e 100644
--- a/lib/chip-types/resource-type-field.js
+++ b/lib/chip-types/resource-type-field.js
@@ -1,103 +1,107 @@
var Sealious = require("../main.js");
var Promise = require("bluebird");
-function ResourceTypeField(declaration, resource_type) {
- this.name = declaration.name;
- this.type_name = declaration.type;
- this.human_readable_name = declaration.human_readable_name || null;
-
- if(!Sealious.ChipManager.chip_exists("field_type", this.type_name)) {
- throw new Sealious.Errors.DeveloperError("In declaration of resource type '" + resource_type.name +"': unknown field type '"+this.type_name+"' in field '"+this.name+"'.");
- }
- var type_constructor = Sealious.ChipManager.get_chip("field_type", declaration.type);
- this.type_parameters = declaration.params;
- this.default_value = declaration.default_value;
- this.type = new type_constructor();
- this.type.set_params(declaration.params);
- this.type.init && this.type.init();
- this.required = declaration.required || false;
- this.derived = declaration.derived || false;
+/**
+ * !! resource_type is optional, needen only for nice errors
+ *
+ */
+
+function ResourceTypeField (declaration, resource_type) {
+ this.name = declaration.name;
+ this.type_name = declaration.type;
+ this.human_readable_name = declaration.human_readable_name || null;
+
+ if (!Sealious.ChipManager.chip_exists("field_type", this.type_name)) {
+ throw new Sealious.Errors.DeveloperError("In declaration of resource type '" + resource_type.name + "': unknown field type '" + this.type_name + "' in field '" + this.name + "'.");
+ }
+ this.params = declaration.params;
+ this.default_value = declaration.default_value;
+ this.type = Sealious.ChipManager.get_chip("field_type", declaration.type);
+
+ this.type.init && this.type.init();
+ this.required = declaration.required || false;
+ this.derived = declaration.derived || false;
};
ResourceTypeField.prototype = new function(){
/**
* Shorthand for ResourceTypeField.type.isProperValue
* @alias ResourceTypeField#isProperValue
* @param {object} value
* @return {Promise}
*/
this.check_value = function(context, value, old_value){
- return this.type.isProperValue(context, value, old_value);
-
- /*var _arguments;
- if(this.type.isProperValue.uses_context){
- _arguments = [context, value, old_value]
- }else{
- _arguments = [value, old_value]
- }
- var ret = this.type.isProperValue.apply(this.type, _arguments);
- return ret;
- /*
- .catch(function(err){
- console.log("caught error", err);
- var new_error={};
- new_error[this.name] = err;
- return Promise.reject(new_error);
- }.bind(this));
- */
+ return this.type.is_proper_value(context, this.params, value, old_value);
}
- function to_map(name, value){
+ function to_map (name, value) {
var obj = {};
obj[name] = value;
return Promise.resolve(obj);
}
- this.has_previous_value_sensitive_methods = function(){
- if (this.encode_value.old_value_sensitive || this.decodeValue.old_value_sensitive || this.type.old_value_sensitive)
- return true;
-
- return false;
+ this.is_old_value_sensitive = function(method_name){
+ return this.type.is_old_value_sensitive(method_name);
}
- this.encode_value = function(context, value, old_value){
- var _arguments;
- if(this.type.encode.uses_context){
- _arguments = [context, value];
- }else{
- _arguments = [value];
- }
- if(this.type.old_value_sensitive){
- _arguments.push(old_value)
- }
- return this.type.encode.apply(this.type, _arguments);
+ this.encode_value = function(context, new_value, old_value){
+ return this.type.encode(context, this.params, new_value, old_value);
}
this.decode_value = function(context, value_in_database){
- if(this.type.decode.uses_context){
+ if (this.type.decode.uses_context) {
_arguments = [context, value_in_database];
- }else{
+ } else {
_arguments = [value_in_database];
}
var decode_value = this.type.decode.apply(this.type, _arguments);
return decode_value;
}
this.get_signature = function(with_validator){
//with_validator:boolean - whether to include validator function in field description. Warning! If set to true, the output is not serializable in JSON.
var field_signature = {};
field_signature.name = this.name;
field_signature.type = this.type_name;
field_signature.required = this.required;
- field_signature.human_readable_name = (typeof this.human_readable_name=="string")? this.human_readable_name : undefined;
- field_signature.params = this.type.get_params();
+ field_signature.human_readable_name = (typeof this.human_readable_name == "string") ? this.human_readable_name : undefined;
+ field_signature.params = this.params;
field_signature.validate = this.check_value.bind(this);
field_signature.default_value = this.default_value;
return field_signature;
}
+
+ this.get_nice_name = function(){
+ return this.human_readable_name || this.name;
+ }
+}
+
+ResourceTypeField.test_start = function(){
+ describe("ResourceTypeField", function(){
+ describe("constructor", function(){
+ it("should throw a nice error when non-existent field type is provided in declaration", function(done){
+ try {
+ var test_field = new ResourceTypeField({
+ name: "test_field",
+ type: "truly_non_existent_field_type",
+ }, {
+ name: "fake_resource_type"
+ });
+ } catch (error) {
+ if (error.is_developer_fault == true) {
+ done();
+ } else {
+ done(new Error("But it threw a non-nice error."));
+ }
+ return;
+ }
+ done(new Error("But it didn't throw any error at all"));
+ });
+ })
+ })
}
module.exports = ResourceTypeField;
\ No newline at end of file
diff --git a/lib/chip-types/resource-type.js b/lib/chip-types/resource-type.js
index 3b1e771f..8678f62e 100644
--- a/lib/chip-types/resource-type.js
+++ b/lib/chip-types/resource-type.js
@@ -1,237 +1,214 @@
var Sealious = require("../main.js");
var Promise = require("bluebird");
var merge = require("merge");
var Chip = require("./chip.js");
var ResourceTypeField = require("./resource-type-field.js");
-var ResourceType = function(parent_module_path, declaration){
- if(typeof declaration != "object"){
+var ResourceType = function(declaration){
+ if (typeof declaration != "object") {
throw new Sealious.Errors.DeveloperError("Tried to create a resource-type without a declaration");
}
- Chip.call(this, parent_module_path, true, "resource_type", declaration.name);
+ Chip.call(this, true, "resource_type", declaration.name);
this.name = declaration.name;
this.fields = {};
this.references = {};
- this.keys = {};
this.access_strategy = {
default: Sealious.ChipManager.get_chip("access_strategy", "public")
};
this._process_declaration(declaration);
}
ResourceType.prototype = new function(){
this._process_declaration = function(declaration){
- if(declaration){
- if(declaration.fields){
+ if (declaration) {
+ if (declaration.fields) {
this.add_fields(declaration.fields);
}
this.set_access_strategy(declaration.access_strategy);
}
}
this.add_field = function(field_declaration){
var field_object = new ResourceTypeField(field_declaration, this);
var field_name = field_object.name;
- if(!this.keys[field_name]){
+ if (!this.fields[field_name]) {
+ this.fields[field_name] = field_object;
this.fields[field_name] = field_object;
- this.keys[field_name] = field_object;
}
- }
+ }
this.add_fields = function(field_declarations_array){
- for(var i in field_declarations_array){
+ for (var i in field_declarations_array) {
var declaration = field_declarations_array[i];
this.add_field(declaration);
}
}
this.has_previous_value_sensitive_fields = function(){
- for (var field_name in this.fields){
- if (this.fields[field_name].has_previous_value_sensitive_methods()){
+ for (var field_name in this.fields) {
+ if (this.fields[field_name].has_previous_value_sensitive_methods()) {
return true;
}
}
return false;
}
- function ensure_no_unknown_fields(values){
+ function ensure_no_unknown_fields (values) {
var validation_errors = {};
- for(var field_name in values){
+ for (var field_name in values) {
- if(this.keys[field_name]==undefined){
+ if (this.fields[field_name] == undefined) {
validation_errors[field_name] = "unknown_field";
}
}
return validation_errors;
}
- function ensure_no_missing_required_fields(values){
- var validation_errors = {};
- for(var i in this.keys){
- var field = this.keys[i];
- if(field.required && values[field.name]==undefined){
- validation_errors[field.name] = "missing_value";
+ this.extend_with_missing_field_values_errors = function(current_validation_errors, values){
+ for (var i in this.fields) {
+ var field = this.fields[i];
+ if (field.required && values[field.name] == undefined) {
+ current_validation_errors[field.name] = new Sealious.Errors.ValidationError("Missing value for field `" + field.get_nice_name() + "`");
}
}
- return validation_errors;
}
this.validate_field_values = function(context, check_missing, values, old_values){
- var that = this;
+ var self = this;
var validation_errors = {};
- validation_errors = merge(validation_errors, ensure_no_unknown_fields.call(that, values));
- if(check_missing){
- validation_errors = merge(validation_errors, ensure_no_missing_required_fields.call(that, values));
- }
- var promises = {};
- for(var key in values){
- if(validation_errors[key]===undefined){
- var _arguments;
- var field = that.keys[key];
- var value = values[key];
- var old_value = (old_values && old_values.body && old_values.body[key]) || undefined;
- var validation_result = field.check_value(context, value, old_value);
- if(validation_result && validation_result.reflect){
- promises[key] = validation_result.reflect();
- }else{
- promises[key] = validation_result;
- }
- }
- }
- var error_message = "There are problems with some of the provided values";//TODO: ładnie generować tekst podsumowujący problem z inputem
+ var validation_tasks = [];
+ for (var key in values) {
+ var value = values[key];
+ var old_value = old_values ? old_values[key] : undefined;
+ var validation_promise = self.fields[key].check_value(context, value, old_value).catch((function(key){
+ return function(error){
+ validation_errors[key] = error;
+ return Promise.resolve();
+ }
+ })(key));
+ validation_tasks.push(validation_promise);
+ }
- return Promise.props(promises)
- .then(function(validation_results){
- for(var key in validation_results){
- var result = validation_results[key];
- if(result==undefined) continue;
- if(typeof result=="boolean"){
- if(result.value===false){
- validation_errors[key] = "bad_value";
- }
- }else if(typeof result=="string"){
- validation_errors[key] = string;
- }else if(typeof result=="object"){
- if(result.isRejected){ //checking if result is an instance of a PromiseInspection
- if(result.isRejected()){
- validation_errors[key] = result.reason();
- }
- }else if(result instanceof Error){
- if(result.type=="validation_error"){
- validation_errors[key] = result;
- }else{
- validation_errors[key] = {error_message: result.status_message, data: result.data};
- }
+ return Promise.all(validation_tasks)
+ .then(function(){
+ self.extend_with_missing_field_values_errors(validation_errors, values);
+ var has_errors = false;
+ for (var key in validation_errors) {
+ //validation_errors is not an empty object
+ has_errors = true;
+ var error = validation_errors[key];
+ if (error.is_user_fault) {
+ validation_errors[key] = error.message;
+ } else {
+ return Promise.reject(error);
}
}
- }
- if(Object.keys(validation_errors).length>0){
- throw new Sealious.Errors.ValidationError(error_message, {invalid_fields: validation_errors});
- }else{
- return Promise.resolve();
- }
- }.bind(this))
+ if (has_errors) {
+ return Promise.reject(new Sealious.Errors.ValidationError("There are problems with some of the provided values.", validation_errors));
+ } else {
+ //validation_errors is empty, resolve
+ return Promise.resolve();
+ }
+ });
}
this.encode_field_values = function(context, body, old_body){
var promises = {};
- for(var field_name in body){
+ for (var field_name in body) {
var current_value = body[field_name];
var old_value = old_body && old_body[field_name];
- promises[field_name] = this.keys[field_name].encode_value(context, current_value, old_value);
+ promises[field_name] = this.fields[field_name].encode_value(context, current_value, old_value);
}
return Promise.props(promises);
}
this.get_signature = function(with_validators){
//with_validators:boolean - whether to include validator functions in field descriptions. Warning! If set to true, the output is not serializable in JSON.
var resource_type_signature = [];
- for(var field_name in this.fields){
+ for (var field_name in this.fields) {
var field_signature = this.fields[field_name].get_signature(with_validators);
resource_type_signature.push(field_signature);
}
return resource_type_signature;
}
this.get_signature_with_validators = function(){
return this.get_signature(true);
}
this.set_access_strategy = function(strategy_declaration){
- if(typeof strategy_declaration == "string"){
- access_strategy_name = strategy_declaration;
+ if (typeof strategy_declaration == "string") {
+ access_strategy_name = strategy_declaration;
this.access_strategy = {
"default": Sealious.ChipManager.get_chip("access_strategy", access_strategy_name),
}
- }else if(typeof strategy_declaration =="object"){
- for(var action_name in strategy_declaration){
+ } else if (typeof strategy_declaration == "object") {
+ for (var action_name in strategy_declaration) {
var access_strategy = Sealious.ChipManager.get_chip("access_strategy", strategy_declaration[action_name]);
this.access_strategy[action_name] = access_strategy;
}
}
}
this.get_access_strategy = function(action){
return this.access_strategy[action] || this.access_strategy["default"];
}
this.has_large_data_fields = function(){
- for(var i in this.fields){
+ for (var i in this.fields) {
var field = this.fields[i];
- if(field.type.handles_large_data){
+ if (field.type.handles_large_data) {
return true;
}
}
return false;
}
- this.is_old_value_sensitive = function(){
- for (var i in this.fields){
- if (this.fields[i].type.old_value_sensitive){
+ this.is_old_value_sensitive = function(method_name){
+ for (var i in this.fields) {
+ if (this.fields[i].type.is_old_value_sensitive(method_name)) {
return true;
}
}
return false;
}
this.decode_values = function(context, values){
var decoded_values = {};
- for(var key in this.keys){
+ for (var key in this.fields) {
var value = values[key];
var field = this.fields[key];
- if(field==undefined) continue;
+ if (field == undefined) continue;
decoded_values[key] = field.decode_value(context, value);
}
return Promise.props(decoded_values);
}
this.decode_db_entry = function(context, db_document){
var id = db_document.sealious_id;
var original_body = db_document.body;
return this.decode_values(context, original_body)
- .then(function(decoded_body){
- var ret = {
- id: id,
- type: db_document.type,
- body: decoded_body,
- created_context: db_document.created_context,
- last_modified_context: db_document.last_modified_context,
- }
- return Promise.resolve(ret);
- });
+ .then(function(decoded_body){
+ var ret = {
+ id: id,
+ type: db_document.type,
+ body: decoded_body,
+ created_context: db_document.created_context,
+ last_modified_context: db_document.last_modified_context,
+ }
+ return Promise.resolve(ret);
+ });
}
}
-ResourceType.is_a_constructor = false;
-
module.exports = ResourceType;
\ No newline at end of file
diff --git a/lib/config/config-manager.js b/lib/config/config-manager.js
index b94907f9..76e8a179 100644
--- a/lib/config/config-manager.js
+++ b/lib/config/config-manager.js
@@ -1,68 +1,68 @@
var Sealious = require("../main.js");
var fs = require("fs");
var path = require("path");
var merge = require("merge");
var ConfigManager = new function(){
default_config = {};
config = {};
- function modify_config(is_default_config, key, value){
+ function modify_config (is_default_config, key, value) {
var key_elements = key.split('.');
var new_values = {};
var current_position = new_values;
- for(var i=0; i<key_elements.length-1; i++){
+ for (var i = 0; i < key_elements.length - 1; i++) {
var current_key = key_elements[i];
current_position[current_key] = {};
current_position = current_position[current_key];
}
- current_position[key_elements[key_elements.length-1]]=value;
- if(is_default_config){
+ current_position[key_elements[key_elements.length - 1]] = value;
+ if (is_default_config) {
default_config = merge.recursive(true, default_config, new_values);
- }else{
+ } else {
config = merge.recursive(true, config, new_values);
}
}
this.set_config = function(key, new_config){
- if(arguments.length==1){
+ if (arguments.length == 1) {
config = config;
- }else{
+ } else {
modify_config(false, key, new_config);
}
}
this.set_default_config = function(key, value){
- if(arguments.length==1){
+ if (arguments.length == 1) {
default_config = default_config;
- }else{
+ } else {
modify_config(true, key, value);
}
}
this.get_configuration = function(key){
var to_merge_left = default_config;
var to_merge_right = config;
- var key_elements = key==undefined? [] : key.split(".");
- while(key_elements.length){
+ var key_elements = key == undefined ? [] : key.split(".");
+ while (key_elements.length) {
var current_key = key_elements.splice(0, 1);
- to_merge_left = to_merge_left[current_key]==undefined? {} : to_merge_left[current_key];
- to_merge_right = to_merge_right[current_key]==undefined? {} : to_merge_right[current_key];
+ to_merge_left = to_merge_left[current_key] == undefined ? {} : to_merge_left[current_key];
+ to_merge_right = to_merge_right[current_key] == undefined ? {} : to_merge_right[current_key];
}
return merge.recursive(true, to_merge_left, to_merge_right);
}
this.get_config = this.get_configuration;
this.get_chip_config = function(longid){
return config.chip_config && config.chip_config[longid];
}
this.get_dispatcher_config = function(){
return config.dispatcher_config || {};
}
}
module.exports = ConfigManager;
\ No newline at end of file
diff --git a/lib/context.js b/lib/context.js
index 85c4cd76..7efadb2e 100644
--- a/lib/context.js
+++ b/lib/context.js
@@ -1,19 +1,19 @@
var Immutable = require("immutable");
-function Context(timestamp, ip, user_id){
- if(user_id===undefined){
- user_id=null;
+function Context (timestamp, ip, user_id) {
+ if (user_id === undefined) {
+ user_id = null;
}
- if(timestamp==undefined){
+ if (timestamp == undefined) {
var d = new Date();
timestamp = d.getTime();
}
var ret = Immutable.fromJS({
timestamp: timestamp,
- ip: ip,
+ ip: ip || null,
user_id: user_id
});
return ret;
}
module.exports = Context;
\ No newline at end of file
diff --git a/lib/core-services/file-manager.js b/lib/core-services/file-manager.js
index 3ac2a36e..18fc7541 100644
--- a/lib/core-services/file-manager.js
+++ b/lib/core-services/file-manager.js
@@ -1,113 +1,112 @@
var Promise = require("bluebird");
var UUIDGenerator = require("uid");
var path = require('path');
var fse = require("fs-extra");
var fs = require("fs");
var ResourceRepresentation = require("../chip-types/resource-representation.js");
var Sealious = require("../main.js");
/**
* Manages files
* @class
*/
- var root_path = function() {
- var parent_tmp = module.parent;
- var parent = null;
- while (parent_tmp) {
- parent = parent_tmp;
- parent_tmp = parent_tmp.parent;
- }
-
- return parent.filename;
+var root_path = function(){
+ var parent_tmp = module.parent;
+ var parent = null;
+ while (parent_tmp) {
+ parent = parent_tmp;
+ parent_tmp = parent_tmp.parent;
+ }
+
+ return parent.filename;
}
-var FileManager = new function(upload_path) {
- this.name = "files";
+var FileManager = new function(upload_path){
+ this.name = "files";
- if (!upload_path) {
- upload_path = "./uploaded_files/";
- }
+ if (!upload_path) {
+ upload_path = "./uploaded_files/";
+ }
- var upload_path_abs = path.resolve(root_path(), "../" + upload_path);
+ var upload_path_abs = path.resolve(root_path(), "../" + upload_path);
- this.save_file = function(file, upload_path) {
+ this.save_file = function(file, upload_path){
- if (!fs.existsSync(upload_path_abs)) {
- fse.mkdirs(upload_path_abs, function(err) {
- });
- }
+ if (!fs.existsSync(upload_path_abs)) {
+ fse.mkdirs(upload_path_abs, function(err){});
+ }
- var newID = UUIDGenerator(10);
+ var newID = UUIDGenerator(10);
- var upload_path_with_sealious_name = upload_path_abs + "/" + newID;
- fs.writeFile(upload_path_with_sealious_name, file.data, function (err,data) {
- if (err) {
- throw(err);
- }
- });
+ var upload_path_with_sealious_name = upload_path_abs + "/" + newID;
+ fs.writeFile(upload_path_with_sealious_name, file.data, function(err, data){
+ if (err) {
+ throw (err);
+ }
+ });
- var file_database_entry = {
- original_name: file.filename,
- creation_context: file.context,
- id: newID,
- mime_type: file.mime,
- }
+ var file_database_entry = {
+ original_name: file.filename,
+ creation_context: file.context,
+ id: newID,
+ mime_type: file.mime,
+ }
- return Sealious.Dispatcher.datastore.insert("files", file_database_entry, {})
- .then(function(){
- return Promise.resolve({
- id: newID,
- filename: file.filename
- });
- })
+ return Sealious.Dispatcher.datastore.insert("files", file_database_entry, {})
+ .then(function(){
+ return Promise.resolve({
+ id: newID,
+ filename: file.filename
+ });
+ })
- }
+ }
- this.diff = function(dispatcher, file) {
+ this.diff = function(dispatcher, file){
- }
+ }
- this.get_list = function(dispatcher, owner) {
- var query = {
- "body.owner": owner
- };
- Sealious.Logger.info("List for owner '" + owner + "' has been created");
- return this.find(dispatcher, query);
- }
+ this.get_list = function(dispatcher, owner){
+ var query = {
+ "body.owner": owner
+ };
+ Sealious.Logger.info("List for owner '" + owner + "' has been created");
+ return this.find(dispatcher, query);
+ }
- this.find = function(context, query) {
- return Sealious.Dispatcher.datastore.find("files", query)
- .then(function(documents) {
- var parsed_documents = documents.map(function(document) {
- var ret = Sealious.File.from_db_entry(document);
- ret.path_on_hdd = upload_path + ret.id;
- return ret;
- });
- return Promise.resolve(parsed_documents);
- })
- }
+ this.find = function(context, query){
+ return Sealious.Dispatcher.datastore.find("files", query)
+ .then(function(documents){
+ var parsed_documents = documents.map(function(document){
+ var ret = Sealious.File.from_db_entry(document);
+ ret.path_on_hdd = upload_path + ret.id;
+ return ret;
+ });
+ return Promise.resolve(parsed_documents);
+ })
+ }
- this.change_name = function(dispatcher, sealious_name, new_name) {
- return dispatcher.datastore.update("files", {
- sealious_id: sealious_name
- }, {
- $set: {
- "body.original_name": new_name
- }
- });
+ this.change_name = function(dispatcher, sealious_name, new_name){
+ return dispatcher.datastore.update("files", {
+ sealious_id: sealious_name
+ }, {
+ $set: {
+ "body.original_name": new_name
+ }
+ });
- }
+ }
- this.delete = function(dispatcher, query) {
+ this.delete = function(dispatcher, query){
- }
+ }
}
//wersjonowanie, historia dostępu, przetrzymywanie poprzednich wersji
-module.exports = FileManager;
+module.exports = FileManager;
\ No newline at end of file
diff --git a/lib/core-services/resource-manager.js b/lib/core-services/resource-manager.js
index d17f13ce..fc31a705 100644
--- a/lib/core-services/resource-manager.js
+++ b/lib/core-services/resource-manager.js
@@ -1,397 +1,598 @@
var Sealious = require("../main.js");
var Promise = require("bluebird");
var ResourceRepresentation = require("../chip-types/resource-representation.js");
var assert = require("assert");
var UUIDGenerator = require("uid");
/**
* Manages resources in the database
* @class
*/
- var ResourceManager = new function(){
- this.name = "resources";
+var ResourceManager = new function(){
+ this.name = "resources";
- var self = this;
+ var self = this;
- this.create = function(context, type_name, body){
- if(!Sealious.ChipManager.chip_exists("resource_type", type_name)){
- return Promise.reject(Sealious.Errors.ValidationError("Unknown resource type: " + type_name));
- }
- var resource_type_object = Sealious.ChipManager.get_chip("resource_type", type_name);
- var access_strategy = resource_type_object.get_access_strategy("create");
+ this.create = function(context, type_name, body){
+ if (!Sealious.ChipManager.chip_exists("resource_type", type_name)) {
+ return Promise.reject(Sealious.Errors.ValidationError("Unknown resource type: " + type_name));
+ }
+ var resource_type_object = Sealious.ChipManager.get_chip("resource_type", type_name);
+ var access_strategy = resource_type_object.get_access_strategy("create");
+ var old_values = {};
- var encoded_body = null;
+ if (resource_type_object.is_old_value_sensitive("is_proper_value")) {
+ for (var i in resource_type_object.fields) {
+ var field = resource_type_object.fields[i];
+ old_values[field.name] = null;
+ }
+ }
+ var encoded_body = {};
return access_strategy.check(context)
- .then(function(){
- return resource_type_object.validate_field_values(context, true, body);
- }).then(function(){
- return resource_type_object.encode_field_values(context, body);
- }).then(function(response){
- encoded_body = response;
- var newID = UUIDGenerator(10);
- var resource_data = {
- sealious_id: newID,
- type: type_name,
- body: encoded_body,
- created_context: context.toObject(),
- };
- return Sealious.Dispatcher.datastore.insert("resources", resource_data, {});
- }).then(function(inserted_document){
- var database_entry = inserted_document;
- return resource_type_object.decode_db_entry(context, database_entry);
- })
- }
-
- this.delete = function(context, type_name, id){
- if(!Sealious.ChipManager.chip_is_registred("resource_type." + type_name)){
- throw new Sealious.Errors.ValidationError("Unknown resource type: " + type_name);
- }
-
- var resource_type_object = Sealious.ChipManager.get_chip("resource_type", type_name);
- var access_strategy = resource_type_object.get_access_strategy("delete");
- return access_strategy.check(context)
- .then(function(){
- return Sealious.Dispatcher.datastore.remove("resources", {sealious_id: id, type: type_name}, {})
- })
- .then(function(data){
- return Promise.resolve();
+ .then(function(){
+ return resource_type_object.validate_field_values(context, true, body, old_values);
+ }).then(function(){
+ return resource_type_object.encode_field_values(context, body);
+ }).then(function(response){
+ encoded_body = response;
+ var newID = UUIDGenerator(10);
+ var resource_data = {
+ sealious_id: newID,
+ type: type_name,
+ body: encoded_body,
+ created_context: context.toObject(),
+ };
+ return Sealious.Dispatcher.datastore.insert("resources", resource_data, {});
+ }).then(function(inserted_document){
+ var database_entry = inserted_document;
+ return resource_type_object.decode_db_entry(context, database_entry);
+ })
+ }
+
+ this.delete = function(context, type_name, id){
+ if (!Sealious.ChipManager.chip_is_registred("resource_type." + type_name)) {
+ throw new Sealious.Errors.ValidationError("Unknown resource type: " + type_name);
+ }
+
+ var resource_type_object = Sealious.ChipManager.get_chip("resource_type", type_name);
+ var access_strategy = resource_type_object.get_access_strategy("delete");
+ return access_strategy.check(context)
+ .then(function(){
+ return Sealious.Dispatcher.datastore.remove("resources", {
+ sealious_id: id,
+ type: type_name
+ }, {})
+ })
+ .then(function(data){
+ return Promise.resolve();
+ });
+ }
+
+ this.get_by_id = function(context, resource_id){
+ //var access_strategy = resource_type_object.get_access_strategy("get_by_id");
+
+ var get_resource = Sealious.Dispatcher.datastore.find("resources", {
+ sealious_id: resource_id
+ }, {})
+ .then(function(documents){
+ if (documents[0] === undefined) {
+ return Promise.reject(new Sealious.Errors.NotFound("resource of id " + resource_id + " not found"));
+ } else {
+ var database_entry = documents[0];
+ var resource_type_name = database_entry.type;
+ var resource_type_object = Sealious.ChipManager.get_chip("resource_type", resource_type_name);
+ var ret = [];
+ ret[0] = resource_type_object;
+ ret[1] = resource_type_object.decode_db_entry(context, database_entry);
+ return Promise.all(ret);
+ }
+ }).then(function(response){
+ var resource_type = response[0];
+ var resource_data = response[1];
+ var access_strategy = resource_type.get_access_strategy("retrieve");
+ return access_strategy.check(context, resource_data);
+ })
+ return get_resource;
+ }
+
+ function filter_resource_list (context, access_strategy) {
+ return function(item){
+ return new Promise(function(resolve, reject){
+ access_strategy.check(context, item)
+ .then(function(){
+ resolve(true);
+ }).catch(function(){
+ resolve(false);
+ })
+ });
+ }
+ }
+
+ this.list_by_type = function(context, type_name){
+ var resource_type = Sealious.ChipManager.get_chip("resource_type", type_name);
+ var access_strategy = resource_type.get_access_strategy("retrieve");
+ var preliminary_access_strategy_check;
+ if (access_strategy.item_sensitive) {
+ preliminary_access_strategy_check = Promise.resolve();
+ } else {
+ preliminary_access_strategy_check = access_strategy.check(context);
+ }
+
+ var get_items = preliminary_access_strategy_check.then(function(){
+ return Sealious.Dispatcher.datastore.find("resources", {
+ type: type_name
+ }, {}, {});
});
- }
-
- this.get_by_id = function(context, resource_id){
- //var access_strategy = resource_type_object.get_access_strategy("get_by_id");
-
- var get_resource = Sealious.Dispatcher.datastore.find("resources", { sealious_id: resource_id }, {})
- .then(function(documents){
- if (documents[0] === undefined) {
- return Promise.reject(new Sealious.Errors.NotFound("resource of id " + resource_id + " not found"));
- } else {
- var database_entry = documents[0];
- var resource_type_name = database_entry.type;
- var resource_type_object = Sealious.ChipManager.get_chip("resource_type", resource_type_name);
- var ret = [];
- ret[0] = resource_type_object;
- ret[1] = resource_type_object.decode_db_entry(context, database_entry);
- return Promise.all(ret);
- }
- }).then(function(response){
- var resource_type = response[0];
- var resource_data = response[1];
- var access_strategy = resource_type.get_access_strategy("retrieve");
- return access_strategy.check(context, resource_data);
- })
- return get_resource;
- }
-
- function filter_resource_list(context, access_strategy){
- return function(item){
- return new Promise(function(resolve, reject){
- access_strategy.check(context, item)
- .then(function(){
- resolve(true);
- }).catch(function(){
- resolve(false);
- })
- });
- }
- }
-
- this.list_by_type = function(context, type_name){
- var resource_type = Sealious.ChipManager.get_chip("resource_type", type_name);
- var access_strategy = resource_type.get_access_strategy("retrieve");
- var preliminary_access_strategy_check;
- if(access_strategy.item_sensitive){
- preliminary_access_strategy_check = Promise.resolve();
- }else{
- preliminary_access_strategy_check = access_strategy.check(context);
- }
-
- var get_items = preliminary_access_strategy_check.then(function(){
- return Sealious.Dispatcher.datastore.find("resources", { type: type_name }, {}, {});
- });
-
- var decoded_items = get_items.map(resource_type.decode_db_entry.bind(resource_type, context));
-
- var filtered_items;
- if(access_strategy.item_sensitive){
- filtered_items = decoded_items.then(function(items){
- return Promise.filter(items, filter_resource_list(context, access_strategy));
- });
- }else{
- filtered_items = decoded_items;
- }
- return filtered_items;
- }
-
- this.find = function(context, field_values, type){
- //throw new Error("ResourceManager.find not implemented.");
-
- if(arguments.length==2){
- type = null;
- }
+
+ var decoded_items = get_items.map(resource_type.decode_db_entry.bind(resource_type, context));
+
+ var filtered_items;
+ if (access_strategy.item_sensitive) {
+ filtered_items = decoded_items.then(function(items){
+ return Promise.filter(items, filter_resource_list(context, access_strategy));
+ });
+ } else {
+ filtered_items = decoded_items;
+ }
+ return filtered_items;
+ }
+
+ this.find = function(context, field_values, type){
+ //throw new Error("ResourceManager.find not implemented.");
+
+ if (arguments.length == 2) {
+ type = null;
+ }
var query = {};
- if(type){
+ if (type) {
query.type = type;
}
- for(var field_name in field_values){
+ for (var field_name in field_values) {
query["body." + field_name] = field_values[field_name];
}
return Sealious.Dispatcher.datastore.find("resources", query)
- .then(function(documents){
- var parsed_documents = documents.map(function(document){return new ResourceRepresentation(document).getData()});
- return Promise.resolve(parsed_documents);
- });
-
- }
-
- this.patch_resource = function(context, type_name, resource_id, values_to_patch){
- //replaces just the provided values. Equivalent of PATCH request
- var resource_type_object = Sealious.ChipManager.get_chip("resource_type", type_name);
- access_strategy = resource_type_object.get_access_strategy();
- var get_item;
- if(access_strategy.item_sensitive || resource_type_object.is_old_value_sensitive()){
- get_item = self.get_by_id(context, resource_id);
- }else{
- get_item = Promise.resolve(null);
- }
-
- return get_item.then(function(item){
- return access_strategy.check(context, item);
- }).then(function(old_values){
- return resource_type_object.validate_field_values(context, false, values_to_patch, old_values)
- .then(function(){
- return Promise.resolve(old_values);
- })
- }).then(function(old_values){
- return resource_type_object.encode_field_values(context, values_to_patch, old_values && old_values.body);
- }).then(function(encoded_values){
- var query = {};
- query.last_modified_context = context.toObject();
- for(var field_name in encoded_values){
+ .then(function(documents){
+ var parsed_documents = documents.map(function(document){
+ return new ResourceRepresentation(document).getData()
+ });
+ return Promise.resolve(parsed_documents);
+ });
+
+ }
+
+ this.patch_resource = function(context, type_name, resource_id, values_to_patch){
+ //replaces just the provided values. Equivalent of PATCH request
+ var resource_type_object = Sealious.ChipManager.get_chip("resource_type", type_name);
+ access_strategy = resource_type_object.get_access_strategy();
+ var get_item;
+ if (access_strategy.item_sensitive || resource_type_object.is_old_value_sensitive()) {
+ get_item = self.get_by_id(context, resource_id);
+ } else {
+ get_item = Promise.resolve({
+ body: {}
+ });
+ }
+
+ return get_item.then(function(item){
+ return access_strategy.check(context, item);
+ }).then(function(current_resource){
+ var old_values = current_resource.body;
+ return resource_type_object.validate_field_values(context, false, values_to_patch, old_values)
+ .then(function(){
+ return Promise.resolve(old_values);
+ })
+ }).then(function(old_values){
+ return resource_type_object.encode_field_values(context, values_to_patch, old_values && old_values.body);
+ }).then(function(encoded_values){
+ var query = {};
+ query.last_modified_context = context.toObject();
+ for (var field_name in encoded_values) {
query["body." + field_name] = encoded_values[field_name];
}
- if(Object.keys(query).length==0){
+ if (Object.keys(query).length == 0) {
return Promise.resolve();
- }else{
- return Sealious.Dispatcher.datastore.update("resources", {sealious_id: resource_id}, {$set: query})
+ } else {
+ return Sealious.Dispatcher.datastore.update("resources", {
+ sealious_id: resource_id
+ }, {
+ $set: query
+ })
}
- }).then(function(){
- return self.get_by_id(context, resource_id);
- });
- }
-
- this.update_resource = function(context, type_name, resource_id, new_resource_data){
- //replaces all values. Equivalent of POST request
- var resource_type_object = Sealious.ChipManager.get_chip("resource_type", type_name);
- var get_old_value;
-
- if (resource_type_object.is_old_value_sensitive()){
- get_old_value = self.get_by_id(context, resource_id);
- }else {
- get_old_value = Promise.resolve(null);
- }
-
- return get_old_value.then(function(old_value){
- return resource_type_object.validate_field_values(context,true, new_resource_data, old_value);
- }).then(function(){
- if(new_resource_data.hasOwnProperty("sealious_id")){
- delete new_resource_data.sealious_id;
+ }).then(function(){
+ return self.get_by_id(context, resource_id);
+ });
+ }
+
+ this.update_resource = function(context, type_name, resource_id, body){
+ var type = Sealious.ChipManager.get_chip("resource_type", type_name);
+ for (var i in type.fields) {
+ var field = type.fields[i];
+ if (body[field.name] == undefined) {
+ body[field.name] = null;
}
- if(new_resource_data.hasOwnProperty("id")){
- delete new_resource_data.id;
+ }
+ return this.patch_resource(context, type_name, resource_id, body);
+ }
+
+ this.search = function(context, type, field_name, query_string){
+ query = {
+ body: {}
+ };
+ query["body"][field_name] = new RegExp(query_string, "gi");
+ return new Promise(function(resolve, reject){
+ Sealious.Dispatcher.datastore.find("resources", query)
+ .then(function(documents){
+ var resource_representations = documents.map(function(document){
+ return new ResourceRepresentation(document).getData()
+ });
+ resolve(resource_representations);
+ })
+ })
+ }
+
+ this.search_by_mode = function(context, type, mode){
+ return new Promise(function(resolve, reject){
+ Sealious.Dispatcher.datastore.find("resources", {
+ access_mode: mode,
+ type: type
+ }, {})
+ .then(function(documents){
+ var database_entry = documents;
+ var resource_representations = documents.map(function(document){
+ return new ResourceRepresentation(document).getData()
+ });
+ resolve(resource_representations);
+ });
+ });
+ }
+
+ this.get_resource_type_signature = function(context, type_name){
+ var resource_type_chip = Sealious.ChipManager.get_chip("resource_type", type_name);
+ if (resource_type_chip) {
+ return Promise.resolve(resource_type_chip.get_signature());
+ } else {
+ return Promise.reject(new Sealious.Errors.Error("ResourceManager tried to access resource type `" + type_name + "`, which does not exist."));
+ }
+ }
+
+ /**
+ * Ran before `Sealious.start()` during `npm test`
+ **/
+ this.test_init = function(){
+ // Creating resource always fails
+
+ var always_fails = new Sealious.ChipTypes.FieldType({
+ name: "always_fails",
+ is_proper_value: function(accept, reject, context, value_in_code){
+ reject();
}
-
- /*
- for(var field_name in new_resource_data){
- query["body." + field_name] = new_resource_data[field_name];
+ })
+ var always_fails_resource = new Sealious.ChipTypes.ResourceType({
+ name: "always_fails_resource",
+ fields: [{
+ name: "#fail",
+ type: "always_fails"
+ }]
+ });
+
+
+ //Creating resource never fails
+ var never_fails = new Sealious.ChipTypes.FieldType({
+ name: "never_fails",
+ is_proper_value: function(accept, reject, context, value_in_code){
+ accept();
}
- */
- return Sealious.Dispatcher.datastore.update("resources", {sealious_id: resource_id}, {$set: {body: new_resource_data, last_modified_context: context.toObject()}})
- }).then(function(){
- return self.get_by_id(context, resource_id);
+ })
+
+ var never_fails_resource = new Sealious.ChipTypes.ResourceType({
+ name: "never_fails_resource",
+ fields: [{
+ name: "#success",
+ type: "never_fails"
+ }, ]
});
- }
-
- this.search = function(context, type, field_name, query_string){
- query = {body: {}};
- query["body"][field_name] = new RegExp(query_string, "gi");
- return new Promise(function(resolve, reject){
- Sealious.Dispatcher.datastore.find("resources", query)
- .then(function(documents){
- var resource_representations = documents.map(function(document){return new ResourceRepresentation(document).getData()});
- resolve(resource_representations);
- })
- })
- }
-
- this.search_by_mode = function(context, type, mode){
- return new Promise(function(resolve, reject){
- Sealious.Dispatcher.datastore.find("resources", {access_mode: mode, type: type}, {})
- .then(function(documents){
- var database_entry = documents;
- var resource_representations = documents.map(function(document){
- return new ResourceRepresentation(document).getData()
- });
- resolve(resource_representations);
- });
- });
- }
-
- this.get_resource_type_signature = function(context, type_name){
- return new Promise(function(resolve, reject){
- var resource_type_chip = Sealious.ChipManager.get_chip("resource_type", type_name);
- if(resource_type_chip){
- resolve(resource_type_chip.get_signature());
- }else{
- reject(new Sealious.Errors.Error("ResourceManager tried to access resource type `" + type_name + "`, which does not exist."));
- }
- })
- }
-
- this.test_init = function(){
- // Creating resource always fails
- var always_fails = new Sealious.ChipTypes.FieldType("always_fails");
- always_fails.prototype.isProperValue = function(value_in_code){
- return new Promise(function(resolve, reject){
- reject();
- })
- }
- var always_fails_resource = new Sealious.ChipTypes.ResourceType({
- name: "always_fails_resource",
- fields: [
- {name: "#fail", type: "always_fails"}
- ]
- });
-
-
- //Creating resource never fails
- var never_fails = new Sealious.ChipTypes.FieldType("never_fails");
- never_fails.prototype.isProperValue = function(value_in_code){
- return new Promise(function(resolve,reject){
- resolve();
- })
- }
-
- var never_fails_resource = new Sealious.ChipTypes.ResourceType({
- name: "never_fails_resource",
- fields: [
- {name: "#success", type: "never_fails"},
- ]
- });
- }
-
- this.test_start = function(){
-
- //`describe` is a global method created by Mocha
-
- describe("ResourceManager", function(){
+
+ var requires_old_value = new Sealious.ChipTypes.FieldType({
+ name: "requires_old_value",
+ is_proper_value: function(accept, reject, context, params, new_value, old_value){
+ if (old_value === undefined) {
+ reject("No old value provided!");
+ } else {
+ accept();
+ }
+ },
+ old_value_sensitive_methods: {
+ is_proper_value: true
+ }
+ })
+
+ var rejects_with_old_value = new Sealious.ChipTypes.FieldType({
+ name: "rejects_with_old_value",
+ is_proper_value: function(accept, reject, context, params, new_value, old_value){
+ if (old_value === undefined) {
+ accept();
+ } else {
+ reject("Old value provided");
+ }
+ },
+ old_value_sensitive_methods: {
+ is_proper_value: false
+ }
+ })
+
+ var always_the_same = new Sealious.ChipTypes.FieldType({
+ name: "always_the_same",
+ is_proper_value: function(accept, reject, context, params, new_value, old_value){
+ if (old_value === null) {
+ accept();
+ } else if (new_value == old_value) {
+ accept();
+ } else {
+ reject();
+ }
+ },
+ old_value_sensitive_methods: {
+ is_proper_value: true
+ }
+ })
+
+ var old_value_sensitive_resource = new Sealious.ChipTypes.ResourceType({
+ name: "old_value_sensitive",
+ fields: [{
+ name: "value",
+ type: "requires_old_value"
+ }, ]
+ })
+
+ var old_value_insensitive_resource = new Sealious.ChipTypes.ResourceType({
+ name: "old_value_insensitive",
+ fields: [{
+ name: "value",
+ type: "rejects_with_old_value"
+ }, ]
+ })
+
+ var always_the_same_resource = new Sealious.ChipTypes.ResourceType({
+ name: "always_the_same",
+ fields: [{
+ name: "value",
+ type: "always_the_same"
+ }, ]
+ })
+
+ var multifield_resource = new Sealious.ChipTypes.ResourceType({
+ name: "multifield",
+ fields: [{
+ name: "value1",
+ type: "text"
+ }, {
+ name: "value2",
+ type: "text"
+ }]
+ })
+ }
+
+
+ /**
+ * Ran after `Sealious.start()` during `npm test`
+ **/
+ this.test_start = function(){
+
+ //`describe` is a global method created by Mocha
+
+ describe("ResourceManager", function(){
var context = Sealious.Context();
- it('should not create a new resource', function(done){
- self.create(context, "always_fails_resource", { "#fail": "tak" })
- .then(function(){
- done(new Error("It didn't throw an error!"));
- }).catch(function(error){
- done();
+ describe(".create", function(){
+ it("should provide resource_type.validate_field_values method with the previous field values, if it is needed", function(done){
+ self.create(new Sealious.Context(), "old_value_sensitive", {
+ value: "any"
+ })
+ .then(function(created_resource){
+ done();
+ }).catch(function(){
+ done(new Error("But it didn't"));
+ })
});
- });
- it('should create a new resource', function(done){
- self.create(context, "never_fails_resource", { "#success": "tak" })
- .then(function(result){
- done();
- }).catch(function(error){
- done(error);
+ it("should NOT provide resource_type.validate_field_values method with the previous field value if it's not needed", function(done){
+ self.create(new Sealious.Context(), "old_value_insensitive", {
+ value: "any"
+ })
+ .then(function(){
+ done();
+ }).catch(function(){
+ done(new Error("But it didn't"));
+ })
});
- });
- it('should get data about the resource', function(done){
- self.create(context, "never_fails_resource", { "#success": "tak" })
- .then(function(result){
- return self.get_by_id(context, result.id)
- .then(function(resource){
- done();
+ });
+
+ describe(".update", function(){
+ it("should remove a value if it's not provided", function(done){
+ self.create(new Sealious.Context(), "multifield", {
+ value1: "1",
+ value2: "2"
+ }).then(function(created_resource){
+ return self.update_resource(new Sealious.Context(), "multifield", created_resource.id, {
+ value1: "3"
+ })
+ }).then(function(updated_resource){
+ if (updated_resource.body.value2 === null) {
+ done();
+ } else {
+ done(new Error("But it didn't"));
+ }
})
- }).catch(function(error){
- done(error);
});
- });
- it('should delete the resource', function(done){
- self.create(context, "never_fails_resource", { "#success": "tak" })
- .then(function(result){
- self.delete(context, "never_fails_resource", result.id)
- .then(function(resource){
- done();
+ });
+
+ describe(".patch", function(){
+ it("should provide resource_type.validate_field_values method with the previous field value if it is needed", function(done){
+ self.create(new Sealious.Context(), "old_value_sensitive", {
+ value: "any"
+ })
+ .then(function(created_resource){
+ return self.patch_resource(new Sealious.Context(), "old_value_sensitive", created_resource.id, {
+ value: "any2"
+ })
+ }).then(function(){
+ done();
+ }).catch(function(){
+ done(new Error("But it didn't."));
+ })
+ });
+ describe("should provide real old value, if old_value is needed", function(){
+ it("always_the_same_resource can be patched with the same value it was created", function(done){
+ self.create(new Sealious.Context(), "always_the_same", {
+ value: 33
+ })
+ .then(function(created_resource){
+ return self.patch_resource(new Sealious.Context(), "always_the_same", created_resource.id, {
+ value: 33
+ })
+ }).then(function(){
+ done();
+ }).catch(function(){
+ done(new Error("But it didn't."));
+ })
+ });
+ it("always_the_same_resource can't be patched with other value than the one it was created with", function(done){
+ self.create(new Sealious.Context(), "always_the_same", {
+ value: 33
+ })
+ .then(function(created_resource){
+ return self.patch_resource(new Sealious.Context(), "always_the_same", created_resource.id, {
+ value: 42
+ })
+ }).then(function(){
+ done(new Error("But it was."));
+ }).catch(function(){
+ done();
+ })
+ });
+ })
+ it("should NOT provide resource_type.validate_field_values method with the previous field value if it's not needed", function(done){
+ self.create(new Sealious.Context(), "old_value_insensitive", {
+ value: "any"
+ })
+ .then(function(created_resource){
+ return self.patch_resource(new Sealious.Context(), "old_value_insensitive", created_resource.id, {
+ value: "any2"
+ })
+ .then(function(){
+ done();
+ }).catch(function(){
+ done(new Error("But it didn't"));
+ })
+ })
+ });
+ });
+
+ it('should not create a new resource', function(done){
+ self.create(context, "always_fails_resource", {
+ "#fail": "tak"
+ })
+ .then(function(){
+ done(new Error("It didn't throw an error!"));
}).catch(function(error){
- done(new Error(error));
+ done();
+ });
+ });
+ it('should create a new resource', function(done){
+ self.create(context, "never_fails_resource", {
+ "#success": "tak"
})
- }).catch(function(error){
- done(new Error("It threw an error!"));
- });
- });
- it('should update the resource', function(done){
- self.create(context, "never_fails_resource", { "#success": "tak" })
- .then(function(result){
- self.update_resource(context, "never_fails_resource", result.id, {"#success" : "tak2"})
- .then(function(resource){
- done();
+ .then(function(result){
+ done();
}).catch(function(error){
- done(new Error(error));
+ done(error);
+ });
+ });
+ it('should get data about the resource', function(done){
+ self.create(context, "never_fails_resource", {
+ "#success": "tak"
})
- }).catch(function(error){
- done(error);
- });
- });
- it('should list resources by type', function(done){
+ .then(function(result){
+ return self.get_by_id(context, result.id)
+ .then(function(resource){
+ done();
+ })
+ }).catch(function(error){
+ done(error);
+ });
+ });
+ it('should delete the resource', function(done){
+ self.create(context, "never_fails_resource", {
+ "#success": "tak"
+ })
+ .then(function(result){
+ self.delete(context, "never_fails_resource", result.id)
+ .then(function(resource){
+ done();
+ }).catch(function(error){
+ done(new Error(error));
+ })
+ }).catch(function(error){
+ done(new Error("It threw an error!"));
+ });
+ });
+ it('should list resources by type', function(done){
self.list_by_type(context, "never_fails_resource")
- .then(function(result){
- done();
- }).catch(function(error){
- done(new Error("It threw an error!"));
- });
- });
- it('should get resource type signature (schema)', function(done){
+ .then(function(result){
+ done();
+ }).catch(function(error){
+ done(new Error("It threw an error!"));
+ });
+ });
+ it('should get resource type signature (schema)', function(done){
self.get_resource_type_signature(context, "never_fails_resource")
- .then(function(result){
- done();
- }).catch(function(error){
- done(new Error("It threw an error!"));
- });
- });
-
-
-
- it('should store creation and modification context', function(done){
- var creation_context = new Sealious.Context();
-
- self.create(creation_context, "never_fails_resource", {"#success": "yes"})
- .then(function(created_resource){
- assert.deepEqual(created_resource.created_context, creation_context.toObject(), "Context info stored in resource's `created_context` attribute should reflect the actual context of creating this resource");
- return Promise.resolve(created_resource.id);
- }).then(function(created_resource_id){
- var modification_context = new Sealious.Context();
- return self.patch_resource(modification_context, "never_fails_resource", created_resource_id, {"#success": "yiss"})
- .then(function(patched_resource){
- assert.deepEqual(patched_resource.last_modified_context, modification_context.toObject(), "Context info stored in resource's `last_modified` attribute should reflect the actual context of last modification to this resource after performing `patch` on it.")
- return Promise.resolve(created_resource_id);
- });
- }).then(function(created_resource_id){
- var update_context = new Sealious.Context();
- self.update_resource(update_context, "never_fails_resource", created_resource_id, {"#success": "yiss plis"})
- .then(function(patched_resource){
- assert.deepEqual(patched_resource.last_modified_context, update_context.toObject(), "Context info stored in resource's `last_modified` attribute should reflect the actual context of last modification to this resource after performing `update` on it.")
- });
- done();
- })
- });
-
- //run(); //!!important
- })
-
- }
- }
-
-
- module.exports = ResourceManager;
+ .then(function(result){
+ done();
+ }).catch(function(error){
+ done(new Error("It threw an error!"));
+ });
+ });
+
+
+
+ it('should store creation and modification context', function(done){
+ var creation_context = new Sealious.Context();
+
+ self.create(creation_context, "never_fails_resource", {
+ "#success": "yes"
+ })
+ .then(function(created_resource){
+ assert.deepEqual(created_resource.created_context, creation_context.toObject(), "Context info stored in resource's `created_context` attribute should reflect the actual context of creating this resource");
+ return Promise.resolve(created_resource.id);
+ }).then(function(created_resource_id){
+ var modification_context = new Sealious.Context();
+ return self.patch_resource(modification_context, "never_fails_resource", created_resource_id, {
+ "#success": "yiss"
+ })
+ .then(function(patched_resource){
+ assert.deepEqual(patched_resource.last_modified_context, modification_context.toObject(), "Context info stored in resource's `last_modified` attribute should reflect the actual context of last modification to this resource after performing `patch` on it.")
+ return Promise.resolve(created_resource_id);
+ });
+ }).then(function(created_resource_id){
+ var update_context = new Sealious.Context();
+ self.update_resource(update_context, "never_fails_resource", created_resource_id, {
+ "#success": "yiss plis"
+ })
+ .then(function(patched_resource){
+ assert.deepEqual(patched_resource.last_modified_context, update_context.toObject(), "Context info stored in resource's `last_modified` attribute should reflect the actual context of last modification to this resource after performing `update` on it.")
+ });
+ done();
+ })
+ });
+
+ run(); //!!important
+ })
+
+ }
+}
+
+
+module.exports = ResourceManager;
\ No newline at end of file
diff --git a/lib/core-services/user_manager.js b/lib/core-services/user_manager.js
index d91cb79b..e1def61c 100644
--- a/lib/core-services/user_manager.js
+++ b/lib/core-services/user_manager.js
@@ -1,82 +1,97 @@
var Sealious = require("../main.js");
var Promise = require("bluebird");
module.exports = new function(){
this.name = "users";
this.create_user = function(context, username, password){
var user_data;
return Sealious.Dispatcher.users.user_exists(context, username)
- .then(function(user_exists){
- if (!user_exists){
- Sealious.Logger.info("User " + username +" has been created");
- return Sealious.Dispatcher.resources.create(context, "user", {username: username, password:password});
- }else{
- throw new Sealious.Errors.ValueExists("Username `" + username + "` is already taken.");
- }
- })
+ .then(function(user_exists){
+ if (!user_exists) {
+ Sealious.Logger.info("User " + username + " has been created");
+ return Sealious.Dispatcher.resources.create(context, "user", {
+ username: username,
+ password: password
+ });
+ } else {
+ throw new Sealious.Errors.ValueExists("Username `" + username + "` is already taken.");
+ }
+ })
}
this.user_exists = function(context, username){
return new Promise(function(resolve, reject){
- Sealious.Dispatcher.resources.find({username: username}, "user")
- .then(function(matched_documents){
- resolve(matched_documents.length===1);
- });
+ Sealious.Dispatcher.resources.find({
+ username: username
+ }, "user")
+ .then(function(matched_documents){
+ resolve(matched_documents.length === 1);
+ });
})
}
this.password_match = function(context, username, password){
return new Promise(function(resolve, reject){
if (!username && !password) {
var err = new Sealious.Errors.InvalidCredentials("Missing username and password!");
reject(err);
} else if (!password) {
var err = new Sealious.Errors.InvalidCredentials("Missing password!");
reject(err);
} else if (!username) {
var err = new Sealious.Errors.InvalidCredentials("Missing username!");
reject(err);
} else {
- var query = {type: "user", body: {username: username, password: password}};
- Sealious.Dispatcher.datastore.find("resources", query)
- .then(function(result){
- if(result[0]){
- resolve(result[0].sealious_id);
- }else{
- var err = new Sealious.Errors.InvalidCredentials("Wrong username or password!");
- reject(err);
+ var query = {
+ type: "user",
+ body: {
+ username: username,
+ password: password
}
- })
- }
+ };
+ Sealious.Dispatcher.datastore.find("resources", query)
+ .then(function(result){
+ if (result[0]) {
+ resolve(result[0].sealious_id);
+ } else {
+ var err = new Sealious.Errors.InvalidCredentials("Wrong username or password!");
+ reject(err);
+ }
+ })
+ }
})
}
this.get_all_users = function(context){
- return Sealious.Dispatcher.datastore.find("resources", {type: "user"});
+ return Sealious.Dispatcher.datastore.find("resources", {
+ type: "user"
+ });
}
this.get_user_data = function(context, user_resource_id){
- try{
+ try {
var ret = Sealious.Dispatcher.resources.get_by_id(context, user_resource_id);
- }catch(err){
+ } catch (err) {
throw err;
}
return ret;
}
this.update_user_data = function(context, user_id, new_user_data){
return Sealious.Dispatcher.resources.update_resource(user_id, new_user_data);
}
this.delete_user = function(context, user_id){
- return new Promise(function(resolve, reject){
- Sealious.Dispatcher.datastore.delete("resources", {sealious_id: user_id})
- .then(function(data){
- resolve(data);
- }).catch(function(e){
- reject(e);
- });
+ return new Promise(function(resolve, reject){
+ Sealious.Dispatcher.datastore.delete("resources", {
+ sealious_id: user_id
+ })
+ .then(function(data){
+ resolve(data);
+ }).catch(function(e){
+ reject(e);
+ });
});
}
-}
+}
\ No newline at end of file
diff --git a/lib/core.js b/lib/core.js
index 3b0dd48c..9815d13f 100644
--- a/lib/core.js
+++ b/lib/core.js
@@ -1,74 +1,74 @@
var Sealious = require("./main.js");
var path = require("path");
var http = require("http");
var ConfigManager = require("./config/config-manager.js");
-var SealiousCore = new function() {
+var SealiousCore = new function(){
- this.check_version = function(package_info) {
- var pkg = require("../package.json")
- var pkg_split = pkg.version.split(".");
- var version = pkg_split[0] + "." + pkg_split[1];
- var url = "http://registry.npmjs.org/sealious/" + version;
+ this.check_version = function(package_info){
+ var pkg = require("../package.json")
+ var pkg_split = pkg.version.split(".");
+ var version = pkg_split[0] + "." + pkg_split[1];
+ var url = "http://registry.npmjs.org/sealious/" + version;
- var check_request = http.get(url, function(res) {
- res.setEncoding('utf8');
- var body = "";
- res.on('data', function(chunk) {
- body += chunk.toString();
- });
- res.on('end', function() {
- try{
- var sealious_npm = JSON.parse(body);
- }catch(error){
- Sealious.Logger.error(new Sealious.Errors.Error("Could not fetch update information from NPM registry."));
- }
- var sealious_npm_array = sealious_npm.version.split(".");
+ var check_request = http.get(url, function(res){
+ res.setEncoding('utf8');
+ var body = "";
+ res.on('data', function(chunk){
+ body += chunk.toString();
+ });
+ res.on('end', function(){
+ try {
+ var sealious_npm = JSON.parse(body);
+ } catch (error) {
+ Sealious.Logger.error(new Sealious.Errors.Error("Could not fetch update information from NPM registry."));
+ }
+ var sealious_npm_array = sealious_npm.version.split(".");
- if ((sealious_npm.version !== pkg.version) && (parseInt(sealious_npm_array[2]) > parseInt(pkg_split[2]))) {
- Sealious.Logger.warning("Sealious@" + pkg.version + " - update available. Run `npm install sealious@" + sealious_npm.version + "` to update.");
- } else {
- Sealious.Logger.info("Sealious@" + pkg.version + " is up-to-date.");
- }
- });
- });
- check_request.on('error', function (err) {
- Sealious.Logger.warning("No network connection available! Unable to fetch information about updates to Sealious.");
+ if ((sealious_npm.version !== pkg.version) && (parseInt(sealious_npm_array[2]) > parseInt(pkg_split[2]))) {
+ Sealious.Logger.warning("Sealious@" + pkg.version + " - update available. Run `npm install sealious@" + sealious_npm.version + "` to update.");
+ } else {
+ Sealious.Logger.info("Sealious@" + pkg.version + " is up-to-date.");
+ }
+ });
});
+ check_request.on('error', function(err){
+ Sealious.Logger.warning("No network connection available! Unable to fetch information about updates to Sealious.");
+ });
+
+ }
- }
+ this.which_chip_types_to_start_for_layer = {
+ db: ["datastore"],
+ biz: ["field_type", "resource_type", "service"],
+ web: ["field_type", "resource_type", "channel"]
+ }
- this.which_chip_types_to_start_for_layer = {
- db: ["datastore"],
- biz: ["field_type", "resource_type", "service"],
- web: ["field_type", "resource_type", "channel"]
- }
+ this.config = function(config_object){
+ ConfigManager.set_config(config_object);
+ }
- this.config = function(config_object) {
- ConfigManager.set_config(config_object);
- }
-
- this.decide_chip_types_to_start = function(mode, layer_name) {
- if (mode == "local") {
- return ["field_type", "resource_type", "service", "channel", "datastore"];
- //}else if(!(layer_name)){
- // throw new Sealious.Errors.ValidationError("Invalid layer name: " + layer_name); //~
- } else {
- return which_chip_types_to_start_for_layer[layer_name];
- }
- }
+ this.decide_chip_types_to_start = function(mode, layer_name){
+ if (mode == "local") {
+ return ["field_type", "resource_type", "service", "channel", "datastore"];
+ //}else if(!(layer_name)){
+ // throw new Sealious.Errors.ValidationError("Invalid layer name: " + layer_name); //~
+ } else {
+ return which_chip_types_to_start_for_layer[layer_name];
+ }
+ }
- this.get_dispatcher = function(mode, layer_name) {
- if (mode == "local") {
- var dispatcher_path = "./dispatchers/local/dispatcher-local.js";
- } else {
- var dispatcher_path = "./dispatchers/" + layer_name + "/dispatcher-" + layer_name + ".js";
- }
- return require(dispatcher_path);
- }
+ this.get_dispatcher = function(mode, layer_name){
+ if (mode == "local") {
+ var dispatcher_path = "./dispatchers/local/dispatcher-local.js";
+ } else {
+ var dispatcher_path = "./dispatchers/" + layer_name + "/dispatcher-" + layer_name + ".js";
+ }
+ return require(dispatcher_path);
+ }
}
module.exports = SealiousCore;
\ No newline at end of file
diff --git a/lib/data-structures/field-type-description.js b/lib/data-structures/field-type-description.js
new file mode 100644
index 00000000..e1a5f4c6
--- /dev/null
+++ b/lib/data-structures/field-type-description.js
@@ -0,0 +1,7 @@
+var FieldTypeDescription = function(summary, raw_params, extra_info){
+ this.summary = summary;
+ this.raw_params = raw_params;
+ this.extra_info = extra_info || {};
+}
+
+module.exports = FieldTypeDescription;
\ No newline at end of file
diff --git a/lib/data-structures/file.js b/lib/data-structures/file.js
index 546969b8..8a516018 100644
--- a/lib/data-structures/file.js
+++ b/lib/data-structures/file.js
@@ -1,31 +1,32 @@
var Sealious = require("../main.js");
-function File(creation_context, filename, data, id, mime){
+function File (creation_context, filename, data, id, mime) {
this.filename = filename;
this.data = data;
this.id = id || null;
this.mime = mime || false;
}
File.from_id = function(context, file_id){
- return Sealious.Dispatcher.files.find(context, {id: file_id})
- .then(function(file_array){
- return Promise.resolve(file_array[0]);
- });
+ return Sealious.Dispatcher.files.find(context, {
+ id: file_id
+ })
+ .then(function(file_array){
+ return Promise.resolve(file_array[0]);
+ });
}
File.from_db_entry = function(db_document, upload_path){
return new File(db_document.creation_context, db_document.original_name, db_document.data, db_document.id, db_document.mime_type);
}
File.prototype = new function(){
this.data_structure = "file";
}
File.Reference = function(id, filename){
this.id = id;
this.filename = filename;
}
-module.exports = File;
-
+module.exports = File;
\ No newline at end of file
diff --git a/lib/dispatchers/biz/dispatcher-biz.js b/lib/dispatchers/biz/dispatcher-biz.js
index 2a3a45eb..2bc4ff2e 100644
--- a/lib/dispatchers/biz/dispatcher-biz.js
+++ b/lib/dispatchers/biz/dispatcher-biz.js
@@ -1,16 +1,16 @@
var DispatcherDistributed = require("../dispatcher-distributed.js");
var DispatcherDistributedBIZ = new DispatcherDistributed("biz");
-DispatcherDistributedBIZ.process_core_service_method = function(service, service_name, method_name) {
- return service[method_name].bind(service);
+DispatcherDistributedBIZ.process_core_service_method = function(service, service_name, method_name){
+ return service[method_name].bind(service);
}
-DispatcherDistributedBIZ.process_datastore_method = function(datastore, method_name) {
- return function(){
- return this.call_over_socket("datastore."+ method_name, arguments);
- }.bind(this);
+DispatcherDistributedBIZ.process_datastore_method = function(datastore, method_name){
+ return function(){
+ return this.call_over_socket("datastore." + method_name, arguments);
+ }.bind(this);
}
-module.exports = DispatcherDistributedBIZ;
+module.exports = DispatcherDistributedBIZ;
\ No newline at end of file
diff --git a/lib/dispatchers/db/dispatcher-db.js b/lib/dispatchers/db/dispatcher-db.js
index 3f3d40fa..feaa0507 100644
--- a/lib/dispatchers/db/dispatcher-db.js
+++ b/lib/dispatchers/db/dispatcher-db.js
@@ -1,16 +1,16 @@
var DispatcherDistributed = require("../dispatcher-distributed.js");
var DispatcherDistributedDB = new DispatcherDistributed("db");
-DispatcherDistributedDB.process_core_service_method = function(service, service_name, method_name) {
- return function(){
- throw new Sealious.Errors.Error("DispatcherDistributedDB tried to call a core-service method, which is not allowed.")
- }
+DispatcherDistributedDB.process_core_service_method = function(service, service_name, method_name){
+ return function(){
+ throw new Sealious.Errors.Error("DispatcherDistributedDB tried to call a core-service method, which is not allowed.")
+ }
}
-DispatcherDistributedDB.process_datastore_method = function(datastore, method_name) {
- return datastore[method_name];
+DispatcherDistributedDB.process_datastore_method = function(datastore, method_name){
+ return datastore[method_name];
}
-module.exports = DispatcherDistributedDB;
+module.exports = DispatcherDistributedDB;
\ No newline at end of file
diff --git a/lib/dispatchers/dispatcher-distributed.js b/lib/dispatchers/dispatcher-distributed.js
index ed5abf6b..1147a3e3 100644
--- a/lib/dispatchers/dispatcher-distributed.js
+++ b/lib/dispatchers/dispatcher-distributed.js
@@ -1,155 +1,158 @@
var io_server = require('socket.io');
var io_client = require('socket.io-client');
var Dispatcher = require("./dispatcher.js");
var ConfigManager = require("../config/config-manager.js");
DispatcherDistributed = function(layer_name){
this.callback_queue = {};
this.error_queue = {};
this.socket_client = null;
this.socket_server = null;
this.max_request_id = 0;
this.layer_name = layer_name;
ConfigManager.set_default_config(
- "layer_config",
- {
- "db":{
+ "layer_config", {
+ "db": {
"host": "localhost",
"port": "7766"
},
- "biz":{
+ "biz": {
"host": "localhost",
"port": "7767"
}
}
);
}
DispatcherDistributed.prototype = Object.create(Dispatcher.prototype);
DispatcherDistributed.prototype.get_request_id = function(){
- this.max_request_id+=1;
+ this.max_request_id += 1;
return this.max_request_id;
}
DispatcherDistributed.prototype.add_callback_to_queue = function(id, callback, error_handler){
this.callback_queue[id] = callback;
this.error_queue[id] = error_handler;
}
DispatcherDistributed.prototype.resolve_to_callback = function(response_data){
var callback = this.callback_queue[response_data.request_id];
callback(response_data.payload);
delete this.callback_queue[response_data.request_id];
delete this.error_queue[response_data.request_id];
}
DispatcherDistributed.prototype.resolve_to_error = function(response_error){
var error_handler = this.error_queue[response_error.request_id];
- if(error_handler){
- error_handler(response_error);
+ if (error_handler) {
+ error_handler(response_error);
}
delete this.callback_queue[response_error.request_id];
delete this.error_queue[response_error.request_id];
}
DispatcherDistributed.prototype.call_over_socket = function(method_name, args){
var id = this.get_request_id();
this.socket_client.emit("request", {
method_name: method_name,
arguments: args,
request_id: id
});
return new Promise(function(resolve, reject){
- this.add_callback_to_queue(id,
+ this.add_callback_to_queue(id,
function(data){
resolve(data);
- },
+ },
function(error){
Sealious.Logger.error(error);
reject(new Sealious.Errors.Error(error.error.status_message, error.error));
}
);
}.bind(this))
-}
+}
DispatcherDistributed.prototype.connect_to_layer = function(layer_name){
var layer_config = ConfigManager.get_config().layer_config;
- if(layer_config[layer_name]==undefined){
+ if (layer_config[layer_name] == undefined) {
throw new Sealious.Errors.Error("Dispatcher tried to connect to layer of name `" + layer_name + "`, but this layer was not found in config.json.");
}
var the_other_layer_config = layer_config[layer_name];
var connection_url = "http://" + the_other_layer_config.host + ":" + the_other_layer_config.port;
- this.socket_client = io_client.connect(connection_url, {reconnect: true});
+ this.socket_client = io_client.connect(connection_url, {
+ reconnect: true
+ });
this.socket_client.on("response", function(data){
this.resolve_to_callback(data);
}.bind(this));
this.socket_client.on("throw_error", function(data){
this.resolve_to_error(data);
- }.bind(this));
+ }.bind(this));
}
DispatcherDistributed.prototype.listen = function(){
var that = this;
this.socket_server = io_server();
var cfg = ConfigManager.get_config().layer_config[this.layer_name];
this.socket_server.listen(cfg.port);
Sealious.Logger.info(this.layer_name.toUpperCase() + " layer listening on port: " + cfg.port + "\n");
- this.socket_server.on('connection', function(socket) {
+ this.socket_server.on('connection', function(socket){
Sealious.Logger.info("A layer from above connected");
- socket.on("request", function(data) {
- var method_name = data.method_name;
- var arguments = data.arguments;
- var arguments_array = Object.keys(arguments).map(function (key) {return data.arguments[key]});
- var request_id = data.request_id;
-
- var method_path = method_name.split(".");
- var method_to_call = that;
- for (var i = 0; i < method_path.length; i++) {
- method_to_call = method_to_call[method_path[i]];
- };
-
- method_to_call.apply(that, arguments_array)
- .then(function(result) {
- var response = {};
- response.request_id = request_id;
- response.payload = result;
- socket.emit("response", response);
- }).catch(function(err) {
- Sealious.Logger.error(err);
- var response = {};
- response.type = "error";
- response.error = err;
- response.request_id = request_id;
- socket.emit("throw_error", response);
- });
- });
- socket.on('logout', function() {
- Sealious.Logger.info("Logging out.");
- socket.disconnect(); // zamknięcie połączenia
- });
- socket.on('disconnect', function() {
- Sealious.Logger.info("Upper layer disconnected"); // event rozłączenia
- });
+ socket.on("request", function(data){
+ var method_name = data.method_name;
+ var arguments = data.arguments;
+ var arguments_array = Object.keys(arguments).map(function(key){
+ return data.arguments[key]
+ });
+ var request_id = data.request_id;
+
+ var method_path = method_name.split(".");
+ var method_to_call = that;
+ for (var i = 0; i < method_path.length; i++) {
+ method_to_call = method_to_call[method_path[i]];
+ };
+
+ method_to_call.apply(that, arguments_array)
+ .then(function(result){
+ var response = {};
+ response.request_id = request_id;
+ response.payload = result;
+ socket.emit("response", response);
+ }).catch(function(err){
+ Sealious.Logger.error(err);
+ var response = {};
+ response.type = "error";
+ response.error = err;
+ response.request_id = request_id;
+ socket.emit("throw_error", response);
+ });
+ });
+ socket.on('logout', function(){
+ Sealious.Logger.info("Logging out.");
+ socket.disconnect(); // zamknięcie połączenia
+ });
+ socket.on('disconnect', function(){
+ Sealious.Logger.info("Upper layer disconnected"); // event rozłączenia
+ });
});
}
DispatcherDistributed.prototype.layer_order = ["web", "biz", "db"]
DispatcherDistributed.prototype.start = function(){
var current_layer_index = this.layer_order.indexOf(this.layer_name);
- if(this.layer_order[current_layer_index+1]!=undefined){ //if we're not on the bottom-most layer
- this.connect_to_layer(this.layer_order[current_layer_index+1])
+ if (this.layer_order[current_layer_index + 1] != undefined) { //if we're not on the bottom-most layer
+ this.connect_to_layer(this.layer_order[current_layer_index + 1])
}
- if(this.layer_order[current_layer_index-1]!=undefined){
+ if (this.layer_order[current_layer_index - 1] != undefined) {
this.listen();
}
}
module.exports = DispatcherDistributed;
\ No newline at end of file
diff --git a/lib/dispatchers/dispatcher.js b/lib/dispatchers/dispatcher.js
index ee34dca2..cb392f0c 100644
--- a/lib/dispatchers/dispatcher.js
+++ b/lib/dispatchers/dispatcher.js
@@ -1,64 +1,64 @@
var Sealious = require("../main.js");
var ResourceManager = Sealious.ResourceManager;
var ChipManager = require("../chip-types/chip-manager.js");
var FileManager = require("../core-services/file-manager.js");
var fs = require("fs");
var path = require("path");
-Dispatcher = function() {
- this.datastore_chip = null;
+Dispatcher = function(){
+ this.datastore_chip = null;
}
-Dispatcher.prototype = new function() {
+Dispatcher.prototype = new function(){
- this.set_datastore = function(datastore_chip) {
- this.datastore_chip = datastore_chip;
- }
+ this.set_datastore = function(datastore_chip){
+ this.datastore_chip = datastore_chip;
+ }
- this.init = function() {
- this.set_datastore(ChipManager.get_datastore_chip());
- this.process_all_core_service_methods();
- this.process_all_datastore_methods();
- }
+ this.init = function(){
+ this.set_datastore(ChipManager.get_datastore_chip());
+ this.process_all_core_service_methods();
+ this.process_all_datastore_methods();
+ }
- this.start = function() {};
+ this.start = function(){};
- this.process_all_core_service_methods = function() {
- var core_services_path = path.resolve(module.filename, "../../core-services/");
- var services_filenames = fs.readdirSync(core_services_path);
+ this.process_all_core_service_methods = function(){
+ var core_services_path = path.resolve(module.filename, "../../core-services/");
+ var services_filenames = fs.readdirSync(core_services_path);
- for(var i in services_filenames){
- var filename = services_filenames[i];
- var service = require("../core-services/" + filename);
+ for (var i in services_filenames) {
+ var filename = services_filenames[i];
+ var service = require("../core-services/" + filename);
- if (this.process_core_service_method) {
- this[service.name] = Object.create(service);
- for (var method_name in service) {
- if (service[method_name] instanceof Function) {
- this[service.name][method_name] = this.process_core_service_method(service, service.name, method_name);
- }
- }
- } else {
- throw new Sealious.Errors.Error("Dispatcher should implement `process_core_service_method`");
- }
+ if (this.process_core_service_method) {
+ this[service.name] = Object.create(service);
+ for (var method_name in service) {
+ if (service[method_name] instanceof Function) {
+ this[service.name][method_name] = this.process_core_service_method(service, service.name, method_name);
+ }
+ }
+ } else {
+ throw new Sealious.Errors.Error("Dispatcher should implement `process_core_service_method`");
+ }
- }
- }
+ }
+ }
- this.process_all_datastore_methods = function() {
- if (this.process_datastore_method) {
- this.datastore = {};
- for (var method_name in this.datastore_chip) {
- if (this.datastore_chip[method_name] instanceof Function) {
- this.datastore[method_name] = this.process_datastore_method(this.datastore_chip, method_name);
- }
- }
- } else {
- throw new Sealious.Errors.Error("Dispatcher should implement `process_datastore_method`");
- }
- }
+ this.process_all_datastore_methods = function(){
+ if (this.process_datastore_method) {
+ this.datastore = {};
+ for (var method_name in this.datastore_chip) {
+ if (this.datastore_chip[method_name] instanceof Function) {
+ this.datastore[method_name] = this.process_datastore_method(this.datastore_chip, method_name);
+ }
+ }
+ } else {
+ throw new Sealious.Errors.Error("Dispatcher should implement `process_datastore_method`");
+ }
+ }
}
-module.exports = Dispatcher;
+module.exports = Dispatcher;
\ No newline at end of file
diff --git a/lib/dispatchers/local/dispatcher-local.js b/lib/dispatchers/local/dispatcher-local.js
index 7cf834b3..b602442f 100644
--- a/lib/dispatchers/local/dispatcher-local.js
+++ b/lib/dispatchers/local/dispatcher-local.js
@@ -1,18 +1,18 @@
-var Promise = require("bluebird");
+var Promise = require("bluebird");
-var Dispatcher = require("../dispatcher.js");
+var Dispatcher = require("../dispatcher.js");
-var DispatcherLocal= Object.create(Dispatcher.prototype);
+var DispatcherLocal = Object.create(Dispatcher.prototype);
DispatcherLocal.process_core_service_method = function(service, service_name, method_name){
- return service[method_name].bind(service);
+ return service[method_name].bind(service);
}
DispatcherLocal.process_datastore_method = function(datastore_chip, method_name){
return datastore_chip[method_name].bind(datastore_chip);
}
-module.exports = DispatcherLocal;
+module.exports = DispatcherLocal;
\ No newline at end of file
diff --git a/lib/dispatchers/web/dispatcher-web.js b/lib/dispatchers/web/dispatcher-web.js
index c91a1425..5bd214bd 100644
--- a/lib/dispatchers/web/dispatcher-web.js
+++ b/lib/dispatchers/web/dispatcher-web.js
@@ -1,17 +1,17 @@
var DispatcherDistributed = require("../dispatcher-distributed.js");
var DispatcherDistributedWEB = new DispatcherDistributed("web");
DispatcherDistributedWEB.process_core_service_method = function(service, service_name, method_name){
return function(){
return this.call_over_socket(service_name + "." + method_name, arguments);
}.bind(this);
}
DispatcherDistributedWEB.process_datastore_method = function(datastore, method_name){
return function(){
- return this.call_over_socket("datastore." + method_name, arguments);
+ return this.call_over_socket("datastore." + method_name, arguments);
}.bind(this);
}
-module.exports = DispatcherDistributedWEB;
+module.exports = DispatcherDistributedWEB;
\ No newline at end of file
diff --git a/lib/logger/logger.js b/lib/logger/logger.js
index 6c5322ad..39efad70 100644
--- a/lib/logger/logger.js
+++ b/lib/logger/logger.js
@@ -1,119 +1,136 @@
var Sealious = require("../main.js");
var winston = require('winston');
var ConfigManager = Sealious.ConfigManager;
/*
This is the default configration of Sealious logger.
To retrieve a specifig setting, use "get_config()" function, ex. "ConfigManager.get_config().logger_config.logger_level".
@logger_level - specifies from which log level (displayed below) onward should be displayed,
@logger_color - specifies if the log should be colorized, values "true" or "false"
@logger_file - defines a filename to save the logs, if a falsy value is given the logs will not be saved,
@logger_dirname - defines a default path to save the logs,
@logger_to_json - specifies the format of the saved logs,
@logger_rotation - defines the log rotation format, set to daily by default
*/
ConfigManager.set_default_config(
- "logger_config",
- {
- logger_level : "info",
- logger_color : true,
- logger_file : null,
- logger_dirname: ".",
- logger_to_json: false,
- logger_rotation: '.yyyy-MM-Tdd'
-});
+ "logger_config", {
+ logger_level: "info",
+ logger_color: true,
+ logger_file: null,
+ logger_dirname: ".",
+ logger_to_json: false,
+ logger_rotation: '.yyyy-MM-Tdd'
+ });
/*
This is the custom logger level and color configuration.
@levels - default logger levels, 0 being the lowest importance, 4 being the highest:
* lazyseal - an Easter, or should we say: Sealious egg. Used only for humorous reasons, the lowest level of importance, default color: white,
* info - used for stating the current status or general information such as starting the server, default color: green,
* debug - used for debugging, default color: blue,
* warning - used to display warnings, default color: yellow,
* error - used to display errors, default color: red
*/
var custom = {
- levels: {
- lazyseal: 0,
- info: 1,
- debug: 2,
- warning: 3,
- error: 4,
- no_output: 5
- },
- colors: {
- lazyseal: "white",
- info: "green",
- debug: 'blue',
- warning: 'yellow',
- error: 'red'
- }
+ levels: {
+ lazyseal: 0,
+ info: 1,
+ debug: 2,
+ warning: 3,
+ error: 4,
+ no_output: 5
+ },
+ colors: {
+ lazyseal: "white",
+ info: "green",
+ debug: 'blue',
+ warning: 'yellow',
+ error: 'red'
+ }
};
/*
Returns the current date and time, default format: "yyyy-mm-dd hh:mm:ss.mmm", ex. "2000-01-01 20:00:00.000"
*/
-function getDateTime(with_date) {
+function getDateTime (with_date) {
- var date = new Date();
+ var date = new Date();
- var hour = date.getHours();
- hour = (hour < 10 ? "0" : "") + hour;
+ var hour = date.getHours();
+ hour = (hour < 10 ? "0" : "") + hour;
- var min = date.getMinutes();
- min = (min < 10 ? "0" : "") + min;
+ var min = date.getMinutes();
+ min = (min < 10 ? "0" : "") + min;
- var sec = date.getSeconds();
- sec = (sec < 10 ? "0" : "") + sec;
+ var sec = date.getSeconds();
+ sec = (sec < 10 ? "0" : "") + sec;
- var milli = date.getMilliseconds();
- milli = (milli < 10 ? "00" : "") + milli;
- milli = (milli < 100 && milli >=10 ? "0" : "") + milli;
+ var milli = date.getMilliseconds();
+ milli = (milli < 10 ? "00" : "") + milli;
+ milli = (milli < 100 && milli >= 10 ? "0" : "") + milli;
- var year = date.getFullYear();
+ var year = date.getFullYear();
- var month = date.getMonth() + 1;
- month = (month < 10 ? "0" : "") + month;
+ var month = date.getMonth() + 1;
+ month = (month < 10 ? "0" : "") + month;
- var day = date.getDate();
- day = (day < 10 ? "0" : "") + day;
+ var day = date.getDate();
+ day = (day < 10 ? "0" : "") + day;
- if (!with_date) { return hour + ":" + min + ":" + sec + "." + milli; }
- else { return year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + sec + "." + milli; }
+ if (!with_date) {
+ return hour + ":" + min + ":" + sec + "." + milli;
+ } else {
+ return year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + sec + "." + milli;
+ }
}
var transports_array = new Array();
var logger_level = ConfigManager.get_config().logger_config.logger_level;
var logger_color = ConfigManager.get_config().logger_config.logger_color;
var logger_file = ConfigManager.get_config().logger_config.logger_file;
var logger_dirname = ConfigManager.get_config().logger_config.logger_dirname;
var logger_to_json = ConfigManager.get_config().logger_config.logger_to_json;
var logger_rotation = ConfigManager.get_config().logger_config.logger_rotation;
-var winston_level = new (winston.transports.Console)({ level: logger_level, colorize: logger_color, timestamp: function() { return getDateTime(false); } });
+var winston_level = new(winston.transports.Console)({
+ level: logger_level,
+ colorize: logger_color,
+ timestamp: function(){
+ return getDateTime(false);
+ }
+});
transports_array.push(winston_level);
if (logger_file) {
- var winston_save_to_file = new (winston.transports.File)({ filename: logger_file, colorize: logger_color, timestamp: function() { return getDateTime(true); }, dirname: logger_dirname, json: logger_to_json });
- var winston_daily_rotate = new (winston.transports.DailyRotateFile)( { filename : logger_file, datePattern: logger_rotation });
- transports_array.push(winston_save_to_file);
- transports_array.push(winston_daily_rotate);
+ var winston_save_to_file = new(winston.transports.File)({
+ filename: logger_file,
+ colorize: logger_color,
+ timestamp: function(){
+ return getDateTime(true);
+ },
+ dirname: logger_dirname,
+ json: logger_to_json
+ });
+ var winston_daily_rotate = new(winston.transports.DailyRotateFile)({
+ filename: logger_file,
+ datePattern: logger_rotation
+ });
+ transports_array.push(winston_save_to_file);
+ transports_array.push(winston_daily_rotate);
}
-var logger = new winston.Logger(
- {
- levels: custom.levels,
- colors: custom.colors,
- transports: transports_array
- }
-);
+var logger = new winston.Logger({
+ levels: custom.levels,
+ colors: custom.colors,
+ transports: transports_array
+});
module.exports = logger;
\ No newline at end of file
diff --git a/lib/main.js b/lib/main.js
index a82386de..952e8266 100644
--- a/lib/main.js
+++ b/lib/main.js
@@ -1,66 +1,75 @@
var path = require("path");
var Sealious = {};
module.exports = Sealious;
var core_instance = null;
var Core = require("./core.js");
-Sealious.Errors = require("./response/error.js");
+Sealious.Errors = require("./response/error.js");
Sealious.Response = require("./response/response.js");
Sealious.File = require("./data-structures/file.js");
Sealious.ChipManager = require("./chip-types/chip-manager.js");
Sealious.ConfigManager = require("./config/config-manager.js");
Sealious.PluginManager = require("./plugins/plugin-manager.js");
Sealious.Dispatcher = null;
Sealious.Context = require("./context.js");
Sealious.ResourceManager = require("./core-services/resource-manager.js");
Sealious.ChipTypes = {
"AccessStrategy": require("./chip-types/access-strategy.js"),
"Channel": require("./chip-types/channel.js"),
"Datastore": require("./chip-types/datastore.js"),
"FieldType": require("./chip-types/field-type.js"),
"ResourceType": require("./chip-types/resource-type.js"),
}
-for(var chip_type_name in Sealious.ChipTypes){
- Sealious.ChipTypes[chip_type_name] = Sealious.ChipTypes[chip_type_name].bind(Sealious.ChipTypes[chip_type_name], null); //null here corresponds to "module_path" of chip's constructor
+for (var chip_type_name in Sealious.ChipTypes) {
+ //Sealious.ChipTypes[chip_type_name] = Sealious.ChipTypes[chip_type_name].bind(Sealious.ChipTypes[chip_type_name], null); //null here corresponds to "module_path" of chip's constructor
}
Sealious.init = function(mode, layer_name){
Sealious.Logger = require("./logger/logger.js");
require("./base-chips/_base-chips.js");
Sealious.PluginManager.load_plugins();
this.mode = mode ? mode : "local";
this.layer_name = layer_name ? layer_name : null;
}
Sealious.start = function(){
Core.check_version();
var dispatcher = Core.get_dispatcher(this.mode, this.layer_name);
dispatcher.init();
dispatcher.start();
Sealious.Dispatcher = dispatcher;
var chip_types_to_start = Core.decide_chip_types_to_start(this.mode, this.layer_name);
return Sealious.ChipManager.start_chips(chip_types_to_start);
}
Sealious.test = function(){
- var ResourceManager = Sealious.ResourceManager;
+ var things_to_test = [
+ Sealious.ResourceManager,
+ Sealious.ChipTypes.FieldType,
+ require("./chip-types/resource-type-field"),
+ ]
Sealious.init();
- ResourceManager.test_init();
+
+ things_to_test.forEach(function(thing){
+ thing.test_init && thing.test_init();
+ })
Sealious.start().then(function(){
- ResourceManager.test_start();
- run(); //function created by Mocha. Present only if Mocha is run with --delay option from the command line
+ things_to_test.forEach(function(thing){
+ thing.test_start && thing.test_start();
+ })
+ run(); //function created by Mocha. Present only if Mocha is run with --delay option from the command line (as it is when running `npm test`)
})
}
module.exports = Sealious;
\ No newline at end of file
diff --git a/lib/response/error.js b/lib/response/error.js
index 97732bfc..04bf6b14 100644
--- a/lib/response/error.js
+++ b/lib/response/error.js
@@ -1,120 +1,120 @@
var Response = require("./response.js");
var SealiousErrors = {};
SealiousErrors.Error = function(message, params, data){
var ret = new Error(message);
params = params || {};
ret.is_sealious_error = true;
ret.status_message = message;
ret.is_error = true;
- ret.is_user_fault = params.is_user_fault===undefined? false : params.is_user_fault;
- ret.is_developer_fault = params.is_developer_fault===undefined? false : params.is_developer_fault;
- ret.type = params.type===undefined? "error" : params.type;
- ret.http_code = params.http_code===undefined? 500 : params.http_code;
+ ret.is_user_fault = params.is_user_fault === undefined ? false : params.is_user_fault;
+ ret.is_developer_fault = params.is_developer_fault === undefined ? false : params.is_developer_fault;
+ ret.type = params.type === undefined ? "error" : params.type;
+ ret.http_code = params.http_code === undefined ? 500 : params.http_code;
ret.data = data || params.data || {};
return ret;
}
SealiousErrors.ValidationError = function(message, data){
var err = new SealiousErrors.Error(message, {}, data);
err.status_message = message;
err.is_user_fault = true;
- err.type="validation";
+ err.type = "validation";
err.http_code = 403;
return err;
}
SealiousErrors.ValueExists = function(message, data){
var err = new SealiousErrors.Error(message, {}, data);
err.status_message = message;
err.is_user_fault = true;
- err.type="valueExists";
+ err.type = "valueExists";
err.http_code = 409;
- return err;
+ return err;
}
SealiousErrors.InvalidCredentials = function(message, data){
var err = new SealiousErrors.Error(message, {}, data);
err.status_message = message;
err.is_user_fault = true;
- err.type="authorization";
+ err.type = "authorization";
err.http_code = 401;
- return err;
+ return err;
}
SealiousErrors.NotFound = function(message, data){
var err = new SealiousErrors.Error(message, {}, data);
err.status_message = message;
err.is_user_fault = true;
- err.type="not_found";
+ err.type = "not_found";
err.http_code = 404;
- return err;
+ return err;
}
SealiousErrors.InternalConnectionError = function(message, data){
var err = new SealiousErrors.Error(message, {}, data);
err.status_message = message;
err.is_user_fault = false;
- err.type="internal_connection_error";
+ err.type = "internal_connection_error";
err.http_code = 500;
return err;
}
SealiousErrors.DependencyError = function(message, data){
var err = new SealiousErrors.Error(message, {}, data);
err.status_message = message;
err.is_user_fault = false;
err.is_developer_fault = true;
- err.type="dependency_error";
+ err.type = "dependency_error";
err.http_code = 500;
return err;
}
SealiousErrors.UnauthorizedRequest = function(message, data){
var err = new SealiousErrors.Error(message, {}, data);
err.status_message = message;
err.is_user_fault = true;
- err.type="unauthorized_request";
+ err.type = "unauthorized_request";
err.http_code = 401;
return err;
}
SealiousErrors.DeveloperError = function(message, data){
var err = new SealiousErrors.Error(message, {}, data);
err.status_message = message;
err.is_user_fault = false;
err.is_developer_fault = true;
- err.type="dev_error";
- return err;
+ err.type = "dev_error";
+ return err;
}
SealiousErrors.BadContext = function(message, data){
var err = new SealiousErrors.Error(message, {}, data);
err.status_message = message;
err.is_user_fault = true;
- err.type="permission";
+ err.type = "permission";
err.http_code = 401;
- return err;
+ return err;
}
/*
process.on('uncaughtException', function (exception) {
switch(exception.code){
case "EACCES":
console.log("\nNo root access - closing!\n");
process.exit();
break;
case "EADDRINUSE":
console.log("\nPort 80 is already taken - closing!\n");
process.exit();
break;
default:
console.log(exception.stack);
throw exception;
break;
}
});
*/
module.exports = SealiousErrors;
\ No newline at end of file
diff --git a/lib/response/response.js b/lib/response/response.js
index a5402bd8..7d9e1a3f 100644
--- a/lib/response/response.js
+++ b/lib/response/response.js
@@ -1,17 +1,17 @@
-function Response(data, is_error, type, status_message){
- this.status = is_error? "error" : "success";
+function Response (data, is_error, type, status_message) {
+ this.status = is_error ? "error" : "success";
this.type = type || "response";
this.status_message = status_message || ok;
this.data = data || {};
}
Response.fromError = function(sealious_error){
return {
- data: sealious_error.data || {},
- is_error: true,
+ data: sealious_error.data || {},
+ is_error: true,
type: sealious_error.type,
status_message: sealious_error.status_message,
};
}
module.exports = Response;
\ No newline at end of file
diff --git a/package.json b/package.json
index 25fc864c..b54fafe6 100644
--- a/package.json
+++ b/package.json
@@ -1,48 +1,61 @@
{
"name": "sealious",
"homepage": "http://sealious.github.io/",
"version": "0.5.13",
"description": "A declarative framework for fast & easy app development.",
"main": "./lib/main.js",
"scripts": {
"prepublish": "require-self",
- "test": "./node_modules/mocha/bin/mocha --delay ./tests/test.js",
- "precoveralls": "node ./tests/prepare-for-coverage.js && jscoverage lib lib-cov",
- "coveralls": "./node_modules/.bin/mocha ./tests/test.js --delay -R mocha-lcov-reporter | ./node_modules/coveralls/bin/coveralls.js || npm run postcoveralls",
- "postcoveralls": "node ./tests/prepare-for-coverage-undo.js",
- "coverage": "npm run precoveralls && ./node_modules/.bin/mocha ./tests/test.js --delay -R html-cov > coverage.html && npm run postcoveralls && (xdg-open coverage.html || start coverage.html)"
+ "test": "mocha --delay ./tests/test.js",
+ "test-coverage": "mocha -R html-cov --delay ./tests/test.js >> coverage.html && xdg-open coverage.html",
+ "precoveralls": "node ./tests/prepare-for-coverage.js && jscoverage lib lib-cov",
+ "coveralls": "./node_modules/.bin/mocha ./tests/test.js --delay -R mocha-lcov-reporter | ./node_modules/coveralls/bin/coveralls.js || npm run postcoveralls",
+ "postcoveralls": "node ./tests/prepare-for-coverage-undo.js",
+ "check-formatting": "jscs -c .jscsrc ./lib && echo \"\\n ✓ Code formatting O.K.!\\n\" || (echo \"\\nSome formatting errors found. Run 'npm run fix-formatting' to correct them.\\n\" && exit )",
+ "fix-formatting": "jscs -c .jscsrc ./lib --fix"
},
"repository": {
"type": "git",
"url": "https://github.com/Sealious/Sealious/"
},
"keywords": [
"sealious"
],
"author": "The Sealious team (http://github.com/Sealious)",
"license": "BSD-2-Clause",
"bugs": {
"url": "https://github.com/Sealious/Sealious/issues"
},
"dependencies": {
"Set": "~0.4.1",
"bluebird": "~2.9.9",
"clone": "^1.0.2",
"fs-extra": "^0.18.2",
"immutable": "^3.7.2",
"merge": "^1.2.0",
"path": "^0.11.14",
"sanitize-html": "^1.6.1",
"sealious-datastore-tingo": "^0.1.3",
"sha1": "^1.1.0",
"uid": "0.0.2",
"winston": "^1.0.0"
},
"devDependencies": {
"coveralls": "^2.11.4",
"jscoverage": "^0.6.0",
"mocha": "*",
"mocha-lcov-reporter": "0.0.2",
- "require-self": "^0.1.0"
+ "require-self": "^0.1.0",
+ "jscs": "^2.1.1",
+ "mocha": "*",
+ "pre-commit": "^1.1.1",
+ "require-self": "^0.1.0"
+ },
+ "pre-commit": {
+ "colors": true,
+ "run": [
+ "check-formatting"
+ ],
+ "silent": false
}
}
\ No newline at end of file

File Metadata

Mime Type
text/x-diff
Expires
Sat, Nov 28, 03:15 (3 h, 20 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
1230149
Default Alt Text
(193 KB)

Event Timeline