Page MenuHomeSealhub

No OneTemporary

Authored By
Unknown
Size
61 KB
Referenced Files
None
Subscribers
None
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 53d5c6f6..f1f4b182 100644
--- a/lib/base-chips/access_strategy.id_starts_with_digit.js
+++ b/lib/base-chips/access_strategy.id_starts_with_digit.js
@@ -1,16 +1,17 @@
+var Sealious = require("../main.js");
var Promise = require("bluebird");
var number_test = /^[0-9]/
var IDStartsWithDigit = new Sealious.ChipTypes.AccessStrategy("id_starts_with_digit", {
checker_function: function(context, item){
return new Promise(function(resolve, reject){
if(number_test.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.noone.js b/lib/base-chips/access_strategy.noone.js
index 57f4e658..d05fe8ff 100644
--- a/lib/base-chips/access_strategy.noone.js
+++ b/lib/base-chips/access_strategy.noone.js
@@ -1,8 +1,9 @@
+var Sealious = require("../main.js");
var Promise = require("bluebird");
var Public = new Sealious.ChipTypes.AccessStrategy("noone", {
checker_function: function(context){
return Promise.reject("Noone gets in!");
},
item_sensitive: false,
});
\ No newline at end of file
diff --git a/lib/base-chips/access_strategy.public.js b/lib/base-chips/access_strategy.public.js
index 654f4af0..d4efccb4 100644
--- a/lib/base-chips/access_strategy.public.js
+++ b/lib/base-chips/access_strategy.public.js
@@ -1,8 +1,9 @@
+var Sealious = require("../main.js");
var Promise = require("bluebird");
var Public = new Sealious.ChipTypes.AccessStrategy("public", {
checker_function: function(context){
return Promise.resolve("Everybody is a winner!");
},
item_sensitive: false,
});
\ No newline at end of file
diff --git a/lib/base-chips/datastore.mongo.js b/lib/base-chips/datastore.mongo.js
index cc7b0fda..be5933a1 100644
--- a/lib/base-chips/datastore.mongo.js
+++ b/lib/base-chips/datastore.mongo.js
@@ -1,125 +1,126 @@
+var Sealious = require("../main.js");
var Promise = require("bluebird");
var mongodb = null;
var TingoDB = null;
var db = null;
var datastore_mongo = new Sealious.ChipTypes.Datastore("mongo");
Sealious.ConfigManager.set_default_config(
"datastore_mongo",
{
embedded: false,
host: 'localhost',
port: 27017,
db_name: 'sealious'
}
);
datastore_mongo.start = function(){
var config = Sealious.ConfigManager.get_config("datastore_mongo");
if(config.embedded){
TingoDB = require('tingodb')();
db = new TingoDB.Db('./db', {});
console.log("Statring datastoremongo");
return Promise.resolve();
}else{
mongodb = require("mongodb")
var mongo_client = new mongodb.MongoClient(new mongodb.Server(config.host, config.port));
return new Promise(function(resolve, reject){
mongo_client.open(function(err, mongoClient){
db = mongoClient.db(config.db_name);
resolve();
});
});
}
}
function process_query(query){
if(!query){
return {};
}
var new_query = {};
for(var attribute_name in query){
if(attribute_name=="sealious_id"){
new_query[attribute_name] = query[attribute_name];
}else{
if(query[attribute_name] instanceof Object){
for(var i in query[attribute_name]){
new_query[attribute_name + "." + i] = query[attribute_name][i];
}
}else{
new_query[attribute_name] = query[attribute_name];
}
}
}
return new_query;
}
datastore_mongo.find = function(collection_name, query, options, output_options){
query = process_query(query);
options = options || {};
output_options = output_options || {};
return new Promise(function(resolve, reject){
var cursor = db.collection(collection_name).find(query, options);
if (output_options.sort) {
cursor.sort(output_options.sort);
}
if (output_options.skip) {
cursor.skip(output_options.skip);
}
if (output_options.amount) {
cursor.limit(output_options.amount);
}
cursor.toArray(function(err, val) {
if (err) {
reject(err)
} else {
resolve(val);
}
})
})
}
datastore_mongo.insert = function(collection_name, to_insert, options){
return new Promise(function(resolve, reject){
db.collection(collection_name).insert(to_insert, options, function(err, inserted){
if (err) {
reject(err);
} else {
resolve(inserted);
}
})
})
}
datastore_mongo.update = function(collection_name, query, new_value){
query = process_query(query);
return new Promise(function(resolve, reject){
db.collection(collection_name).update(query, new_value, function(err, inserted) {
if (err) {
reject(err);
} else {
resolve(inserted);
}
})
})
}
datastore_mongo.delete = function(collection_name, query, justOne){
query = process_query(query);
return new Promise(function(resolve, reject){
if(justOne===undefined){
justOne=0;
}
justOne = justOne? 1 : 0;
db.collection(collection_name).remove(query, justOne, function(err, delete_response) {
if (err) {
reject(err);
} else {
resolve(delete_response);
}
})
})
}
diff --git a/lib/base-chips/field_type.date.js b/lib/base-chips/field_type.date.js
index beace48d..9533a281 100644
--- a/lib/base-chips/field_type.date.js
+++ b/lib/base-chips/field_type.date.js
@@ -1,25 +1,27 @@
+var Sealious = require("../main.js");
+
var Promise = require("bluebird");
var field_type_date = new Sealious.ChipTypes.FieldType("date");
field_type_date.prototype.isProperValue = function(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
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();
}
})
}
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
diff --git a/lib/base-chips/field_type.datetime.js b/lib/base-chips/field_type.datetime.js
index 4df46ab1..8c3a328f 100644
--- a/lib/base-chips/field_type.datetime.js
+++ b/lib/base-chips/field_type.datetime.js
@@ -1,22 +1,24 @@
+var Sealious = require("../main.js");
+
var Promise = require("bluebird");
var field_type_datetime = new Sealious.ChipTypes.FieldType("datetime");
field_type_datetime.prototype.isProperValue = function(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
diff --git a/lib/base-chips/field_type.email.js b/lib/base-chips/field_type.email.js
index 4d22bd47..e4ebaa8b 100644
--- a/lib/base-chips/field_type.email.js
+++ b/lib/base-chips/field_type.email.js
@@ -1,18 +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(value){
return new Promise(function(resolve, reject){
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)){
reject(address + " is not valid e-mail address.");
} else {
resolve();
}
})
}
\ 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 13346046..b880a527 100644
--- a/lib/base-chips/field_type.file.js
+++ b/lib/base-chips/field_type.file.js
@@ -1,45 +1,46 @@
+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(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{
return undefined;
}
}
}
FieldFileType.prototype.decode.uses_context = true;
\ 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 014be776..8355fc01 100644
--- a/lib/base-chips/field_type.float.js
+++ b/lib/base-chips/field_type.float.js
@@ -1,18 +1,19 @@
+var Sealious = require("../main.js");
var Promise = require("bluebird");
var field_type_float = new Sealious.ChipTypes.FieldType("float");
field_type_float.prototype.isProperValue = function(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));
})
}
diff --git a/lib/base-chips/field_type.int.js b/lib/base-chips/field_type.int.js
index 26a4c5d4..2b0e6866 100644
--- a/lib/base-chips/field_type.int.js
+++ b/lib/base-chips/field_type.int.js
@@ -1,7 +1,8 @@
+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
diff --git a/lib/base-chips/field_type.reference.js b/lib/base-chips/field_type.reference.js
index 0bd6d02b..310f27e3 100644
--- a/lib/base-chips/field_type.reference.js
+++ b/lib/base-chips/field_type.reference.js
@@ -1,101 +1,102 @@
+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.");
}
}
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);
}
}
}
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);
})
}
}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.uses_context = true;
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
diff --git a/lib/base-chips/field_type.text.js b/lib/base-chips/field_type.text.js
index b6a03072..be41d5d8 100644
--- a/lib/base-chips/field_type.text.js
+++ b/lib/base-chips/field_type.text.js
@@ -1,33 +1,34 @@
+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(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.");
}
}
}
field_type_text.prototype.encode = function(value_in_code){
return new Promise(function(resolve, reject){
if(this.params && this.params.strip_html === true){
var stripped = sanitizeHtml(value_in_code.toString(), {
allowedTags: []
})
resolve(stripped);
}else{
if(value_in_code instanceof Object){
resolve(JSON.stringify(value_in_code));
}else{
resolve(value_in_code.toString());
}
}
}.bind(this))
}
\ 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 5b99d6b1..a7d5a0db 100644
--- a/lib/base-chips/resource_type.user.js
+++ b/lib/base-chips/resource_type.user.js
@@ -1,10 +1,11 @@
+var Sealious = require("../main.js");
var user = new Sealious.ChipTypes.ResourceType("user", {
fields:[
{name: "username", type: "text", required: true},
{name: "email", type: "email"},
{name: "password", type: "text", required: true},
{name: "status", type: "text"},
{name:"username", type:"text"}
]
});
diff --git a/lib/chip-types/access-strategy.js b/lib/chip-types/access-strategy.js
index c8787748..c068f1ae 100644
--- a/lib/chip-types/access-strategy.js
+++ b/lib/chip-types/access-strategy.js
@@ -1,41 +1,42 @@
+var Sealious = require("../main.js");
var Promise = require("bluebird");
var Chip = require("./chip.js");
function AccessStrategy(parent_module_path, name, declaration){
Chip.call(this, parent_module_path, true, "access_strategy", name);
this.checker_function = null;
this.item_sensitive = false;
if(declaration) this._process_declaration(declaration);
}
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.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);
}
});
}
}
AccessStrategy.type_name = "access_strategy";
module.exports = AccessStrategy;
\ No newline at end of file
diff --git a/lib/chip-types/channel.js b/lib/chip-types/channel.js
index 6c40dcaf..c45cc353 100644
--- a/lib/chip-types/channel.js
+++ b/lib/chip-types/channel.js
@@ -1,12 +1,13 @@
+var Sealious = require("../main.js");
var chip = require("./chip.js");
function channel(parent_module_path, name){
this.name = name;
this.longid = "channel."+name;
this.default_configuration = {};
Sealious.ChipManager.add_chip("channel", this.name, this, parent_module_path);
}
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 16e151a4..05894cdc 100644
--- a/lib/chip-types/chip-manager.js
+++ b/lib/chip-types/chip-manager.js
@@ -1,130 +1,131 @@
+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")
}
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){
var type = chip_type_start_order[i];
if(chips[type] && chip_types_to_start.indexOf(type)!==-1){
Sealious.Logger.info(" " + type + ":");
for(var name in chips[type]){
var chip = chips[type][name];
Sealious.Logger.info("\t \u2713 " + name);
try{
if(chip.start){
var promise = chip.start();
promises.push(promise);
}
}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]=[];
}
chips[type][name]=chip;
if(chips_by_module[module_path]==undefined){
chips_by_module[module_path]=[];
}
chips_by_module[module_path].push(chip);
}
this.get_all_resource_types = function(){
var names = [];
for (resource_type in chips.resource_type) {
names.push(resource_type);
}
return names;
}
this.chip_exists = function(type, name){
if(chips[type] && chips[type][name]){
return true;
}else{
return false;
}
}
this.get_chip = function(type, name){
try{
return chips[type][name]
}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]){
return Object.keys(chips[type]).length;
}else{
return 0;
}
}
this.get_datastore_chip = function(){
var datastore_chip_amount = this.get_chip_amount_by_type("datastore");
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.")
}
if(datastore_chip_amount===1){
return chips["datastore"][Object.keys(chips["datastore"])[0]]
}
var datastore_chip_name = ConfigurationManager.get_dispatcher_config().datastore_chip;
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;
diff --git a/lib/chip-types/datastore.js b/lib/chip-types/datastore.js
index b7bd4ef4..b9d4f99c 100644
--- a/lib/chip-types/datastore.js
+++ b/lib/chip-types/datastore.js
@@ -1,26 +1,27 @@
+var Sealious = require("../main.js");
var Chip = require("./chip.js");
var Datastore = function(parent_module_path, name){
this.name = name;
this.longid = "datastore."+name;
this.default_configuration = {};
Sealious.ChipManager.add_chip("datastore", this.name, this, parent_module_path);
}
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.");
}
}
var needs_to_implement = ["find", "insert", "update", "remove"]
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)
}
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 a1b05a07..fd85de21 100644
--- a/lib/chip-types/field-type.js
+++ b/lib/chip-types/field-type.js
@@ -1,67 +1,68 @@
+var Sealious = require("../main.js");
var Promise = require("bluebird");
var merge = require("merge");
var Chip = require("./chip.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);
instance.prototype = Object.create(FieldType.prototype);
return instance;
}
FieldType.prototype = new function(){
/**
* 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();
}
this.validate_declaration = function(declaration){
return Promise.resolve();
}
this.encode = function(value_in_code){
return Promise.resolve(value_in_code);
}
this.encode.uses_context = false;
this.decode = function(value_in_database, formatting_options){
return Promise.resolve(value_in_database);
}
this.set_params = function(param_map){
if(this.params==undefined){
this.params = param_map;
}
this.params = merge(this.params, param_map);
}
this.set_fieldname = function(fieldname){
this.fieldname = fieldname;
}
this.get_params = function(context){
return this.params;
}
}
FieldType.is_a_constructor = true;
FieldType.type_name = "field_type";
module.exports = FieldType;
\ 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 50413a69..0d3da44b 100644
--- a/lib/chip-types/resource-type-field.js
+++ b/lib/chip-types/resource-type-field.js
@@ -1,95 +1,97 @@
+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.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;
};
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){
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));
*/
}
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.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.decode_value = function(context, value_in_database){
if(this.type.decode.uses_context){
_arguments = [context, value_in_database];
}else{
_arguments = [value_in_database];
}
var decode_value = this.type.decode.apply(this.type, _arguments);
return decode_value;
}
this.get_signature = function(){
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();
return field_signature;
}
}
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 9c5a7a2b..a271ed36 100644
--- a/lib/chip-types/resource-type.js
+++ b/lib/chip-types/resource-type.js
@@ -1,227 +1,228 @@
+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, name, declaration){
Chip.call(this, parent_module_path, true, "resource_type", name);
this.name = 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){
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]){
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){
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()){
return true;
}
}
return false;
}
function ensure_no_unknown_fields(values){
var validation_errors = {};
for(var field_name in values){
if(this.keys[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]){
validation_errors[field.name] = "missing_value";
}
}
return validation_errors;
}
this.validate_field_values = function(context, check_missing, values, old_values){
var that = 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
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};
}
}
}
}
if(Object.keys(validation_errors).length>0){
throw new Sealious.Errors.ValidationError(error_message, {invalid_fields: validation_errors});
}else{
return Promise.resolve();
}
}.bind(this))
}
this.encode_field_values = function(context, body, old_body){
var promises = {};
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);
}
return Promise.props(promises);
}
this.get_signature = function(){
var resource_type_signature = [];
for(var field_name in this.fields){
var field_signature = this.fields[field_name].get_signature();
resource_type_signature.push(field_signature);
}
return resource_type_signature;
}
this.set_access_strategy = function(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){
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){
var field = this.fields[i];
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){
return true;
}
}
return false;
}
this.decode_values = function(context, values){
var decoded_values = {};
for(var key in this.keys){
var value = values[key];
var field = this.fields[key];
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
}
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 3db43933..533d7325 100644
--- a/lib/config/config-manager.js
+++ b/lib/config/config-manager.js
@@ -1,62 +1,63 @@
+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(config_object, 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++){
current_position[key] = {};
current_position = current_position[key];
}
current_position[key_elements[key_elements.length-1]]=value;
config_object = merge.recursive(config_object, new_values);
}
this.set_config = function(key, new_config){
if(arguments.length==1){
config = config;
}else{
modify_config(config, key, new_config);
}
}
this.set_default_config = function(key, value){
if(arguments.length==1){
default_config = default_config;
}else{
modify_config(default_config, 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 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];
}
return merge(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/core-services/resource-manager.js b/lib/core-services/resource-manager.js
index 99968027..80951ad5 100644
--- a/lib/core-services/resource-manager.js
+++ b/lib/core-services/resource-manager.js
@@ -1,250 +1,251 @@
+var Sealious = require("../main.js");
var Promise = require("bluebird");
var ResourceRepresentation = require("../chip-types/resource-representation.js");
var UUIDGenerator = require("uid");
/**
* Manages resources in the database
* @class
*/
var ResourceManager = new function(){
this.name = "resources";
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 encoded_body = null;
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
};
return Sealious.Dispatcher.datastore.insert("resources", resource_data, {});
}).then(function(data){
var database_entry = data[0];
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.delete("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 }, {}, {});
});
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){
query.type = type;
}
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){
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 = Sealious.Dispatcher.resources.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 = {};
for(var field_name in encoded_values){
query["body." + field_name] = encoded_values[field_name];
}
if(Object.keys(query).length==0){
return Promise.resolve();
}else{
return Sealious.Dispatcher.datastore.update("resources", {sealious_id: resource_id}, {$set: query})
}
}).then(function(){
return Sealious.Dispatcher.resources.get_by_id(context, resource_id);
});
}
this.update_resource = function(context, type_name, resource_id, new_resource_data){
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 = Sealious.Dispatcher.resources.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(){
var query = {};
if(new_resource_data.hasOwnProperty("sealious_id")){
delete new_resource_data.sealious_id;
}
if(new_resource_data.hasOwnProperty("id")){
delete new_resource_data.id;
}
/*
for(var field_name in new_resource_data){
query["body." + field_name] = new_resource_data[field_name];
}
*/
return Sealious.Dispatcher.datastore.update("resources", {sealious_id: resource_id}, {$set: {body: new_resource_data}})
}).then(function(){
return Sealious.Dispatcher.resources.get_by_id(context, resource_id);
});
}
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."));
}
})
}
}
module.exports = ResourceManager;
diff --git a/lib/core.js b/lib/core.js
index 2b5bfeeb..39188c24 100644
--- a/lib/core.js
+++ b/lib/core.js
@@ -1,69 +1,70 @@
+var Sealious = require("./main.js");
var path = require("path");
var http = require("http");
var ConfigManager = require("./config/config-manager.js");
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;
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() {
var sealious_npm = JSON.parse(body);
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.");
});
}
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.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);
}
}
module.exports = SealiousCore;
\ No newline at end of file
diff --git a/lib/data-structures/file.js b/lib/data-structures/file.js
index 58893509..546969b8 100644
--- a/lib/data-structures/file.js
+++ b/lib/data-structures/file.js
@@ -1,29 +1,31 @@
+var Sealious = require("../main.js");
+
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]);
});
}
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;
diff --git a/lib/logger/logger.js b/lib/logger/logger.js
index 9b2f1bf7..4763b9ed 100644
--- a/lib/logger/logger.js
+++ b/lib/logger/logger.js
@@ -1,118 +1,121 @@
+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 : "no_output",
+ 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'
}
};
/*
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) {
var date = new Date();
var hour = date.getHours();
hour = (hour < 10 ? "0" : "") + hour;
var min = date.getMinutes();
min = (min < 10 ? "0" : "") + min;
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 year = date.getFullYear();
var month = date.getMonth() + 1;
month = (month < 10 ? "0" : "") + month;
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; }
}
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); } });
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 logger = new (winston.Logger)(
+var logger = new winston.Logger(
{
levels: custom.levels,
colors: custom.colors,
transports: transports_array
}
);
+logger.info("nini");
+
module.exports = logger;
\ No newline at end of file
diff --git a/lib/main.js b/lib/main.js
index c7560daf..ac52f9ca 100644
--- a/lib/main.js
+++ b/lib/main.js
@@ -1,49 +1,52 @@
var path = require("path");
-var Core = require("./core.js");
+
+var Sealious = {};
+module.exports = Sealious;
+
var core_instance = null;
-global.Sealious = {};
+var Core = require("./core.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.Logger = require("./logger/logger.js");
Sealious.PluginManager = require("./plugins/plugin-manager.js");
Sealious.Dispatcher = null;
Sealious.Context = require("./context.js");
-Sealious.Logger = require("./logger/logger.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
}
Sealious.init = function(mode, layer_name){
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);
}
module.exports = Sealious;
\ No newline at end of file
diff --git a/lib/plugins/plugin-manager.js b/lib/plugins/plugin-manager.js
index db98d518..4955668a 100644
--- a/lib/plugins/plugin-manager.js
+++ b/lib/plugins/plugin-manager.js
@@ -1,22 +1,23 @@
+var Sealious = require("../main.js");
var path = require("path");
var PluginManager = new function(){
this.load_plugins = function(package_dir){
package_dir = package_dir || "";
var root = path.resolve(package_dir);
var pkgfile = path.join(root, 'package.json');
var pkg = require(pkgfile);
for(var dependency_name in pkg.dependencies){
var plugin_package_info_file = path.resolve(root, "node_modules", dependency_name, "package.json");
var plugin_package_info = require(plugin_package_info_file);
if(plugin_package_info.keywords && plugin_package_info.keywords.indexOf("sealious-plugin")!==-1){
Sealious.Logger.info("Detected plugin " + plugin_package_info.name);
var plugin = require(path.resolve(root, "node_modules", dependency_name));
}
}
}
}
module.exports = PluginManager;
diff --git a/tests/test.js b/tests/test.js
index 40cb2b39..8e15c4ba 100644
--- a/tests/test.js
+++ b/tests/test.js
@@ -1,111 +1,111 @@
-require("../lib/main.js"); //Sealious
+var Sealious = require("../lib/main.js"); //Sealious
var assert = require("assert");
Sealious.init();
// 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("always_fails_resource");
always_fails_resource.add_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("never_fails_resource");
never_fails_resource.add_fields([
{name: "#success", type: "never_fails"},
])
describe("Sealious", function(){
Sealious.start().then(function(){
it('should not create a new resource', function(done){
Sealious.Dispatcher.resources.create({}, "always_fails_resource", { "#fail": "tak" })
.then(function(){
done(new Error("It didn't throw an error!"));
}).catch(function(error){
done();
});
});
it('should create a new resource', function(done){
Sealious.Dispatcher.resources.create({}, "never_fails_resource", { "#success": "tak" })
.then(function(result){
done();
}).catch(function(error){
done(error);
});
});
it('should get data about the resource', function(done){
Sealious.Dispatcher.resources.create({}, "never_fails_resource", { "#success": "tak" })
.then(function(result){
Sealious.Dispatcher.resources.get_by_id({}, 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 delete the resource', function(done){
Sealious.Dispatcher.resources.create({}, "never_fails_resource", { "#success": "tak" })
.then(function(result){
Sealious.Dispatcher.resources.delete({}, "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 update the resource', function(done){
Sealious.Dispatcher.resources.create({}, "never_fails_resource", { "#success": "tak" })
.then(function(result){
Sealious.Dispatcher.resources.update_resource({}, "never_fails_resource", result.id, {"#success" : "tak2"})
.then(function(resource){
done();
}).catch(function(error){
done(new Error(error));
})
}).catch(function(error){
done(error);
});
});
it('should list resources by type', function(done){
Sealious.Dispatcher.resources.list_by_type({}, "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){
Sealious.Dispatcher.resources.get_resource_type_signature({}, "never_fails_resource")
.then(function(result){
done();
}).catch(function(error){
done(new Error("It threw an error!"));
});
});
run(); //!!important
})
})

File Metadata

Mime Type
text/x-diff
Expires
Sat, Nov 28, 03:16 (1 d, 14 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
1218113
Default Alt Text
(61 KB)

Event Timeline