Page MenuHomeSealhub

No OneTemporary

Authored By
Unknown
Size
217 KB
Referenced Files
None
Subscribers
None
diff --git a/.eslintrc.json b/.eslintrc.json
index 6fc396be..d9ce5239 100644
--- a/.eslintrc.json
+++ b/.eslintrc.json
@@ -1,46 +1,46 @@
{
"env": {
"es6": true,
"node": true
},
"globals" : {
"describe" : false,
"it" : false,
"before" : false,
"beforeEach" : false,
"after" : false,
"afterEach" : false
},
"extends": "eslint:recommended",
"rules": {
"quotes": [
"error",
"double"
],
"semi": [
"error",
"always"
],
"no-console": 2,
"no-var": 2,
"prefer-const": 2,
"prefer-template": 1,
"eqeqeq": [
"error",
"smart"
],
"comma-dangle": [
"error",
"only-multiline"
],
- "no-unused-vars": "warn",
+ "no-unused-vars": "off",
"no-trailing-spaces": "error",
"no-whitespace-before-property": "error",
"space-before-blocks": ["error", "never"],
"space-in-parens": ["error", "never"],
"spaced-comment": ["error", "always"],
"no-lonely-if": "error",
"no-else-return": "warn",
"no-case-declarations": "warn"
}
}
diff --git a/default_config.yml b/default_config.yml
new file mode 100644
index 00000000..38e7f22b
--- /dev/null
+++ b/default_config.yml
@@ -0,0 +1,9 @@
+core:
+ datastore: tingodb
+logger:
+ level: "info"
+ color: true
+ file: null
+ dirname: "."
+ to_json: false
+ rotation: ".yyyy-MM-Tdd"
diff --git a/lib/action.js b/lib/action.js
index 7f331229..76c3d038 100644
--- a/lib/action.js
+++ b/lib/action.js
@@ -1,26 +1,33 @@
"use strict";
const locreq = require("locreq")(__dirname);
const SubjectPath = locreq("lib/data-structures/subject-path.js");
-const RootSubject = locreq("lib/subject/predefined-subjects/root-subject.js");
const Promise = require("bluebird");
-function Action (subject_path, action_name){
+function Action (RootSubject, subject_path, action_name){
+ this.RootSubject = RootSubject;
this.subject_path = new SubjectPath(subject_path);
this.action_name = action_name;
}
-Action.prototype.perform = Action.prototype.run = function(context){
- const self = this;
- const args = Array.prototype.slice.call(arguments, 1);
+Action.pure = {};
+Action.pure.perform = function(RootSubject, subject_path, action_name, context, args){
return Promise.try(function(){
- return RootSubject.get_subject(self.subject_path)
+ return RootSubject.get_subject(subject_path)
.then(function(subject){
- return subject.perform_action.apply(subject, [context, self.action_name].concat(args));
+ return subject.perform_action(context, action_name, args);
});
});
};
+Action.prototype.perform = Action.prototype.run = function(context, args){
+ return Action.pure.perform(this.RootSubject, this.subject_path, this.action_name, context, args);
+};
+Action.curry = function(RootSubject){
+ return function(subject_path, action_name){
+ return new Action(RootSubject, subject_path, action_name);
+ };
+};
module.exports = Action;
diff --git a/lib/app/app.js b/lib/app/app.js
new file mode 100644
index 00000000..810b38b7
--- /dev/null
+++ b/lib/app/app.js
@@ -0,0 +1,79 @@
+const locreq = require("locreq")(__dirname);
+const path = require("path");
+
+const Sealious = locreq("lib/main.js");
+
+const ConfigManager = locreq("lib/app/config-manager.js");
+const ChipManager = locreq("lib/app/chip-manager.js");
+const Logger = locreq("lib/app/logger.js");
+const RootSubject = locreq("lib/subject/predefined-subjects/root-subject.js");
+const Action = locreq("lib/action.js");
+const run_action_curry = locreq("lib/app/run-action-curry.js");
+const FileManager = locreq("lib/app/file-manager.js");
+const PluginManager = locreq("lib/app/plugin-manager.js");
+
+const load_base_chips = locreq("lib/app/load-base-chips");
+
+const get_main_app_dir = locreq("lib/utils/get-main-app-dir.js");
+const check_for_updates = locreq("lib/utils/check-for-updates.js");
+
+const App = function(app_dir_arg){
+ const app_dir = app_dir_arg || get_main_app_dir();
+ const sealious_dir = path.resolve(module.filename, "../../../");
+
+ const app = this;
+ app.Sealious = Sealious;
+
+ app.ConfigManager = new ConfigManager();
+ app.Datastore = null; // this variable will hold the default datastore.
+
+ app.ConfigManager.load_default_config_for_dir(sealious_dir);
+ app.ConfigManager.load_custom_config(app_dir);
+
+ app.Logger = new Logger(app);
+ app.ChipManager = new ChipManager(app);
+
+ app.RootSubject = new RootSubject(app);
+ app.Action = Action.curry(app.RootSubject);
+ app.run_action = run_action_curry(app);
+
+ load_base_chips(app);
+
+ app.PluginManager = new PluginManager(app.ConfigManager, app.Logger);
+ app.PluginManager.load_plugins(sealious_dir, app);
+
+ app.Datastore = app.ChipManager.get_datastore_chip();
+
+ app.FileManager = new FileManager(
+ app.Datastore,
+ app.Logger,
+ path.resolve(app_dir, "./uploaded_files")
+ );
+
+ return app;
+};
+
+App.pure = {
+ createChip: function(app, constructor, declaration){
+ const chip = new constructor(app, declaration);
+ app.ChipManager.add_chip(constructor.type_name, declaration.name, chip);
+ return chip;
+ },
+ start: function(app){
+ check_for_updates(app.Logger);
+ return app.ChipManager.start_chips()
+ .then(() => app);
+ },
+};
+
+App.prototype = {
+ createChip(constructor, declaration){return App.pure.createChip(this, constructor, declaration);},
+ createAccessStrategyType(declaration){return this.createChip(Sealious.AccessStrategyType, declaration);},
+ createAccessStrategy(declaration){return this.createChip(Sealious.AccessStrategy, declaration);},
+ createDatastore(declaration){return this.createChip(Sealious.Datastore, declaration);},
+ createCollection(declaration){return this.createChip(Sealious.Collection, declaration);},
+ createChannel(declaration){return this.createChip(Sealious.Channel, declaration);},
+ start(){return App.pure.start(this);},
+};
+
+module.exports = App;
diff --git a/lib/base-chips/access-strategy-types/and.js b/lib/app/base-chips/access-strategy-types/and.js
similarity index 95%
rename from lib/base-chips/access-strategy-types/and.js
rename to lib/app/base-chips/access-strategy-types/and.js
index abdd544e..dbe0f8a3 100644
--- a/lib/base-chips/access-strategy-types/and.js
+++ b/lib/app/base-chips/access-strategy-types/and.js
@@ -1,38 +1,38 @@
"use strict";
const locreq = require("locreq")(__dirname);
const Promise = require("bluebird");
const AccessStrategy = locreq("lib/chip-types/access-strategy.js");
const AccessStrategyType = locreq("lib/chip-types/access-strategy-type.js");
function parse_params (params){
const access_strategies = [];
for (const i in params){
access_strategies.push(new AccessStrategy(params[i]));
}
return access_strategies;
}
-module.exports = new AccessStrategyType({
+module.exports = {
name: "and",
item_sensitive: function(params){
const access_strategies = parse_params(params);
return Promise.map(access_strategies, function(access_strategy){
return access_strategy.is_item_sensitive();
}).reduce((a,b) => a || b);
},
checker_function: function(context, params, item){
return this.is_item_sensitive(params)
.then(function(item_sensitive){
if (item_sensitive && item === undefined){
return undefined;
} else {
const access_strategies = parse_params(params);
const results = access_strategies.map(function(strategy){
return strategy.check(context, item);
});
return Promise.all(results);
}
});
},
-});
+};
diff --git a/lib/base-chips/access-strategy-types/logged_in.js b/lib/app/base-chips/access-strategy-types/logged_in.js
similarity index 100%
rename from lib/base-chips/access-strategy-types/logged_in.js
rename to lib/app/base-chips/access-strategy-types/logged_in.js
diff --git a/lib/base-chips/access-strategy-types/noone.js b/lib/app/base-chips/access-strategy-types/noone.js
similarity index 100%
rename from lib/base-chips/access-strategy-types/noone.js
rename to lib/app/base-chips/access-strategy-types/noone.js
diff --git a/lib/base-chips/access-strategy-types/not.js b/lib/app/base-chips/access-strategy-types/not.js
similarity index 84%
rename from lib/base-chips/access-strategy-types/not.js
rename to lib/app/base-chips/access-strategy-types/not.js
index 6818fb24..0c5f52a1 100644
--- a/lib/base-chips/access-strategy-types/not.js
+++ b/lib/app/base-chips/access-strategy-types/not.js
@@ -1,27 +1,26 @@
"use strict";
const locreq = require("locreq")(__dirname);
const Promise = require("bluebird");
const AccessStrategy = locreq("lib/chip-types/access-strategy.js");
-const AccessStrategyType = locreq("lib/chip-types/access-strategy-type.js");
-module.exports = new AccessStrategyType({
+module.exports = {
name: "not",
checker_function: function(context, params, item){
let strategies;
if (params instanceof Array){
strategies = params.map((declaration) => new AccessStrategy(declaration));
} else {
strategies = [new AccessStrategy(params)];
}
return Promise.map(strategies, function(strategy){
return strategy.check(context, params, item);
})
.any()
.then(function(){
return Promise.reject("Action not allowed");
})
.catch({sealious_error: true}, function(){
return Promise.resolve();
});
},
-});
+};
diff --git a/lib/base-chips/access-strategy-types/or.js b/lib/app/base-chips/access-strategy-types/or.js
similarity index 97%
rename from lib/base-chips/access-strategy-types/or.js
rename to lib/app/base-chips/access-strategy-types/or.js
index db4d98ca..91fb68fc 100644
--- a/lib/base-chips/access-strategy-types/or.js
+++ b/lib/app/base-chips/access-strategy-types/or.js
@@ -1,49 +1,49 @@
"use strict";
const locreq = require("locreq")(__dirname);
const Promise = require("bluebird");
const AccessStrategy = locreq("lib/chip-types/access-strategy.js");
const AccessStrategyType = locreq("lib/chip-types/access-strategy-type.js");
const Error = locreq("lib/response/error.js").Error;
function parse_params (params){
const access_strategies = [];
for (const i in params){
access_strategies.push(new AccessStrategy(params[i]));
}
return access_strategies;
}
-module.exports = new AccessStrategyType({
+module.exports = {
name: "or",
item_sensitive: function(params){
const access_strategies = parse_params(params);
return Promise.map(access_strategies, function(access_strategy){
return access_strategy.is_item_sensitive();
})
.reduce((a,b) => a || b);
},
checker_function: function(context, params, item){
return this.is_item_sensitive(params)
.then(function(item_sensitive){
if (item_sensitive && item === undefined){
return undefined;
} else {
const access_strategies = parse_params(params);
const results = access_strategies.map(function(strategy){
return strategy.check(context, item);
});
return Promise.any(results)
.catch(Promise.AggregateError, function(aggregated_errors){
aggregated_errors.forEach(function(error){
if (!(error instanceof Error)){
throw error;
}
});
const error_message = aggregated_errors.map((aggregated_errors)=>aggregated_errors.message)
.reduce((a,b) => `${a} ${b}`);
return Promise.reject(error_message);
});
}
});
},
-});
+};
diff --git a/lib/base-chips/access-strategy-types/owner.js b/lib/app/base-chips/access-strategy-types/owner.js
similarity index 100%
rename from lib/base-chips/access-strategy-types/owner.js
rename to lib/app/base-chips/access-strategy-types/owner.js
diff --git a/lib/base-chips/access-strategy-types/public.js b/lib/app/base-chips/access-strategy-types/public.js
similarity index 100%
rename from lib/base-chips/access-strategy-types/public.js
rename to lib/app/base-chips/access-strategy-types/public.js
diff --git a/lib/base-chips/access-strategy-types/super.js b/lib/app/base-chips/access-strategy-types/super.js
similarity index 76%
rename from lib/base-chips/access-strategy-types/super.js
rename to lib/app/base-chips/access-strategy-types/super.js
index 87290875..b10e26db 100644
--- a/lib/base-chips/access-strategy-types/super.js
+++ b/lib/app/base-chips/access-strategy-types/super.js
@@ -1,18 +1,17 @@
"use strict";
const locreq = require("locreq")(__dirname);
const Promise = require("bluebird");
-const AccessStrategyType = locreq("lib/chip-types/access-strategy-type.js");
-const Super = new AccessStrategyType({
+const Super = {
name: "super",
checker_function: function(context){
if (context.is_super){
return Promise.resolve();
} else {
return Promise.reject("This action cannot be performed by a regular user, but only by the server itself.");
}
},
item_sensitive: true,
-});
+};
module.exports = Super;
diff --git a/lib/base-chips/access-strategy-types/themselves.js b/lib/app/base-chips/access-strategy-types/themselves.js
similarity index 90%
rename from lib/base-chips/access-strategy-types/themselves.js
rename to lib/app/base-chips/access-strategy-types/themselves.js
index abee145b..402971a6 100644
--- a/lib/base-chips/access-strategy-types/themselves.js
+++ b/lib/app/base-chips/access-strategy-types/themselves.js
@@ -1,16 +1,16 @@
"use strict";
const locreq = require("locreq")(__dirname);
const Promise = require("bluebird");
const AccessStrategyType = locreq("lib/chip-types/access-strategy-type.js");
-module.exports = new AccessStrategyType({
+module.exports = {
name: "themselves",
item_sensitive: true,
checker_function: function(context, params, item){
if (context.user_id === item.id){
return Promise.resolve();
} else {
return Promise.reject(`You are not the user of id ${item.id}.`);
}
},
-});
+};
diff --git a/lib/app/base-chips/collections/sessions.js b/lib/app/base-chips/collections/sessions.js
new file mode 100644
index 00000000..2bac8b2e
--- /dev/null
+++ b/lib/app/base-chips/collections/sessions.js
@@ -0,0 +1,12 @@
+const Sessions = {
+ name: "sessions",
+ fields: [
+ {name: "session-id", type: "session-id"},
+ {name: "user", type: "single_reference", params: {collection: "users"}},
+ ],
+ access_strategy: {
+ default: "super",
+ }
+};
+
+module.exports = Sessions;
diff --git a/lib/base-chips/collection.users.js b/lib/app/base-chips/collections/users.js
similarity index 100%
rename from lib/base-chips/collection.users.js
rename to lib/app/base-chips/collections/users.js
diff --git a/lib/base-chips/field-types/boolean.js b/lib/app/base-chips/field-types/boolean.js
similarity index 100%
rename from lib/base-chips/field-types/boolean.js
rename to lib/app/base-chips/field-types/boolean.js
diff --git a/lib/base-chips/field-types/color.js b/lib/app/base-chips/field-types/color.js
similarity index 100%
rename from lib/base-chips/field-types/color.js
rename to lib/app/base-chips/field-types/color.js
diff --git a/lib/base-chips/field-types/context.js b/lib/app/base-chips/field-types/context.js
similarity index 100%
rename from lib/base-chips/field-types/context.js
rename to lib/app/base-chips/field-types/context.js
diff --git a/lib/base-chips/field-types/date.js b/lib/app/base-chips/field-types/date.js
similarity index 100%
rename from lib/base-chips/field-types/date.js
rename to lib/app/base-chips/field-types/date.js
diff --git a/lib/base-chips/field-types/datetime.js b/lib/app/base-chips/field-types/datetime.js
similarity index 100%
rename from lib/base-chips/field-types/datetime.js
rename to lib/app/base-chips/field-types/datetime.js
diff --git a/lib/base-chips/field-types/email.js b/lib/app/base-chips/field-types/email.js
similarity index 100%
rename from lib/base-chips/field-types/email.js
rename to lib/app/base-chips/field-types/email.js
diff --git a/lib/app/base-chips/field-types/file.js b/lib/app/base-chips/field-types/file.js
new file mode 100644
index 00000000..d0a20357
--- /dev/null
+++ b/lib/app/base-chips/field-types/file.js
@@ -0,0 +1,86 @@
+"use strict";
+const locreq = require("locreq")(__dirname);
+const Promise = require("bluebird");
+const File = locreq("lib/data-structures/file.js");
+const rp = require("request-promise");
+const url = require("url");
+
+module.exports = function(app){
+ return {
+ name: "file",
+ handles_large_data: true,
+ is_proper_value: function(context, params, value){
+ if (value === undefined){
+ return undefined;
+ }
+ if (typeof value == "string"){
+ return rp({url: value, encoding: null})
+ .then(function(){
+ return Promise.resolve();
+ }).catch(function(){
+ return Promise.reject(`There was a problem while getting the file: '${ value }'. Is the URL correct?`);
+ });
+ }
+ if (value === null
+ || value === ""
+ || (value instanceof File)
+ || (value.filename !== undefined && value.data instanceof Buffer)
+ ){
+ return Promise.resolve();
+ } else {
+ let 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. Should be Sealious.File, but received ${type}`);
+ }
+ },
+ encode: function(context, params, value_in_code){
+ if(typeof value_in_code === "string"){
+ return rp({url: value_in_code, encoding: null})
+ .then(function(file_buffer){
+ const filename = url.parse(value_in_code).pathname.split("/").pop();
+ const file = new File(context, filename, file_buffer);
+ return app.FileManager.save_file(file);
+ });
+ }
+ if (value_in_code){
+ return app.FileManager.save_file(value_in_code);
+ } else {
+ return null;
+ }
+ },
+ decode: function(context, params, value_in_database){
+ if (value_in_database){
+ return Promise.resolve(new File.Reference(value_in_database.id, value_in_database.filename));
+ } else if (params.no_file_value){
+ return params.no_file_value;
+ } else {
+ return undefined;
+ }
+ },
+ format: function(context, params, decoded_value, format){
+ if (format === "url"){
+ return `/api/v1/uploaded-files/${decoded_value.id}/${decoded_value.filename}`;
+ } else if (format === "url-with-filename"){
+ if (decoded_value === undefined){
+ return {
+ url: params.no_file_value || "",
+ filename: null,
+ empty: true,
+ };
+ } else {
+ return {
+ url: `/api/v1/uploaded-files/${decoded_value.id}/${decoded_value.filename}`,
+ filename: decoded_value.filename,
+ empty: false,
+ };
+ }
+ } else {
+ return decoded_value;
+ }
+ },
+ };
+};
diff --git a/lib/base-chips/field-types/float.js b/lib/app/base-chips/field-types/float.js
similarity index 100%
rename from lib/base-chips/field-types/float.js
rename to lib/app/base-chips/field-types/float.js
diff --git a/lib/base-chips/field-types/hashed-text.js b/lib/app/base-chips/field-types/hashed-text.js
similarity index 96%
rename from lib/base-chips/field-types/hashed-text.js
rename to lib/app/base-chips/field-types/hashed-text.js
index 80278d25..3272e588 100644
--- a/lib/base-chips/field-types/hashed-text.js
+++ b/lib/app/base-chips/field-types/hashed-text.js
@@ -1,78 +1,76 @@
"use strict";
const Promise = require("bluebird");
const crypto = require("crypto");
module.exports = {
name: "hashed-text",
extends: "text",
get_description: function(context, params){
let message = "Hash text with chosen algorithm (default md5)";
if (params && Object.keys(params).length > 0){
message += " with ";
if (params.digits){
message += `required digits: ${params.digits} `;
}
if (params.capitals){
message += `required capitals: ${params.capitals} `;
}
}
return message;
},
is_proper_value: function(context, params, new_value){
const pattern_array = [];
- if (typeof params === "object"){
+ if (params){
if (params.digits){
pattern_array.push(new RegExp(`(.*[0-9]+.*){${params.digits}}`));
}
if (params.capitals){
pattern_array.push(new RegExp(`(.*[A-Z]+.*){${params.capitals}}`));
}
const isAccepted = pattern_array.map(n => n.test(new_value)).reduce((a,b) => a && b, true);
if (isAccepted){
return Promise.resolve();
- }
- else {
+ } else {
const digits = params.digits || "0";
const capitals = params.capitals || "0";
return Promise.reject(`It didn't fulfill the requirements: required digits - ${digits} , required capitals ${capitals}`);
}
- }
- else {
+ } else {
return Promise.resolve();
}
},
encode: function(context, params, value_in_code){
let salt = "", algorithm = "md5";
if (params){
if (params.salt){
salt = params.salt;
}
else if (params.algorithm){
algorithm = params.algorithm;
}
}
return new Promise(function(resolve, reject){
crypto.pbkdf2(value_in_code, salt, 4096, 64, algorithm, function(err, key){
if (err){
reject(err);
} else {
resolve(key.toString("hex"));
}
});
});
},
decode: function(context, params, value_in_db){
if (params && params.hide_hash){
return null;
} else {
return value_in_db;
}
},
};
diff --git a/lib/base-chips/field-types/html.js b/lib/app/base-chips/field-types/html.js
similarity index 100%
rename from lib/base-chips/field-types/html.js
rename to lib/app/base-chips/field-types/html.js
diff --git a/lib/base-chips/field-types/int.js b/lib/app/base-chips/field-types/int.js
similarity index 89%
rename from lib/base-chips/field-types/int.js
rename to lib/app/base-chips/field-types/int.js
index 6bd07e4e..0705e58e 100644
--- a/lib/base-chips/field-types/int.js
+++ b/lib/app/base-chips/field-types/int.js
@@ -1,53 +1,54 @@
"use strict";
const locreq = require("locreq")(__dirname);
-const Errors = require("../../response/error.js");
+const Errors = locreq("lib/response/error.js");
const human_comparators_to_query = {
">": "$gt",
"gt": "$gt",
"gte": "$gte",
">=": "$gte",
"=>": "$gte",
"<": "$lt",
"lt": "$lt",
"lte": "$lte",
"<=": "$lte",
"=<": "$lte",
+ "=": "$eq",
};
module.exports = {
name: "int",
get_description: function(){
return "An integer number.";
},
is_proper_value: function(context, params, new_value){
if (new_value === null || isNaN(new_value) === true || new_value % 1 !== 0){
return Promise.reject(`Value '${new_value}' is not a int number format.`);
} else {
return Promise.resolve();
}
},
encode: function(context, params, value_in_code){
const parsed_int = parseInt(value_in_code);
return parsed_int;
},
filter_to_query: function(context, params, field_filter){
const self = this;
// treating filter as a query here
if (typeof field_filter === "object"){
const new_filter = {};
for(const comparator in field_filter){
const new_comparator = human_comparators_to_query[comparator];
if(new_comparator === undefined){
- throw new Errors.ValidationError("Unknown comparator: '" + comparator + "'.");
+ throw new Errors.ValidationError(`Unknown comparator: '${ comparator }'.`);
}
new_filter[new_comparator] = parseInt(field_filter[comparator]);
}
return new_filter;
} else {
return {
$eq: parseInt(field_filter),
};
}
},
};
diff --git a/lib/app/base-chips/field-types/session-id.js b/lib/app/base-chips/field-types/session-id.js
new file mode 100644
index 00000000..6d9d9d5c
--- /dev/null
+++ b/lib/app/base-chips/field-types/session-id.js
@@ -0,0 +1,10 @@
+const uuid = require("node-uuid").v4;
+
+const session_id = {
+ name: "session-id",
+ is_proper_value: () => Promise.resolve(),
+ encode: (context, params, value) => value? value : uuid(),
+ decode: (context, params, value) => value,
+};
+
+module.exports = session_id;
diff --git a/lib/app/base-chips/field-types/single_reference.js b/lib/app/base-chips/field-types/single_reference.js
new file mode 100644
index 00000000..cc754598
--- /dev/null
+++ b/lib/app/base-chips/field-types/single_reference.js
@@ -0,0 +1,60 @@
+"use strict";
+const locreq = require("locreq")(__dirname);
+const Collection = locreq("lib/chip-types/collection.js");
+
+module.exports = function(app){
+ return {
+ name: "single_reference",
+ is_proper_value: function(context, params, new_value){
+ const collection = new Collection(app, params.collection);
+ let resource_id;
+ if (typeof new_value === "string"){
+ resource_id = new_value;
+ } else if (typeof new_value === "object"){
+ resource_id = new_value.id;
+ }
+ return app.run_action(context, ["collections", collection.name, resource_id], "show")
+ .catch({type: "not_found"}, (error) => Promise.reject(error.message));
+ },
+ encode: function(context, params, value_in_code){
+ let resource_id;
+ if (typeof value_in_code === "string"){
+ resource_id = value_in_code;
+ } else if (typeof value_in_code === "object"){
+ resource_id = value_in_code.id;
+ }
+ return resource_id;
+ },
+ format: function(context, params, decoded_value, format_params){
+ if (format_params === "expand"){
+ if (decoded_value === undefined){
+ return undefined;
+ }
+ const collection = new Collection(params.collection);
+ const resource_id = decoded_value;
+ const action = new app.Action(["collections", collection.name, resource_id], "show");
+ return action.perform(context);
+ } else {
+ return decoded_value;
+ }
+ },
+ filter_to_query: function(context, params, field_filter){
+ // treating filter as a query here
+ if (typeof field_filter === "object"){
+ const collection = new Collection(params.collection);
+ return context.run_action(["collections", collection.name], "show", {filter: field_filter})
+ .map(function(resource){
+ return resource.id;
+ }).then(function(id_array){
+ return {
+ $in: id_array,
+ };
+ });
+ } else {
+ return {
+ $eq: field_filter,
+ };
+ }
+ },
+ };
+};
diff --git a/lib/base-chips/field-types/text.js b/lib/app/base-chips/field-types/text.js
similarity index 100%
rename from lib/base-chips/field-types/text.js
rename to lib/app/base-chips/field-types/text.js
diff --git a/lib/app/base-chips/field-types/username.js b/lib/app/base-chips/field-types/username.js
new file mode 100644
index 00000000..2f1717e2
--- /dev/null
+++ b/lib/app/base-chips/field-types/username.js
@@ -0,0 +1,27 @@
+"use strict";
+const locreq = require("locreq")(__dirname);
+const me_synonyms = locreq("lib/misc/me-synonyms.json");
+const SuperContext = locreq("lib/super-context.js");
+
+module.exports = function(app){
+ return {
+ name: "username",
+ extends: "text",
+ is_proper_value: function(context, params, new_value, old_value){
+ if (old_value === new_value){
+ return Promise.resolve();
+ } else if (me_synonyms.indexOf(new_value) !== -1){
+ return Promise.reject(`'${new_value}'' is a reserved keyword. Please pick another username.`);
+ } else {
+ return app.run_action(new SuperContext(context), ["collections", "users"], "show", {filter:{username: new_value}})
+ .then(function(results){
+ if (results.length === 0){
+ return Promise.resolve();
+ } else {
+ return Promise.reject("Username already taken");
+ }
+ });
+ }
+ }
+ };
+};
diff --git a/lib/app/chip-manager.js b/lib/app/chip-manager.js
new file mode 100644
index 00000000..5a89095f
--- /dev/null
+++ b/lib/app/chip-manager.js
@@ -0,0 +1,104 @@
+"use strict";
+const locreq = require("locreq")(__dirname);
+const Promise = require("bluebird");
+const Errors = locreq("lib/response/error.js");
+
+const ChipManager = function(app){
+ this.app = app;
+ this.chips = {};
+};
+
+ChipManager.chip_type_start_order = ["access_strategy_type", "field_type", "collection", "channel"];
+
+ChipManager.pure = {
+ start_chips: function(app, chips){
+ app.Logger.info("Starting all chips:");
+ const promises = [];
+ const datastore = ChipManager.pure.get_datastore_chip(app, chips);
+
+ let promise = datastore.start();
+ promises.push(promise);
+ app.Logger.info(`\t \u2713 ${datastore.name}`);
+
+ for (const i in ChipManager.chip_type_start_order){
+ const type = ChipManager.chip_type_start_order[i];
+ app.Logger.info(` ${type}:`);
+ for (const name in chips[type]){
+ const chip = chips[type][name];
+ app.Logger.info(`\t \u2713 ${name}`);
+ try {
+ if (chip.start){
+ promise = chip.start();
+ promises.push(promise);
+ }
+ } catch (error){
+ app.Logger.error(`\t " + "couldn't start "${name}"`);
+ return Promise.reject(error);
+ }
+ }
+ }
+ return Promise.all(promises);
+ },
+ add_chip: function(chips, type, name, chip){
+ if (chips[type] === undefined){
+ chips[type] = [];
+ }
+ if(chips[type][name]) throw Error(`Chip '${type}.${name}' already exists!`);
+ chips[type][name] = chip;
+ },
+ get_all_collections: function(chips){
+ const names = [];
+ for (const collection in chips.collection){
+ names.push(collection);
+ }
+ return names;
+ },
+ get_chip: function(chips, type, name){
+ try {
+ const ret = chips[type][name];
+ if (ret === undefined){
+ throw new Error(`Chip of type ${type} and name ${name} has not yet been registered`);
+ }
+ return ret;
+ } catch (e){
+ throw new Errors.ValidationError(`ChipManager was asked to return a chip of type "${type}" and name "${name}", but it was not found`, {}, {short_message: "chip_not_found"});
+ }
+ },
+ get_chip_amount_by_type: function(chips, type){
+ if (chips[type]){
+ return Object.keys(chips[type]).length;
+ } else {
+ return 0;
+ }
+ },
+ get_datastore_chip: function(app, chips){
+ const datastore_chip_amount = ChipManager.pure.get_chip_amount_by_type(chips, "datastore");
+ if (datastore_chip_amount === 0){
+ throw new 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){
+ return chips["datastore"][Object.keys(chips["datastore"])[0]];
+ } else {
+ const datastore_chip_name = app.ConfigManager.get_config().core.datastore;
+ if (datastore_chip_name === undefined){
+ throw 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 ChipManager.pure.get_chip(chips, "datastore", datastore_chip_name);
+ }
+ }
+ },
+ get_chips_by_type: function(chips, chip_type){
+ return chips[chip_type];
+ },
+};
+
+ChipManager.prototype = {
+ start_chips(){ return ChipManager.pure.start_chips(this.app, this.chips);},
+ add_chip(type, name, chip){return ChipManager.pure.add_chip(this.chips, type, name, chip);},
+ get_all_collections(){ return ChipManager.pure.get_all_collections(this.chips);},
+ get_chip(type, name){ return ChipManager.pure.get_chip(this.chips, type, name);},
+ get_chip_amount_by_type(type){ return ChipManager.pure.get_chip_amount_by_type(this.chips, type);},
+ get_datastore_chip(){return ChipManager.pure.get_datastore_chip(this.app, this.chips);},
+ get_chips_by_type(chip_type){return ChipManager.pure.get_chips_by_type(this.chips, chip_type);},
+};
+
+module.exports = ChipManager;
diff --git a/lib/app/config-manager.js b/lib/app/config-manager.js
new file mode 100644
index 00000000..ca5eaf64
--- /dev/null
+++ b/lib/app/config-manager.js
@@ -0,0 +1,146 @@
+"use strict";
+const locreq = require("locreq")(__dirname);
+const merge = require("merge");
+const path = require("path");
+const fs = require("fs");
+const yaml = require("js-yaml");
+const get_main_app_dir = locreq("lib/utils/get-main-app-dir.js");
+
+const ConfigManager = function(){
+ this.default_config = {};
+ this.config = {};
+};
+
+ConfigManager.pure = {
+ load_default_config_for_dir: function(default_config_arg, config_arg, dir){
+ const default_config_file = path.join(dir, "default_config.yml");
+ try{
+ const default_config = yaml.safeLoad(fs.readFileSync(default_config_file, "utf8"));
+ return ConfigManager.pure.set_default_config(
+ default_config_arg,
+ config_arg,
+ merge.recursive(default_config_arg, default_config)
+ );
+ }catch(e){
+ if(e.code === "ENOENT"){
+ return null;
+ }else{
+ throw e;
+ }
+ }
+ },
+ load_custom_config: function(default_config, config, app_dir){
+ // we're using console.log here because Logger will not be loaded by now, as it needs config to work.
+ const log = global.console.log.bind(console);
+ const log_error = global.console.error.bind(console);
+ const default_file_path = path.resolve(app_dir, "./sealious.yml");
+ log("Looking for custom config from file in:", default_file_path);
+ const custom_config_file = path.resolve(default_file_path);
+ try {
+ const custom_config = yaml.safeLoad(fs.readFileSync(custom_config_file, "utf8"));
+ log("-----");
+ log("custom config:", "\n", yaml.safeDump(custom_config));
+ log("-----");
+ return ConfigManager.pure.set_config(default_config, config, custom_config);
+ } catch(e){
+ if(e.name === "YAMLException"){
+ log_error(`Syntax error in sealious.yml:\n#{e.message}`);
+ process.exit(1);
+ } else if (e.code === "ENOENT"){
+ log("\n\n\tNo 'sealious.yml' file detected.\n\tConsider creating it alongside your app's package.json file if you want to configure the app's chips.\n\n");
+ } else {
+ log_error(e);
+ process.exit(1);
+ }
+ return null;
+ }
+ },
+ set_config: function(default_config, config, key, new_config){
+ if (arguments.length === 3){
+ return [default_config, arguments[2]];
+ } else {
+ return ConfigManager.pure.modify_config(default_config, config, false, key, new_config);
+ }
+ },
+ set_default_config: function(default_config, config, key, value){
+ if (arguments.length === 3){
+ return [arguments[2], config];
+ } else {
+ return ConfigManager.pure.modify_config(default_config, config, true, key, value);
+ }
+ },
+ get_configuration: function(default_config, config, key){
+ let to_merge_left = default_config;
+ let to_merge_right = config;
+ const key_elements = key === undefined ? [] : key.split(".");
+ while (key_elements.length){
+ const 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];
+ }
+ const merged = merge.recursive(true, to_merge_left, to_merge_right);
+ return merged;
+ },
+ modify_config: function(default_config, config, is_default_config, key, value){
+ const key_elements = key.split(".");
+ const new_values = {};
+ let current_position = new_values;
+ for (let i = 0; i < key_elements.length - 1; i++){
+ const 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){
+ default_config = merge.recursive(true, default_config, new_values);
+ } else {
+ config = merge.recursive(true, config, new_values);
+ }
+ return [default_config, config];
+ },
+};
+
+ConfigManager.prototype = {
+ apply_changes: function(config_array){
+ // config_array is [default_config, config] or null;
+ if(config_array === null) return;
+ if(config_array instanceof Array){
+ this.default_config = config_array[0];
+ this.config = config_array[1];
+ }else{
+ throw new Error(`Bad configuration array:${ config_array.toString()}`);
+ }
+ },
+ load_default_config_for_dir: function(dir){
+ return this.apply_changes(
+ ConfigManager.pure.load_default_config_for_dir(this.default_config, this.config, dir)
+ );
+ },
+ load_custom_config: function(app_dir){
+ return this.apply_changes(
+ ConfigManager.pure.load_custom_config(this.default_config, this.config, app_dir)
+ );
+ },
+ set_config: function(key, value){
+ return this.apply_changes(
+ ConfigManager.pure.set_config(this.default_config, this.config, key, value)
+ );
+ },
+ set_default_config: function(key, value){
+ return this.apply_changes(
+ ConfigManager.pure.set_default_config(this.default_config, this.config, key, value)
+ );
+ },
+ get_configuration: function(key){
+ return ConfigManager.pure.get_configuration(this.default_config, this.config, key);
+ },
+ modify_config: function(is_default_config, key, value){
+ return this.apply_changes(
+ ConfigManager.pure.modify_config(this.default_config, this.config, is_default_config, key, value)
+ );
+ },
+};
+
+ConfigManager.prototype.get_config = ConfigManager.prototype.get_configuration;
+
+module.exports = ConfigManager;
diff --git a/lib/app/file-manager.js b/lib/app/file-manager.js
new file mode 100644
index 00000000..596461ca
--- /dev/null
+++ b/lib/app/file-manager.js
@@ -0,0 +1,64 @@
+"use strict";
+const locreq = require("locreq")(__dirname);
+const Promise = require("bluebird");
+const UUIDGenerator = require("shortid");
+const path = require("path");
+const fs = require("fs");
+
+const File = locreq("lib/data-structures/file.js");
+
+function FileManager(datastore, logger, upload_path){
+ this.datastore = datastore;
+ this.logger = logger;
+ this.upload_path = upload_path;
+
+ if (!fs.existsSync(this.upload_path)){
+ fs.mkdirSync(this.upload_path);
+ }
+}
+
+FileManager.pure = {
+ save_file: function(datastore, upload_path, file){
+ const newID = UUIDGenerator();
+ const upload_path_with_sealious_name = `${upload_path }/${ newID}`;
+ return Promise.promisify(fs.writeFile)(upload_path_with_sealious_name, file.data)
+ .then(function(){
+ const file_database_entry = {
+ original_name: file.filename,
+ creation_context: file.context,
+ id: newID,
+ mime_type: file.mime,
+ };
+ return datastore.insert("files", file_database_entry, {});
+ }).then(function(){
+ return {
+ id: newID,
+ filename: file.filename
+ };
+ });
+ },
+ find: function(datastore, upload_path, context, query){
+ return datastore.find("files", query)
+ .then(function(documents){
+ const parsed_documents = documents.map(function(document){
+ const ret = File.from_db_entry(document);
+ ret.path_on_hdd = path.resolve(upload_path, `./${ ret.id}`);
+ return ret;
+ });
+ return Promise.resolve(parsed_documents);
+ });
+ },
+ get_by_id: function(datastore, upload_path, context, file_id){
+ return FileManager.pure.find(datastore, upload_path, context, {id: file_id})
+ .then(function(file_array){
+ return Promise.resolve(file_array[0]);
+ });
+ },
+};
+
+FileManager.prototype = {
+ save_file(file){ return FileManager.pure.save_file(this.datastore, this.upload_path, file);},
+ find(context, query){return FileManager.pure.find(this.datastore, this.upload_path, context, query);},
+};
+
+module.exports = FileManager;
diff --git a/lib/app/load-base-chips.js b/lib/app/load-base-chips.js
new file mode 100644
index 00000000..5af8b778
--- /dev/null
+++ b/lib/app/load-base-chips.js
@@ -0,0 +1,52 @@
+"use strict";
+
+const locreq = require("locreq")(__dirname);
+
+const AccessStrategyType = locreq("lib/chip-types/access-strategy-type.js");
+const FieldType = locreq("lib/chip-types/field-type.js");
+const Collection = locreq("lib/chip-types/collection.js");
+
+const BaseChips = new Map();
+
+BaseChips.set(AccessStrategyType, ["and", "logged_in", "noone", "not", "or", "owner", "public", "super", "themselves"]);
+BaseChips.set(FieldType, [
+ "boolean",
+ "color",
+ "context",
+ "date",
+ "datetime",
+ "email",
+ "file",
+ "float",
+ "int",
+ "single_reference",
+ "text",
+ "hashed-text",
+ "username",
+ "session-id",
+ "html",
+]);
+BaseChips.set(Collection, ["users", "sessions"]);
+
+const BaseChipDirs = new Map();
+BaseChipDirs.set(AccessStrategyType, "access-strategy-types");
+BaseChipDirs.set(FieldType, "field-types");
+BaseChipDirs.set(Collection, "collections");
+
+function load_base_chips(app){
+
+ BaseChips.forEach(function(names, constructor){
+ for(const i in names){
+ const chip_name = names[i];
+ let declaration = locreq(
+ `lib/app/base-chips/${ BaseChipDirs.get(constructor) }/${ chip_name }.js`
+ );
+ if(declaration instanceof Function){
+ declaration = declaration(app);
+ }
+ app.createChip(constructor, declaration);
+ }
+ });
+}
+
+module.exports = load_base_chips;
diff --git a/lib/app/logger.js b/lib/app/logger.js
new file mode 100644
index 00000000..09616af6
--- /dev/null
+++ b/lib/app/logger.js
@@ -0,0 +1,100 @@
+"use strict";
+const locreq = require("locreq")(__dirname);
+const winston = require("winston");
+const getDateTime = locreq("lib/utils/get-datetime.js");
+
+/*
+ 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
+
+*/
+
+const Logger = function(app){
+ const transports_array = [];
+
+ const logger_level = app.ConfigManager.get_config().logger.level;
+ const logger_color = app.ConfigManager.get_config().logger.color;
+ const logger_file = app.ConfigManager.get_config().logger.file;
+ const logger_dirname = app.ConfigManager.get_config().logger.dirname;
+ const logger_to_json = app.ConfigManager.get_config().logger.to_json;
+ const logger_rotation = app.ConfigManager.get_config().logger.rotation;
+
+
+ const 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){
+ const 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,
+ });
+ const 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);
+ }
+
+ const logger = new winston.Logger({
+ levels: Logger.custom.levels,
+ colors: Logger.custom.colors,
+ transports: transports_array,
+ });
+
+ logger.rewriters.push(function(level, msg, meta){
+ let ret = "";
+ if (Object.keys(meta).length){
+ let message = "\n";
+ for (const prop in meta){
+ message += ` - ${ prop }: ${ JSON.stringify(meta[prop]) }\n`;
+ }
+ ret = message;
+ }
+ if(meta instanceof Error){
+ ret += meta.stack;
+ }
+
+ return ret;
+ });
+
+ return logger;
+};
+
+Logger.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",
+ },
+};
+
+module.exports = Logger;
diff --git a/lib/app/plugin-manager.js b/lib/app/plugin-manager.js
new file mode 100644
index 00000000..cc9a4eb6
--- /dev/null
+++ b/lib/app/plugin-manager.js
@@ -0,0 +1,87 @@
+"use strict";
+const uncarried_locrec = require("locreq");
+const locreq = uncarried_locrec(__dirname);
+const path = require("path");
+const fs = require("fs");
+const resolve = require("resolve");
+
+function custom_resolve (plugin_name, root){
+ try {
+ return resolve.sync(plugin_name, {basedir: root});
+ } catch (error){
+ return require.resolve(plugin_name);
+ }
+}
+
+function PluginManager(ConfigManager, Logger){
+ this.ConfigManager = ConfigManager;
+ this.Logger = Logger;
+ this.loaded_plugins = [];
+}
+
+PluginManager.pure = {
+ is_sealious_plugin: function(dir, module_name){
+ const plugin_package_info = PluginManager.pure.get_package_info(dir, module_name);
+ return plugin_package_info.keywords && plugin_package_info.keywords.indexOf("sealious-plugin") !== -1;
+ },
+ get_package_info: function(dir, package_name){
+ return require(PluginManager.pure.get_package_info_path(dir, package_name));
+ },
+ get_package_info_path: function(dir, package_name){
+ let package_path = custom_resolve(package_name, dir);
+ let package_info_path = null;
+ while (package_info_path === null){
+ const temp_path = path.resolve(package_path, "../package.json");
+ try {
+ fs.accessSync(temp_path, fs.F_OK);
+ package_info_path = temp_path;
+ } catch (e){
+ package_path = path.resolve(package_path, "../");
+ }
+ }
+ return package_info_path;
+ },
+ load_plugins: function(Logger, ConfigManager, plugins, sealious_dir, app){
+ Logger.info("Loading plugins...");
+ if (sealious_dir !== path.resolve("")){
+ PluginManager.pure.load_plugins_from_dir(Logger, ConfigManager, plugins, sealious_dir, app);
+ }
+ PluginManager.pure.load_plugins_from_dir(Logger, ConfigManager, plugins, "", app);
+ },
+ load_plugins_from_dir: function(Logger, ConfigManager, loaded_plugins, dir, app){
+ const root = path.resolve(dir);
+ const pkgfile = uncarried_locrec(dir).resolve("package.json");
+ const pkg = require(pkgfile);
+
+ const dependencies = pkg.dependencies || {};
+ const required_sealious_plugins = Object.keys(dependencies)
+ .filter(PluginManager.pure.is_sealious_plugin.bind({}, root));
+
+
+ if (required_sealious_plugins.length){
+ Logger.debug(`${pkg.name} (${pkgfile}) requires: ${required_sealious_plugins.join(", ")}`);
+ for (const i in required_sealious_plugins){
+ const plugin_name = required_sealious_plugins[i];
+ const plugin_info_path = PluginManager.pure.get_package_info_path(root, plugin_name);
+ const plugin_dir = path.resolve(plugin_info_path, "../");
+ ConfigManager.load_default_config_for_dir(plugin_dir);
+ PluginManager.pure.load_plugins_from_dir(Logger, ConfigManager, loaded_plugins, plugin_dir, app);
+ if(loaded_plugins.indexOf(plugin_name) === -1){
+ require(custom_resolve(plugin_name, plugin_dir))(app);
+ loaded_plugins.push(plugin_name);
+ Logger.info(`\t\u2713 ${plugin_name} (${plugin_dir})`);
+ }else{
+ Logger.info(`\ ${plugin_name} (already loaded)`);
+ }
+ }
+ }
+ }
+};
+
+// not all pure methods are kept here, as they're not intended to be called from outside
+
+PluginManager.prototype = {
+ load_plugins: function(sealious_dir, app){return PluginManager.pure.load_plugins(this.Logger, this.ConfigManager, this.loaded_plugins, sealious_dir, app);},
+};
+
+module.exports = PluginManager;
diff --git a/lib/app/run-action-curry.js b/lib/app/run-action-curry.js
new file mode 100644
index 00000000..0b6403da
--- /dev/null
+++ b/lib/app/run-action-curry.js
@@ -0,0 +1,15 @@
+"use strict";
+const locreq = require("locreq")(__dirname);
+
+
+function run_action_curry(app){
+ return function run_action(context, subject_path, action_name, params){
+ return app.RootSubject.get_subject(subject_path)
+ .then(function(subject){
+ return subject.perform_action(context, action_name, params);
+ });
+ };
+}
+
+
+module.exports = run_action_curry;
diff --git a/lib/base-chips/_base-chips.js b/lib/base-chips/_base-chips.js
deleted file mode 100644
index 568e43dd..00000000
--- a/lib/base-chips/_base-chips.js
+++ /dev/null
@@ -1,43 +0,0 @@
-"use strict";
-
-const locreq = require("locreq")(__dirname);
-
-const fs = require("fs");
-const path = require("path");
-
-const AccessStrategyType = locreq("lib/chip-types/access-strategy-type.js");
-const FieldType = locreq("lib/chip-types/field-type.js");
-const Collection = locreq("lib/chip-types/collection.js");
-
-const access_strategy_types = ["and", "logged_in", "noone", "not", "or", "owner", "public", "super", "themselves"];
-const field_types = [
- "boolean",
- "color",
- "context",
- "date",
- "datetime",
- "email",
- "file",
- "float",
- "int",
- "single_reference",
- "text",
- "hashed-text",
- "username",
- "html",
-];
-
-for(const i in access_strategy_types){
- const type_name = access_strategy_types[i];
- const declaration = require("./access-strategy-types/" + type_name);
- new AccessStrategyType(declaration);
-}
-
-for(const i in field_types){
- const type_name = field_types[i];
- const declaration = require("./field-types/" + type_name);
- new FieldType(declaration);
-}
-
-
-new Collection(require("./collection.users.js"));
diff --git a/lib/base-chips/field-types/file.js b/lib/base-chips/field-types/file.js
deleted file mode 100644
index a0f84ccf..00000000
--- a/lib/base-chips/field-types/file.js
+++ /dev/null
@@ -1,85 +0,0 @@
-"use strict";
-const locreq = require("locreq")(__dirname);
-const Promise = require("bluebird");
-const File = locreq("lib/data-structures/file.js");
-const FileManager = locreq("lib/core-services/file-manager.js");
-const rp = require("request-promise");
-const url = require("url");
-
-module.exports = {
- name: "file",
- handles_large_data: true,
- is_proper_value: function(context, params, value){
- if (value === undefined){
- return undefined;
- }
- if (typeof value == "string"){
- return rp({url: value, encoding: null})
- .then(function(){
- return Promise.resolve();
- }).catch(function(){
- return Promise.reject("There was a problem while getting the file: '" + value + "'. Is the URL correct?");
- });
- }
- if (value === null
- || value === ""
- || (value instanceof File)
- || (value.filename !== undefined && value.data instanceof Buffer)
- ){
- return Promise.resolve();
- } else {
- let 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. Should be Sealious.File, but received ${type}`);
- }
- },
- encode: function(context, params, value_in_code){
- if(typeof value_in_code === "string"){
- return rp({url: value_in_code, encoding: null})
- .then(function(file_buffer){
- const filename = url.parse(value_in_code).pathname.split("/").pop();
- const file = new File(context, filename, file_buffer);
- return FileManager.save_file(file);
- });
- }
- if (value_in_code){
- return FileManager.save_file(value_in_code);
- } else {
- return null;
- }
- },
- decode: function(context, params, value_in_database){
- if (value_in_database){
- return Promise.resolve(new File.Reference(value_in_database.id, value_in_database.filename));
- } else if (params.no_file_value){
- return params.no_file_value;
- } else {
- return undefined;
- }
- },
- format: function(context, params, decoded_value, format){
- if (format === "url"){
- return `/api/v1/uploaded-files/${decoded_value.id}/${decoded_value.filename}`;
- } else if (format === "url-with-filename"){
- if (decoded_value === undefined){
- return {
- url: params.no_file_value || "",
- filename: null,
- empty: true,
- };
- } else {
- return {
- url: `/api/v1/uploaded-files/${decoded_value.id}/${decoded_value.filename}`,
- filename: decoded_value.filename,
- empty: false,
- };
- }
- } else {
- return decoded_value;
- }
- },
-};
diff --git a/lib/base-chips/field-types/single_reference.js b/lib/base-chips/field-types/single_reference.js
deleted file mode 100644
index 5e147f2c..00000000
--- a/lib/base-chips/field-types/single_reference.js
+++ /dev/null
@@ -1,60 +0,0 @@
-"use strict";
-const locreq = require("locreq")(__dirname);
-const Collection = locreq("lib/chip-types/collection.js");
-const Action = locreq("lib/action.js");
-
-module.exports = {
- name: "single_reference",
- is_proper_value: function(context, params, new_value){
- const collection = new Collection(params.collection);
- let resource_id;
- if (typeof new_value === "string"){
- resource_id = new_value;
- } else if (typeof new_value === "object"){
- resource_id = new_value.id;
- }
- const action = new Action(["collections", collection.name, resource_id], "show");
- return action.perform(context)
- .catch({type: "not_found"}, (error) => Promise.reject(error.message));
- },
- encode: function(context, params, value_in_code){
- let resource_id;
- if (typeof value_in_code === "string"){
- resource_id = value_in_code;
- } else if (typeof value_in_code === "object"){
- resource_id = value_in_code.id;
- }
- return resource_id;
- },
- format: function(context, params, decoded_value, format_params){
- if (format_params === "expand"){
- if (decoded_value === undefined){
- return undefined;
- }
- const collection = new Collection(params.collection);
- const resource_id = decoded_value;
- const action = new Action(["collections", collection.name, resource_id], "show");
- return action.perform(context);
- } else {
- return decoded_value;
- }
- },
- filter_to_query: function(context, params, field_filter){
- // treating filter as a query here
- if (typeof field_filter === "object"){
- const collection = new Collection(params.collection);
- return context.run_action(["collections", collection.name], "show", {filter: field_filter})
- .map(function(resource){
- return resource.id;
- }).then(function(id_array){
- return {
- $in: id_array,
- };
- });
- } else {
- return {
- $eq: field_filter,
- };
- }
- },
-};
diff --git a/lib/base-chips/field-types/username.js b/lib/base-chips/field-types/username.js
deleted file mode 100644
index 0e9fcfbe..00000000
--- a/lib/base-chips/field-types/username.js
+++ /dev/null
@@ -1,26 +0,0 @@
-"use strict";
-const locreq = require("locreq")(__dirname);
-const me_synonyms = locreq("lib/misc/me-synonyms.json");
-const SuperContext = locreq("lib/super-context.js");
-const run_action = locreq("lib/utils/run-action.js");
-
-module.exports = {
- name: "username",
- extends: "text",
- is_proper_value: function(context, params, new_value, old_value){
- if (old_value === new_value){
- return Promise.resolve();
- } else if (me_synonyms.indexOf(new_value) !== -1){
- return Promise.reject(`'${new_value}'' is a reserved keyword. Please pick another username.`);
- } else {
- run_action(new SuperContext(context), ["resources", "user"], "show", {filter:{username: new_value}})
- .then(function(results){
- if (results.length === 0){
- return Promise.resolve();
- } else {
- return Promise.reject("Username already taken");
- }
- });
- }
- },
-};
diff --git a/lib/chip-types/access-strategy-type.js b/lib/chip-types/access-strategy-type.js
index 54ecc448..f6ee91f3 100644
--- a/lib/chip-types/access-strategy-type.js
+++ b/lib/chip-types/access-strategy-type.js
@@ -1,70 +1,67 @@
"use strict";
const locreq = require("locreq")(__dirname);
const Promise = require("bluebird");
-const Chip = require("./chip.js");
const Errors = locreq("lib/response/error.js");
-const ChipManager = locreq("lib/chip-types/chip-manager.js");
+const Chip = locreq("lib/chip-types/chip.js");
-function AccessStrategyType(declaration){
+function AccessStrategyType(app, declaration){
if (declaration instanceof AccessStrategyType){
return declaration;
} else if (typeof declaration === "string"){
- return ChipManager.get_chip("access_strategy_type", declaration);
+ return app.ChipManager.get_chip("access_strategy_type", declaration);
}
- Chip.call(this, "access_strategy_type", declaration.name);
this.declaration = declaration;
this.checker_function = null;
this.name = declaration.name;
+ this.app = app;
if (declaration){
- this._process_declaration(declaration);
+ this.checker_function = declaration.checker_function === undefined ? null : declaration.checker_function;
}
}
-AccessStrategyType.prototype._process_declaration = function(declaration){
- this.checker_function = declaration.checker_function === undefined ? null : declaration.checker_function;
-};
-AccessStrategyType.prototype.__is_item_sensitive = function(declaration, params){
- if (typeof declaration.item_sensitive === "function"){
- return Promise.resolve(declaration.item_sensitive(params));
- } else {
- return Promise.resolve(Boolean(declaration.item_sensitive));
- }
-};
-AccessStrategyType.prototype.__check = function(declaration, context, params, item){
- if (context.is_super){
- return Promise.resolve();
- }
- return this.__is_item_sensitive(declaration, params)
- .then(function(is_item_sensitive){
- if (is_item_sensitive && item === undefined){
- return Promise.resolve(undefined);
- } else {
- return Promise.try(function(){
- return Promise.method(declaration.checker_function)(context, params, item)
- .then(function(result){
- if (result === false){
- return Promise.reject("Access denied");
- } else {
- return Promise.resolve(result);
- }
- });
- });
+AccessStrategyType.type_name = "access_strategy_type";
+
+AccessStrategyType.pure = {
+ check: function(declaration, context, params, item){
+ if (context.is_super){
+ return Promise.resolve();
}
- }).catch(function(error){
- if (typeof error === "string"){
- return Promise.reject(new Errors.BadContext(error));
+ return AccessStrategyType.pure.is_item_sensitive(declaration, params)
+ .then(function(is_item_sensitive){
+ if (is_item_sensitive && item === undefined){
+ return Promise.resolve(undefined);
+ } else {
+ return Promise.try(function(){
+ return Promise.method(declaration.checker_function)(context, params, item)
+ .then(function(result){
+ if (result === false){
+ return Promise.reject("Access denied");
+ } else {
+ return Promise.resolve(result);
+ }
+ });
+ });
+ }
+ }).catch(function(error){
+ if (typeof error === "string"){
+ return Promise.reject(new Errors.BadContext(error));
+ } else {
+ return Promise.reject(error);
+ }
+ });
+ },
+ is_item_sensitive: function(declaration, params){
+ if (typeof declaration.item_sensitive === "function"){
+ return Promise.resolve(declaration.item_sensitive(params));
} else {
- return Promise.reject(error);
+ return Promise.resolve(Boolean(declaration.item_sensitive));
}
- });
-};
-AccessStrategyType.prototype.is_item_sensitive = function(params){
- return this.__is_item_sensitive(this.declaration, params);
-};
-AccessStrategyType.prototype.check = function(context, params, item){
- return this.__check(this.declaration, context, params, item);
+ }
};
-AccessStrategyType.type_name = "access_strategy_type";
+AccessStrategyType.prototype = {
+ check(context, params, item){return AccessStrategyType.pure.check(this.declaration, context, params, item);},
+ is_item_sensitive(params){return AccessStrategyType.pure.is_item_sensitive(this.declaration, params);},
+};
module.exports = AccessStrategyType;
diff --git a/lib/chip-types/access-strategy.js b/lib/chip-types/access-strategy.js
index a35fa50c..12d24910 100644
--- a/lib/chip-types/access-strategy.js
+++ b/lib/chip-types/access-strategy.js
@@ -1,28 +1,29 @@
"use strict";
const locreq = require("locreq")(__dirname);
const Promise = require("bluebird");
const AccessStrategyType = locreq("lib/chip-types/access-strategy-type.js");
-const AccessStrategy = function(declaration){
+const AccessStrategy = function(app, declaration){
if (declaration instanceof Array){
- this.type = new AccessStrategyType(declaration[0]);
+ this.type = new AccessStrategyType(app, declaration[0]);
this.params = declaration[1] || {};
} else if (typeof declaration === "string" || declaration instanceof AccessStrategyType){
- this.type = new AccessStrategyType(declaration);
+ this.type = new AccessStrategyType(app, declaration);
this.params = {};
} else {
- this.type = new AccessStrategyType(declaration.type);
+ this.type = new AccessStrategyType(app, declaration.type);
this.params = declaration.params || {};
}
};
+AccessStrategy.type_name = "AccessStrategy";
+
AccessStrategy.prototype.check = function(context, item){
return Promise.resolve(this.type.check(context, this.params, item));
};
AccessStrategy.prototype.is_item_sensitive = function(){
return this.type.is_item_sensitive(this.params);
};
-
module.exports = AccessStrategy;
diff --git a/lib/chip-types/channel.js b/lib/chip-types/channel.js
index 0dd2f92d..a3ba5b8d 100644
--- a/lib/chip-types/channel.js
+++ b/lib/chip-types/channel.js
@@ -1,21 +1,11 @@
"use strict";
const locreq = require("locreq")(__dirname);
-const chip = require("./chip.js");
-const ChipManager = locreq("lib/chip-types/chip-manager");
-/*
-Represents channel.
-@constructor
-@param {string} name - name of channel
-return void
-*/
-function channel (name){
- this.name = name;
- this.longid = `channel.${name}`;
- this.default_configuration = {};
- ChipManager.add_chip("channel", this.name, this);
-}
+const channel = function(app, declaration){
+ this.name = declaration.name;
+ this.longid = `channel.${declaration.name}`;
+};
-channel.prototype = new chip();
+channel.type_name = "channel";
module.exports = channel;
diff --git a/lib/chip-types/chip-manager.js b/lib/chip-types/chip-manager.js
deleted file mode 100644
index 2aaae3bd..00000000
--- a/lib/chip-types/chip-manager.js
+++ /dev/null
@@ -1,154 +0,0 @@
-"use strict";
-const locreq = require("locreq")(__dirname);
-const Errors = locreq("lib/response/error.js");
-const Logger = locreq("lib/logger/logger.js");
-
-const Promise = require("bluebird");
-
-const ConfigurationManager = require("../config/config-manager.js");
-
-// const chip_type_functions = {
-// channel: require("./channel.js"),
-// collection: require("./resource-type.js"),
-// field_type: require("./field-type.js"),
-// datastore: require("./datastore.js")
-// };
-
-const chips = {};
-
-const chip_type_start_order = ["access_strategy", "field_type", "collection", "channel"];
-
-const ChipManager = {
- /**
- * Starts chips in proper order.
- * @param {array} chip_types_to_start - array of names of chips we want to start
- * @returns {Promise} - Promise, which will resolve with starting chips or reject with error
- */
- start_chips: function(){
- Logger.info("Starting all chips:");
- const promises = [];
- const datastore = this.get_datastore_chip();
-
- let promise = datastore.start();
- promises.push(promise);
- Logger.info(`\t \u2713 ${datastore.name}`);
-
- for (const i in chip_type_start_order){
- const type = chip_type_start_order[i];
- Logger.info(` ${type}:`);
- for (const name in chips[type]){
- const chip = chips[type][name];
- Logger.info(`\t \u2713 ${name}`);
- try {
- if (chip.start){
- promise = chip.start();
- promises.push(promise);
- }
- } catch (error){
- Logger.error(`\t " + "couldn't start "${name}"`);
- return Promise.reject(error);
- }
- }
- }
- return Promise.all(promises);
- },
- add_chip: function(type, name, chip){
- if (chips[type] === undefined){
- chips[type] = [];
- }
- if(chips[type][name]) throw Error(`Chip '${type}.${name}' already exists!`);
- chips[type][name] = chip;
- },
- /**
- * Gets all resource types
- * @returns {array} Array of names of resource types.
- */
- __get_all_collections: function(chips){
- const names = [];
- for (const collection in chips.collection){
- names.push(collection);
- }
- return names;
- },
- get_all_collections: function(){
- return this.__get_all_collections(chips);
- },
- /**
- * Checks if chip exists
- * @param {string} type - chip type
- * @param {string} name - chip name
- * @returns {boolean} true if exists, otherwise false
- */
- chip_exists: function(type, name){
- if (chips[type] && chips[type][name]){
- return true;
- } else {
- return false;
- }
- },
- __get_chip: function(chips, type, name){
- try {
- const ret = chips[type][name];
- if (ret === undefined){
- throw new Error(`Chip of type ${type} and name ${name} has not yet been registered`);
- }
- return ret;
- } catch (e){
- throw new Errors.ValidationError(`ChipManager was asked to return a chip of type "${type}" and name "${name}", but it was not found`, {}, {short_message: "chip_not_found"});
- }
- },
- get_chip: function(type, name){
- return this.__get_chip(chips, type, name);
- },
- /*
- * Gets chip by long id
- * @param {string} longid - longid is chip_type.chip_name ex. chanell.cli
- * @returns {object} requested chip or throws error
- */
- __get_chip_by_longid: function(chips, longid){
- const type = longid.split(".")[0];
- const name = longid.split(".")[1];
- return this.__get_chip(chips, type, name);
- },
- get_chip_by_longid: function(longid){
- return this.__get_chip_by_longid(chips, longid);
- },
- __get_chip_amount_by_type: function(chips, type){
- if (chips[type]){
- return Object.keys(chips[type]).length;
- } else {
- return 0;
- }
- },
- get_chip_amount_by_type: function(type){
- return this.__get_chip_amount_by_type(chips, type);
- },
- /**
- * Gets proper datastore chip
- * @returns {object} datastore chip for application or throws error if no datastore chip is defined
- */
- get_datastore_chip: function(){
- const datastore_chip_amount = this.get_chip_amount_by_type("datastore");
- if (datastore_chip_amount === 0){
- throw new 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){
- return chips["datastore"][Object.keys(chips["datastore"])[0]];
- } else {
- const datastore_chip_name = ConfigurationManager.get_config().datastore_chip_name;
- if (datastore_chip_name === undefined){
- throw 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);
- }
- }
- },
- __get_chips_by_type: function(chips, chip_type){
- return chips[chip_type];
- },
- get_chips_by_type: function(chip_type){
- return this.__get_chips_by_type(chips, chip_type);
- }
-};
-
-
-module.exports = ChipManager;
diff --git a/lib/chip-types/chip.js b/lib/chip-types/chip.js
index 82a363a1..156c6d70 100644
--- a/lib/chip-types/chip.js
+++ b/lib/chip-types/chip.js
@@ -1,50 +1,17 @@
"use strict";
const Promise = require("bluebird");
let ChipManager;
const Chip = function(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 (name){
- ChipManager = ChipManager || require("./chip-manager.js");
- ChipManager.add_chip(type, name, this);
- }
-};
-
-Chip.prototype.apply_default_settings = function(default_config){
- for (const i in default_config){
- if (!this.configuration[i]){
- this.configuration[i] = default_config[i];
- }
- }
-};
-
-Chip.prototype.configure = function(config){
- config = config || {};
- this.configuration = config;
};
Chip.prototype.start = function(){
// to be overwritten
return Promise.resolve();
};
-// Chip.prototype.test = function(){
-// if (this.test_compatibility){
-// console.log("Starting compatibility tests for chip: `" + this.name + "`");
-// this.test_compatibility().then(function(){
-// console.log("\t✓ Compatibility test successfull!");
-// })
-// }
-// }
-
module.exports = Chip;
diff --git a/lib/chip-types/collection.js b/lib/chip-types/collection.js
index 22ebc7ad..cdd0af83 100644
--- a/lib/chip-types/collection.js
+++ b/lib/chip-types/collection.js
@@ -1,282 +1,288 @@
"use strict";
const locreq = require("locreq")(__dirname);
const Promise = require("bluebird");
const merge = require("merge");
const clone = require("clone");
-const ChipManager = locreq("lib/chip-types/chip-manager.js");
const Errors = locreq("lib/response/error.js");
const Chip = require("./chip.js");
const Field = require("./field.js");
const AccessStrategy = require("./access-strategy.js");
const AccessStrategyType = locreq("lib/chip-types/access-strategy-type.js");
-const Collection = function(declaration){
+const Collection = function(app, declaration){
if (typeof declaration === "string"){
- return ChipManager.get_chip("collection", declaration);
+ return app.ChipManager.get_chip("collection", declaration);
} else if (declaration instanceof Collection){
return declaration;
}
Chip.call(this, "collection", declaration.name);
+ this.app = app;
this.name = declaration.name;
+ this.fields = {};
this.human_readable_name = declaration.human_readable_name;
this.summary = declaration.summary;
- this.fields = {};
this.access_strategy = {
- default: new AccessStrategy("public", {}),
+ default: new AccessStrategy(app, "public", {}),
};
- this._process_declaration(declaration);
-};
-Collection.prototype._process_declaration = function(declaration){
if (declaration){
if (declaration.fields){
for (let i = 0; i < declaration.fields.length; i++){
if (declaration.fields[i].params){
if (typeof declaration.fields[i].params !== "object"){
throw new Errors.ValidationError(`In field "${declaration.fields[i].name}": "params" is of wrong type, it should be an object`);
}
}
}
this.add_fields(declaration.fields);
}
this.set_access_strategy(declaration.access_strategy);
}
};
-Collection.prototype.add_field = function(field_declaration){
- const field_object = new Field(field_declaration, this);
- const field_name = field_object.name;
- if (!this.fields[field_name]){
- this.fields[field_name] = field_object;
- }
- else {
- throw new Errors.DeveloperError(`Duplicate field names: "${field_name}" in collection: "${this.name}"`);
- }
-};
-Collection.prototype.add_fields = function(field_declarations_array){
- for (const i in field_declarations_array){
- const declaration = field_declarations_array[i];
- this.add_field(declaration);
- }
-};
-Collection.prototype.has_previous_value_sensitive_fields = function(){
- for (const field_name in this.fields){
- if (this.fields[field_name].has_previous_value_sensitive_methods()){
- return true;
+
+Collection.type_name = "collection";
+
+Collection.pure = {
+ add_field: function(app, field_type, fields, field_declaration){
+ const field_object = new Field(app, field_declaration, field_type);
+ const field_name = field_object.name;
+ if (!fields[field_name]){
+ fields[field_name] = field_object;
+ } else {
+ throw new Errors.DeveloperError(`Duplicate field names: "${field_name}" in collection: "${field_type.name}"`);
}
- }
- return false;
-};
-Collection.prototype.get_unknown_field_errors = function(values){
- const validation_errors = {};
- for (const field_name in values){
- if (this.fields[field_name] === undefined){
- validation_errors[field_name] = new Errors.ValidationError(`Unknown field '${field_name}' for resource-type '${this.name}`);
+ },
+ add_fields: function(app, field_type, fields, field_declarations_array){
+ for (const i in field_declarations_array){
+ const declaration = field_declarations_array[i];
+ Collection.pure.add_field(app, field_type, fields, declaration);
}
- }
- return validation_errors;
-};
-Collection.prototype.get_missing_values_checker = function(values, assume_delete_value_on_missing_key, old_values){
- const self = this;
- if (assume_delete_value_on_missing_key){
- return function(field_name){
- return self.fields[field_name].required && values[field_name] === undefined;
- };
- } else {
- return function(field_name){
- return self.fields[field_name].required && values[field_name] === undefined && old_values[field_name] === undefined;
- };
- }
-};
-Collection.prototype.get_missing_field_values_errors = function(values, assume_delete_value_on_missing_key, old_values){
- const self = this;
- const errors = {};
- const checker_fn = this.get_missing_values_checker(values, assume_delete_value_on_missing_key, old_values);
+ },
+ get_unknown_field_errors: function(field_type_name, fields, values){
+ const validation_errors = {};
+ for (const field_name in values){
+ if (fields[field_name] === undefined){
+ validation_errors[field_name] = new Errors.ValidationError(`Unknown field '${field_name}' for resource-type '${field_type_name}`);
+ }
+ }
+ return validation_errors;
+ },
+ get_missing_values_checker: function(fields, values, assume_delete_value_on_missing_key, old_values){
+ if (assume_delete_value_on_missing_key){
+ return function(field_name){
+ return fields[field_name].required && values[field_name] === undefined;
+ };
+ } else {
+ return function(field_name){
+ return fields[field_name].required && values[field_name] === undefined && old_values[field_name] === undefined;
+ };
+ }
+ },
+ get_missing_field_values_errors: function(fields, values, assume_delete_value_on_missing_key, old_values){
+ const errors = {};
+ const checker_fn = Collection.pure.get_missing_values_checker(fields, values, assume_delete_value_on_missing_key, old_values);
- return Promise.filter(Object.keys(self.fields), checker_fn.bind(self))
- .each(function(field_name){
- errors[field_name] = new Errors.ValidationError("Missing value for field '" + field_name + "'");
- }).then(function(){
- return errors;
- });
-};
-Collection.prototype.get_invalid_field_values_errors = function(context, values, old_values){
- const errors = {};
- const promises = [];
- for (const field_name in values){
- if (this.fields[field_name]){
- const value = values[field_name];
- const old_value = old_values? old_values[field_name] : undefined;
- const promise = this.fields[field_name].is_proper_value(context, value, old_value)
- .catch(function(error){
- if(typeof error === "string" || error.type === "validation"){
- errors[field_name] = new Errors.ValidationError(error);
- }else{
- throw error;
- }
- });
- promises.push(promise);
+ return Promise.filter(Object.keys(fields), checker_fn)
+ .each(function(field_name){
+ errors[field_name] = new Errors.ValidationError(`Missing value for field '${ field_name }'`);
+ }).then(function(){
+ return errors;
+ });
+ },
+ get_invalid_field_values_errors: function(fields, context, values, old_values){
+ const errors = {};
+ const promises = [];
+ for (const field_name in values){
+ if (fields[field_name]){
+ const value = values[field_name];
+ const old_value = old_values? old_values[field_name] : undefined;
+ const promise = fields[field_name].is_proper_value(context, value, old_value)
+ .catch(function(error){
+ if(typeof error === "string" || error.type === "validation"){
+ errors[field_name] = new Errors.ValidationError(error);
+ }else{
+ throw error;
+ }
+ });
+ promises.push(promise);
+ }
}
- }
- return Promise.all(promises)
- .then(function(){
- return errors;
- });
-};
-Collection.prototype.validate_field_values = function(context, assume_delete_value_on_missing_key, new_values, old_values){
- const self = this;
- const errors_array = [
- self.get_unknown_field_errors(new_values),
- self.get_missing_field_values_errors(new_values, assume_delete_value_on_missing_key, old_values),
- self.get_invalid_field_values_errors(context, new_values, old_values)
- ];
+ return Promise.all(promises)
+ .then(function(){
+ return errors;
+ });
+ },
+ validate_field_values: function(field_type_name, fields, context, assume_delete_value_on_missing_key, new_values, old_values){
+ const errors_array = [
+ Collection.pure.get_unknown_field_errors(field_type_name, fields, new_values),
+ Collection.pure.get_missing_field_values_errors(fields, new_values, assume_delete_value_on_missing_key, old_values),
+ Collection.pure.get_invalid_field_values_errors(fields, context, new_values, old_values)
+ ];
- return Promise.all(errors_array)
- .reduce(merge)
- .then(function(errors){
- const user_errors = {};
- const non_user_errors = {};
- for (const field_name in errors){
- const error = errors[field_name];
- if (error.is_user_fault){
- user_errors[field_name] = error;
+ return Promise.all(errors_array)
+ .reduce(merge)
+ .then(function(errors){
+ const user_errors = {};
+ const non_user_errors = {};
+ for (const field_name in errors){
+ const error = errors[field_name];
+ if (error.is_user_fault){
+ user_errors[field_name] = error;
+ } else {
+ non_user_errors[field_name] = error;
+ }
+ }
+ const non_user_errors_amount = Object.keys(non_user_errors).length;
+ if (non_user_errors_amount > 0){
+ throw non_user_errors[Object.keys(non_user_errors)[0]];
+ }
+ const user_errors_amount = Object.keys(user_errors).length;
+ if (user_errors_amount > 0){
+ throw new Errors.ValidationError("There are problems with some of the provided values.", user_errors);
+ }
+ });
+ },
+ encode_field_values: function(fields, context, body, old_body){
+ const promises = {};
+ for (const field_name in body){
+ const current_value = body[field_name];
+ if (current_value === undefined){
+ promises[field_name] = null;
} else {
- non_user_errors[field_name] = error;
+ const old_value = old_body && old_body[field_name];
+ promises[field_name] = fields[field_name].encode(context, current_value, old_value);
}
}
- const non_user_errors_amount = Object.keys(non_user_errors).length;
- if (non_user_errors_amount > 0){
- throw non_user_errors[Object.keys(non_user_errors)[0]];
+ return Promise.props(promises);
+ },
+ get_specification: function(name, human_readable_name, summary, fields, 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.
+ const collection_specification = {};
+ for (const field_name in fields){
+ const field_specification = fields[field_name].get_specification(with_validators);
+ collection_specification[field_name] = field_specification;
}
- const user_errors_amount = Object.keys(user_errors).length;
- if (user_errors_amount > 0){
- throw new Errors.ValidationError("There are problems with some of the provided values.", user_errors);
- }
- });
-};
-Collection.prototype.encode_field_values = function(context, body, old_body){
- const promises = {};
- for (const field_name in body){
- const current_value = body[field_name];
- if (current_value === undefined){
- promises[field_name] = null;
- } else {
- const old_value = old_body && old_body[field_name];
- promises[field_name] = this.fields[field_name].encode(context, current_value, old_value);
- }
- }
- return Promise.props(promises);
-};
-Collection.prototype.get_specification = 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.
- const collection_specification = {};
- for (const field_name in this.fields){
- const field_specification = this.fields[field_name].get_specification(with_validators);
- collection_specification[field_name] = field_specification;
- }
- const specification = {
- name: this.name,
- human_readable_name: this.human_readable_name,
- summary: this.summary,
- fields: collection_specification
- };
- return specification;
-};
-Collection.prototype.get_specification_with_validators = function(){
- return this.get_specification(true);
-};
-Collection.prototype.set_access_strategy = function(strategy_declaration){
- if (typeof strategy_declaration === "string" ||
- strategy_declaration instanceof AccessStrategyType ||
- strategy_declaration instanceof Array){
- this.access_strategy = {
- "default": new AccessStrategy(strategy_declaration)
+ const specification = {
+ name: name,
+ human_readable_name: human_readable_name,
+ summary: summary,
+ fields: collection_specification
};
- } else if (typeof strategy_declaration === "object"){
- for (const action_name in strategy_declaration){
- const access_strategy = strategy_declaration[action_name];
- this.access_strategy[action_name] = new AccessStrategy(access_strategy);
+ return specification;
+ },
+ set_access_strategy: function(app, field_type, strategy_declaration){
+ if (typeof strategy_declaration === "string" ||
+ strategy_declaration instanceof AccessStrategyType ||
+ strategy_declaration instanceof Array){
+ field_type.access_strategy = {
+ "default": new AccessStrategy(strategy_declaration)
+ };
+ } else if (typeof strategy_declaration === "object"){
+ for (const action_name in strategy_declaration){
+ const access_strategy = strategy_declaration[action_name];
+ field_type.access_strategy[action_name] = new AccessStrategy(app, access_strategy);
+ }
}
- }
-};
-Collection.prototype.get_access_strategy = function(action_name){
- return this.access_strategy[action_name] || this.access_strategy["default"];
-};
-Collection.prototype.has_large_data_fields = function(){
- for (const i in this.fields){
- const field = this.fields[i];
- if (field.type.handles_large_data){
- return true;
+ },
+ get_access_strategy: function(access_strategy_map, action_name){
+ return access_strategy_map[action_name] || access_strategy_map["default"];
+ },
+ has_large_data_fields: function(fields){
+ for (const i in fields){
+ const field = fields[i];
+ if (field.type.handles_large_data){
+ return true;
+ }
}
- }
- return false;
-};
-Collection.prototype.is_old_value_sensitive = function(method_name){
- for (const i in this.fields){
- if (this.fields[i].type.is_old_value_sensitive(method_name)){
- return true;
+ return false;
+ },
+ is_old_value_sensitive: function(fields, action_name){
+ for (const i in fields){
+ if (fields[i].type.is_old_value_sensitive(action_name)){
+ return true;
+ }
}
- }
- return false;
-};
-Collection.prototype.decode_values = function(context, values){
- const decoded_values = {};
- for (const key in this.fields){
- const value = values[key];
- const field = this.fields[key];
- if (field === undefined){
- continue;
+ return false;
+ },
+ decode_values: function(fields, context, values){
+ const decoded_values = {};
+ for (const key in fields){
+ const value = values[key];
+ const field = fields[key];
+ if (field === undefined){
+ continue;
+ }
+ decoded_values[key] = field.decode(context, value);
}
- decoded_values[key] = field.decode(context, value);
- }
- return Promise.props(decoded_values);
-};
-Collection.prototype._format_decoded_values = function(context, decoded_values, format){
-
- const formatted_values = clone(decoded_values);
- for (const field_name in formatted_values){
- if (format[field_name]){
- const decoded_value = decoded_values[field_name];
- const field_format = format[field_name];
- formatted_values[field_name] = this.fields[field_name].format(context, decoded_value, field_format);
+ return Promise.props(decoded_values);
+ },
+ format_decoded_values: function(fields, context, decoded_values, format){
+ const formatted_values = clone(decoded_values);
+ for (const field_name in formatted_values){
+ if (format[field_name]){
+ const decoded_value = decoded_values[field_name];
+ const field_format = format[field_name];
+ formatted_values[field_name] = fields[field_name].format(context, decoded_value, field_format);
+ }
}
- }
- return Promise.props(formatted_values);
-};
-Collection.prototype._get_body = function(context, db_document, format){
- const self = this;
- const decoded_values = this.decode_values(context, db_document.body);
- if (format){
- return decoded_values.then(function(decoded_values){
- return self._format_decoded_values(context, decoded_values, format);
+ return Promise.props(formatted_values);
+ },
+ _get_body: function(fields, context, db_document, format){
+ const decoded_values = Collection.pure.decode_values(fields, context, db_document.body);
+ if (format){
+ return decoded_values.then(function(decoded_values){
+ return Collection.pure.format_decoded_values(fields, context, decoded_values, format);
+ });
+ } else {
+ return decoded_values;
+ }
+ },
+ get_resource_representation: function(fields, field_type_name, context, db_document, format){
+ const representation = {};
+ representation.created_context = db_document.created_context;
+ representation.last_modified_context = db_document.last_modified_context;
+ representation.id = db_document.sealious_id;
+ representation.collection_name = field_type_name;
+ representation.body = Collection.pure._get_body(fields, context, db_document, format);
+ return Promise.props(representation).then(function(res){
+ return res;
});
- } else {
- return decoded_values;
- }
-};
-Collection.prototype.get_resource_representation = Collection.prototype.decode_db_entry = function(context, db_document, format){
- const representation = {};
+ },
+ check_if_action_is_allowed: function(access_strategy_map, context, action_name, resource_representation){
+ const access_strategy = Collection.pure.get_access_strategy(access_strategy_map, action_name);
- representation.created_context = db_document.created_context;
- representation.last_modified_context = db_document.last_modified_context;
- representation.id = db_document.sealious_id;
- representation.collection_name = this.name;
- representation.body = this._get_body(context, db_document, format);
-
- return Promise.props(representation).then(function(res){
- return res;
- });
+ return access_strategy.check(context, resource_representation)
+ .then(function(results){
+ return results;
+ });
+ },
};
-Collection.prototype.check_if_action_is_allowed = function(context, action_name, resource_representation){
- const access_strategy = this.get_access_strategy(action_name);
+const pure = Collection.pure;
- return access_strategy.check(context, resource_representation)
- .then(function(results){
- return results;
- });
+// not all pure methods are linked here, because they are not intended to be called from outside
+
+Collection.prototype = {
+ add_field(field_declaration){ return pure.add_field(this.app, this, this.fields, field_declaration);},
+ add_fields(field_declarations_array){ return pure.add_fields(this.app, this, this.fields, field_declarations_array);},
+ validate_field_values(context, assume_delete_value_on_missing_key, new_values, old_values){
+ return pure.validate_field_values(this.name, this.fields, context, assume_delete_value_on_missing_key, new_values, old_values);
+ },
+ encode_field_values(context, body, old_body){ return pure.encode_field_values(this.fields, context, body, old_body);},
+ get_specification(with_validators){ return pure.get_specification(this.name, this.human_readable_name, this.summary, this.fields, with_validators);},
+ set_access_strategy(strategy_declaration){ return pure.set_access_strategy(this.app, this, strategy_declaration); },
+ get_access_strategy(action_name){return pure.get_access_strategy(this.access_strategy, action_name);},
+ has_large_data_fields(){ return pure.has_large_data_fields(this.fields);},
+ is_old_value_sensitive(action_name){return pure.is_old_value_sensitive(this.fields, action_name);},
+ decoded_values(context, values){return pure.decode_values(this.fields, context, values);},
+ format_decoded_values(context, decoded_values, format){ return pure.format_decoded_values(this.fields, context, decoded_values, format);},
+ get_resource_representation(context, db_document, format){ return pure.get_resource_representation(this.fields, this.name, context, db_document, format);},
+ check_if_action_is_allowed(context, action_name, resource_representation){ return pure.check_if_action_is_allowed(this.access_strategy, context, action_name, resource_representation);},
};
+Collection.prototype.decode_db_entry = Collection.prototype.get_resource_representation;
+
module.exports = Collection;
diff --git a/lib/chip-types/datastore.js b/lib/chip-types/datastore.js
index f0949459..382d8f39 100644
--- a/lib/chip-types/datastore.js
+++ b/lib/chip-types/datastore.js
@@ -1,255 +1,240 @@
"use strict";
const locreq = require("locreq")(__dirname);
const assert = require("assert");
const Chip = require("./chip.js");
const Promise = require("bluebird");
-const ChipManager = locreq("lib/chip-types/chip-manager.js");
const Errors = locreq("lib/response/error.js");
-/*
- Represents datastore.
- @constructor
- @param {string} name - name of datastore
-*/
-const Datastore = function(name){
- this.name = name;
- this.longid = `datastore.${name}`;
- this.default_configuration = {};
- ChipManager.add_chip("datastore", this.name, this);
+const Datastore = function(app, declaration){
+ this.name = declaration.name;
+ this.longid = `${Datastore.type_name }.${ this.name}`;
};
+Datastore.type_name = "datastore";
+
Datastore.prototype = new Chip();
-/**
- * Defines functions datastore need to implement,
- * then ensures that if one of these function will not be implemented Selious will throw an informative error.
- */
const needs_to_implement = ["find", "insert", "update", "remove"];
Datastore.prototype.return_not_implemented = function(fn_name){
return function(){
throw new Errors.DeveloperError("Function ", fn_name, "not implemented in ", this.longid, ", aborting.");
};
};
-for (const i in needs_to_implement){
- const fn_name = needs_to_implement[i];
- Datastore.prototype[fn_name] = Datastore.prototype.return_not_implemented(fn_name);
-}
-
/*
Tests datastore compatibility with Sealious. It is a cascade of Promises, which result will be logged in console.
*/
Datastore.prototype.test_compatibility = function(){
const self = this;
this.start();
const rand = Math.random();
const test_collection_name = "_test";
return Promise.resolve()
.then(function(){
// .insert method should respond with the created document
const 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
const 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,
}),
];
const 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
const 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
const 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(){
self.clear_collection(test_collection_name);
}).catch(function(){
self.clear_collection(test_collection_name);
return Promise.reject("Compatibility test unsuccesfull");
});
};
module.exports = Datastore;
diff --git a/lib/chip-types/field-structures/single.js b/lib/chip-types/field-structures/single.js
deleted file mode 100644
index 29769410..00000000
--- a/lib/chip-types/field-structures/single.js
+++ /dev/null
@@ -1,14 +0,0 @@
-"use strict";
-const Single = {
- encode: function(context, field, value_in_code){
- return field.encode(context, field.params, value_in_code);
- },
- decode: function(context, field, value_in_datastore){
- return field.decode(context, field.params, value_in_datastore);
- },
- is_proper_value: function(context, field, new_value, old_value){
- return field.is_proper_value(context, field.params, new_value, old_value);
- }
-};
-
-module.exports = Single;
diff --git a/lib/chip-types/field-type.js b/lib/chip-types/field-type.js
index 7bf3a59e..82d6eb14 100644
--- a/lib/chip-types/field-type.js
+++ b/lib/chip-types/field-type.js
@@ -1,50 +1,46 @@
"use strict";
const locreq = require("locreq")(__dirname);
const Promise = require("bluebird");
-const ChipManager = locreq("lib/chip-types/chip-manager.js");
const Errors = locreq("lib/response/error.js");
const default_methods = require("./field-type-default-methods.js");
function wrap_method_in_promise (context, declaration, method_name){
return function(){
return Promise.resolve(declaration[method_name].apply(context, arguments));
};
}
-const FieldType = function(declaration){
- const ChipManager = locreq("lib/chip-types/chip-manager.js"); // for some reason it doesn't work when placed at the beginning
+const FieldType = function(app, declaration){
let self;
if (declaration instanceof FieldType){
return declaration;
} else if (typeof declaration === "string"){
- return ChipManager.get_chip("field_type", declaration);
+ return app.ChipManager.get_chip("field_type", declaration);
} else if (declaration.extends){
- const parent_field_type = ChipManager.get_chip("field_type", declaration.extends);
+ const parent_field_type = app.ChipManager.get_chip("field_type", declaration.extends);
self = Object.create(parent_field_type);
} else {
self = this;
for (const method_name in default_methods){
self[method_name] = default_methods[method_name];
}
}
- if (declaration.name){
- ChipManager.add_chip("field_type", declaration.name, self);
- }
-
for (const prop_name in declaration){
if (default_methods[prop_name] !== undefined && typeof self[prop_name] === "function"){
self[prop_name] = wrap_method_in_promise(self, declaration, prop_name);
} else {
self[prop_name] = declaration[prop_name];
}
}
return self;
};
+FieldType.type_name = "field_type";
+
module.exports = FieldType;
diff --git a/lib/chip-types/field.js b/lib/chip-types/field.js
index 6ea02af3..f84fb556 100644
--- a/lib/chip-types/field.js
+++ b/lib/chip-types/field.js
@@ -1,28 +1,28 @@
"use strict";
const locreq = require("locreq")(__dirname);
const default_methods = require("./field-type-default-methods.js");
const FieldType = locreq("lib/chip-types/field-type.js");
-function Field (declaration){
+function Field (app, declaration){
this.name = declaration.name;
this.declaration = declaration;
- this.type = new FieldType(declaration.type);
+ this.type = new FieldType(app, declaration.type);
this.required = declaration.required || false;
this.params = declaration.params || {};
const self = this;
for (const method_name in default_methods){
this[method_name] = (function(method_name){
return function(){
const arguments_array = Object.keys(arguments).map((key)=>arguments[key]);
arguments_array.splice(1, 0, self.params);
return self.type[method_name].apply(self.type, arguments_array);
};
})(method_name);
}
}
module.exports = Field;
diff --git a/lib/config/config-manager.js b/lib/config/config-manager.js
deleted file mode 100644
index f4421f4d..00000000
--- a/lib/config/config-manager.js
+++ /dev/null
@@ -1,60 +0,0 @@
-"use strict";
-const merge = require("merge");
-
-let default_config = {};
-let config = {};
-
-function modify_config (is_default_config, key, value){
- const key_elements = key.split(".");
- const new_values = {};
- let current_position = new_values;
- for (let i = 0; i < key_elements.length - 1; i++){
- const 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){
- default_config = merge.recursive(true, default_config, new_values);
- } else {
- config = merge.recursive(true, config, new_values);
- }
-}
-
-const ConfigManager = {
- set_config: function(key, new_config){
- if (arguments.length === 1){
- // config = config;
- } else {
- modify_config(false, key, new_config);
- }
- },
- set_default_config: function(key, value){
- if (arguments.length === 1){
- // default_config = default_config;
- } else {
- modify_config(true, key, value);
- }
- },
- get_configuration: function(key){
- let to_merge_left = default_config;
- let to_merge_right = config;
- const key_elements = key === undefined ? [] : key.split(".");
- while (key_elements.length){
- const 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.recursive(true, to_merge_left, to_merge_right);
- },
- get_chip_config: function(longid){
- return config.chip_config && config.chip_config[longid];
- },
- get_dispatcher_config: function(){
- return config.dispatcher_config || {};
- }
-};
-
-ConfigManager.get_config = ConfigManager.get_configuration;
-
-module.exports = ConfigManager;
diff --git a/lib/context.js b/lib/context.js
index 50df556a..ac4db8da 100644
--- a/lib/context.js
+++ b/lib/context.js
@@ -1,76 +1,70 @@
"use strict";
const locreq = require("locreq")(__dirname);
const promisify = require("bluebird-events");
const EventEmitter = require("events");
function Context (timestamp, ip, user_id, session_id){
Object.defineProperty(this, "_cached_user_data", {
value: false,
writable: true,
});
Object.defineProperty(this, "loading_user_data", {
value: false,
writable: true,
});
Object.defineProperty(this, "e", {
value: new EventEmitter(),
});
this.e.setMaxListeners(20);
Object.defineProperty(this, "session_id", {
value: session_id,
}); // to make it non-enumerable and non-writeable
if (user_id === undefined || user_id === false){
user_id = null;
}
if (timestamp === undefined){
const d = new Date();
timestamp = d.getTime();
}
this.timestamp = timestamp;
this.ip = ip || null;
this.user_id = user_id;
}
-Context.prototype.get_user_data = function(){
+Context.prototype.get_user_data = function(app){
const self = this;
if (this.user_id === null){
return Promise.resolve(null);
} else if (self.loading_user_data){
return promisify(self.e, {
resolve: "loaded_user_data",
reject: "error"
});
} else if (self._cached_user_data === false){
- const run_action = locreq("lib/utils/run-action.js");
const SuperContext = locreq("lib/super-context.js");
self.loading_user_data = true;
const c = new SuperContext(self);
- return run_action(c, ["resources", "user", this.user_id], "show")
+ return app.run_action(c, ["collections", "users", this.user_id], "show")
.then(function(user_data){
self._cached_user_data = user_data;
self.loading_user_data = false;
self.e.emit("loaded_user_data", user_data);
return user_data;
}).catch(function(error){
self.e.emit("error");
throw error;
});
} else {
return Promise.resolve(self._cached_user_data);
}
};
-Context.prototype.run_action = function(subject_path, action_name, params){
- const run_action = locreq("lib/utils/run-action.js");
- return run_action(this, subject_path, action_name, params);
-};
-
module.exports = Context;
diff --git a/lib/core-services/file-manager.js b/lib/core-services/file-manager.js
deleted file mode 100644
index 27ddd35c..00000000
--- a/lib/core-services/file-manager.js
+++ /dev/null
@@ -1,107 +0,0 @@
-"use strict";
-const locreq = require("locreq")(__dirname);
-const Promise = require("bluebird");
-const UUIDGenerator = require("shortid");
-const path = require("path");
-const fse = require("fs-extra");
-const fs = require("fs");
-const get_main_app_dir = locreq("lib/utils/get-main-app-dir.js");
-
-const Logger = locreq("lib/logger/logger.js");
-const File = locreq("lib/data-structures/file.js");
-const ChipManager = locreq("lib/chip-types/chip-manager.js");
-
-/**
- * Manages files
- * @class
- */
-
-const root_path = function(){
- let parent_tmp = module.parent;
- let parent = null;
- while (parent_tmp){
- parent = parent_tmp;
- parent_tmp = parent_tmp.parent;
- }
-
- return parent.filename;
-};
-
-const FileManager = function(upload_path){
- if (upload_path === undefined){
- upload_path = "./uploaded_files/";
- }
- this.upload_path = path.resolve(get_main_app_dir(), "./" + upload_path);
-};
-
-FileManager.prototype.name = "files";
-FileManager.prototype.save_file = function(file){
- // should be passed as an argument
- const Datastore = ChipManager.get_datastore_chip();
-
- if (!fs.existsSync(this.upload_path)){
- fs.mkdirSync(this.upload_path);
- }
-
- const newID = UUIDGenerator();
-
- const upload_path_with_sealious_name = this.upload_path + "/" + newID;
- return Promise.promisify(fs.writeFile)(upload_path_with_sealious_name, file.data)
- .then(function(){
-
- const file_database_entry = {
- original_name: file.filename,
- creation_context: file.context,
- id: newID,
- mime_type: file.mime,
- };
-
- return Datastore.insert("files", file_database_entry, {});
- })
- .then(function(){
- return {
- id: newID,
- filename: file.filename
- };
- });
-
-};
-FileManager.prototype.diff = function(dispatcher, file){
-
-};
-FileManager.prototype.get_list = function(dispatcher, owner){
- const query = {
- "body.owner": owner
- };
- Logger.info("List for owner '" + owner + "' has been created");
- return this.find(dispatcher, query);
-};
-FileManager.prototype.find = function(context, query){
- const Datastore = ChipManager.get_datastore_chip();
- const self = this;
- return Datastore.find("files", query)
- .then(function(documents){
- const parsed_documents = documents.map(function(document){
- const ret = File.from_db_entry(document);
- ret.path_on_hdd = path.resolve(self.upload_path, "./" + ret.id);
- return ret;
- });
- return Promise.resolve(parsed_documents);
- });
-};
-FileManager.prototype.change_name = function(dispatcher, sealious_name, new_name){
- const Datastore = ChipManager.get_datastore_chip();
- return Datastore.update("files", {
- sealious_id: sealious_name
- }, {
- $set: {
- "body.original_name": new_name
- }
- });
-};
-FileManager.prototype.delete = function(dispatcher, query){
-
-};
-// wersjonowanie, historia dostępu, przetrzymywanie poprzednich wersji
-
-module.exports = new FileManager();
diff --git a/lib/core.js b/lib/core.js
deleted file mode 100644
index f25ad240..00000000
--- a/lib/core.js
+++ /dev/null
@@ -1,55 +0,0 @@
-"use strict";
-const Sealious = require("./main.js");
-const http = require("http");
-
-const ConfigManager = require("./config/config-manager.js");
-
-const SealiousCore = new function(){
-
- this.check_version = function(package_info){
- const pkg = require("../package.json");
- const pkg_split = pkg.version.split(".");
- const version = pkg_split[0] + "." + pkg_split[1];
- const url = "http://registry.npmjs.org/sealious/" + version;
-
- const check_request = http.get(url, function(res){
- res.setEncoding("utf8");
- let body = "";
- res.on("data", function(chunk){
- body += chunk.toString();
- });
- let sealious_npm;
- res.on("end", function(){
- try {
- sealious_npm = JSON.parse(body);
- } catch (error){
- Sealious.Logger.error(new Sealious.Errors.Error("Could not fetch update information from NPM registry."));
- }
- if (sealious_npm.error){
- Sealious.Logger.warning("npm registry error when requesting info for version " + version + ": " + sealious_npm.error);
- } else if (!sealious_npm.version || sealious_npm === undefined){
- Sealious.Logger.warning("unknown npm registry error when requesting info for version " + version + ".");
- } else {
- const 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.config = function(config_object){
- ConfigManager.set_config(config_object);
- };
-
-};
-
-module.exports = SealiousCore;
diff --git a/lib/data-structures/file.js b/lib/data-structures/file.js
index 9b5485c5..7439d4a8 100644
--- a/lib/data-structures/file.js
+++ b/lib/data-structures/file.js
@@ -1,35 +1,25 @@
"use strict";
const locreq = require("locreq")(__dirname);
const mime = require("mime-types");
-const FileManager = locreq("lib/core-services/file-manager.js");
const Promise = require("bluebird");
function File (creation_context, filename, data, id, file_mime){
this.filename = filename;
this.data = data;
this.id = id || null;
this.mime = file_mime || mime.lookup(filename);
}
-File.from_id = function(context, file_id){
- return FileManager.find(context, {
- id: file_id,
- })
- .then(function(file_array){
- return Promise.resolve(file_array[0]);
- });
-};
-
File.from_db_entry = function(db_document){
return new File(db_document.creation_context, db_document.original_name, db_document.data, db_document.id, db_document.mime_type);
};
File.prototype.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
deleted file mode 100644
index a3ff3bd3..00000000
--- a/lib/logger/logger.js
+++ /dev/null
@@ -1,148 +0,0 @@
-"use strict";
-const locreq = require("locreq")(__dirname);
-const winston = require("winston");
-const ConfigManager = locreq("lib/config/config-manager.js");
-
-/*
- 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",
- });
-
-
-/*
- 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
-
-*/
-const 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){
- const date = new Date();
-
- let hour = date.getHours();
- hour = (hour < 10 ? "0" : "") + hour;
-
- let min = date.getMinutes();
- min = (min < 10 ? "0" : "") + min;
-
- let sec = date.getSeconds();
- sec = (sec < 10 ? "0" : "") + sec;
-
- let milli = date.getMilliseconds();
- milli = (milli < 10 ? "00" : "") + milli;
- milli = (milli < 100 && milli >= 10 ? "0" : "") + milli;
-
- const year = date.getFullYear();
-
- let month = date.getMonth() + 1;
- month = (month < 10 ? "0" : "") + month;
-
- let 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;
- }
-}
-
-const transports_array = [];
-
-const logger_level = ConfigManager.get_config().logger_config.logger_level;
-const logger_color = ConfigManager.get_config().logger_config.logger_color;
-const logger_file = ConfigManager.get_config().logger_config.logger_file;
-const logger_dirname = ConfigManager.get_config().logger_config.logger_dirname;
-const logger_to_json = ConfigManager.get_config().logger_config.logger_to_json;
-const logger_rotation = ConfigManager.get_config().logger_config.logger_rotation;
-
-
-const 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){
- const 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,
- });
- const 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);
-}
-
-
-const logger = new winston.Logger({
- levels: custom.levels,
- colors: custom.colors,
- transports: transports_array,
-});
-
-logger.rewriters.push(function(level, msg, meta){
- if (Object.keys(meta).length){
- let message = "\n";
- for (const prop in meta){
- message += " - " + prop + ": " + JSON.stringify(meta[prop]) + "\n";
- }
- meta = message;
- }
-
- return meta;
-});
-
-module.exports = logger;
diff --git a/lib/main.js b/lib/main.js
index 405152ce..d149382a 100644
--- a/lib/main.js
+++ b/lib/main.js
@@ -1,62 +1,34 @@
"use strict";
+const locreq = require("locreq")(__dirname);
const Sealious = {};
-module.exports = Sealious;
-const Core = require("./core.js");
+module.exports = Sealious;
Sealious.Errors = require("./response/error.js");
Sealious.Error = Sealious.Errors.Error;
Sealious.Responses = require("./response/responses.js");
Sealious.Response = require("./response/response.js");
Sealious.SubjectPath = require("./data-structures/subject-path.js");
Sealious.Subject = require("./subject/subject.js");
-Sealious.Action = require("./action.js");
-Sealious.run_action = require("./utils/run-action.js");
-Sealious.File = require("./data-structures/file.js");
Sealious.VirtualFile = require("./data-structures/virtual-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.Context = require("./context.js");
Sealious.SuperContext = require("./super-context.js");
-Sealious.FieldStructures = require("./chip-types/field-structures.js");
-Sealious.RootSubject = require("./subject/predefined-subjects/root-subject.js");
-
-Sealious.FileManager = require("./core-services/file-manager.js");
+Sealious.File = require("./data-structures/file.js");
Sealious.ChipTypes = {
"AccessStrategyType": require("./chip-types/access-strategy-type.js"),
"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"),
"Collection": require("./chip-types/collection.js")
};
// prefix Sealious.ChipTypes[chip_type_name] to Sealious[chip_type_name]
-for (let chip_type_name in Sealious.ChipTypes){
- if (chip_type_name === "Datastore"){
- chip_type_name += "Creator";
- }
+for (const chip_type_name in Sealious.ChipTypes){
Sealious[chip_type_name] = Sealious.ChipTypes[chip_type_name];
}
-Sealious.Datastore = null; // this variable will hold the default datastore.
-
-Sealious.init = function(){
- require("./base-chips/_base-chips.js");
- Sealious.Logger = require("./logger/logger.js");
- Sealious.PluginManager.load_plugins();
- Sealious.Datastore = Sealious.ChipManager.get_datastore_chip();
-};
-
-Sealious.start = function(){
- Core.check_version();
- return Sealious.ChipManager.start_chips()
- .then(() => Sealious);
-};
-
-module.exports = Sealious;
+Sealious.App = locreq("lib/app/app.js");
diff --git a/lib/plugins/plugin-manager.js b/lib/plugins/plugin-manager.js
deleted file mode 100644
index 75adb329..00000000
--- a/lib/plugins/plugin-manager.js
+++ /dev/null
@@ -1,79 +0,0 @@
-"use strict";
-const locreq = require("locreq")(__dirname);
-const path = require("path");
-const fs = require("fs");
-const resolve = require("resolve");
-
-const Logger = locreq("lib/logger/logger.js");
-
-function custom_resolve (plugin_name, root){
- try {
- return resolve.sync(plugin_name, {basedir: root});
- } catch (error){
- return require.resolve(plugin_name);
- }
-}
-
-function get_package_info_path (dir, package_name){
- let package_path = custom_resolve(package_name, dir);
- let package_info_path = null;
- while (package_info_path === null){
- const temp_path = path.resolve(package_path, "../package.json");
- try {
- fs.accessSync(temp_path, fs.F_OK);
- package_info_path = temp_path;
- } catch (e){
- package_path = path.resolve(package_path, "../");
- }
- }
- return package_info_path;
-}
-
-function get_package_info (dir, package_name){
- return require(get_package_info_path(dir, package_name));
-}
-
-function is_sealious_plugin (dir, module_name){
- const plugin_package_info = get_package_info(dir, module_name);
- return plugin_package_info.keywords && plugin_package_info.keywords.indexOf("sealious-plugin") !== -1;
-}
-
-function load_plugins_from_dir (dir){
- const root = path.resolve(dir);
- const pkgfile = require("locreq")(dir).resolve("package.json");
- const pkg = require(pkgfile);
-
- const dependencies = pkg.dependencies || {};
- const required_sealious_plugins = Object.keys(dependencies).filter(is_sealious_plugin.bind({}, root));
-
-
- if (required_sealious_plugins.length){
- Logger.debug(`${pkg.name} (${pkgfile}) requires: ${required_sealious_plugins.join(", ")}`);
- for (const i in required_sealious_plugins){
- const plugin_name = required_sealious_plugins[i];
- const plugin_info_path = get_package_info_path(root, plugin_name);
- const plugin_dir = path.resolve(plugin_info_path, "../");
- load_plugins_from_dir(plugin_dir);
- if(PluginManager.loaded_plugins.indexOf(plugin_name) === -1){
- require(custom_resolve(plugin_name, plugin_dir));
- PluginManager.loaded_plugins.push(plugin_name);
- Logger.info(`\t\u2713 ${plugin_name} (${plugin_dir})`);
- }else{
- Logger.info(`\ ${plugin_name} (already loaded)`);
- }
- }
- }
-}
-const PluginManager = {
- loaded_plugins: [],
- load_plugins: function(){
- Logger.info("Loading plugins...");
- const sealious_dir = path.resolve(module.filename, "../../../");
- if (sealious_dir !== path.resolve("")){
- load_plugins_from_dir(sealious_dir);
- }
- load_plugins_from_dir("");
- }
-};
-
-module.exports = PluginManager;
diff --git a/lib/response/error.js b/lib/response/error.js
index fc206338..56ef552a 100644
--- a/lib/response/error.js
+++ b/lib/response/error.js
@@ -1,81 +1,86 @@
"use strict";
const Response = require("./response.js");
const SealiousErrors = {};
-SealiousErrors.Error = function(message, params, data){
+SealiousErrors.Error = function(content, params, data){
params = params || {};
- this.message = message;
- this.sealious_error = true;
this.is_user_fault = params.is_user_fault === undefined ? false : params.is_user_fault;
- this.is_developer_fault = params.is_developer_fault === undefined ? false : params.is_developer_fault;
this.type = params.type === undefined ? "error" : params.type;
this.data = data || params.data || {};
+ this.message = {
+ content: content,
+ is_user_fault: this.is_user_fault,
+ type: this.type,
+ data: this.data,
+ };
+ this.sealious_error = true;
+ this.is_developer_fault = params.is_developer_fault === undefined ? false : params.is_developer_fault;
Error.captureStackTrace(this, SealiousErrors.Error);
};
SealiousErrors.Error.prototype = Object.create(Error.prototype);
SealiousErrors.Error.prototype.constructor = SealiousErrors.Error;
SealiousErrors.Error.prototype.to_object = function(){
return {
message: this.message,
type: this.type,
data: this.data,
};
};
const error_types = {
ValidationError: {
is_user_fault: true,
type: "validation",
},
ValueExists: {
is_user_fault: true,
type: "value_exists",
},
InvalidCredentials: {
is_user_fault: true,
type: "invalid_credentials",
},
NotFound: {
is_user_fault: true,
type: "not_found"
},
DeveloperError: {
is_user_fault: false,
is_developer_fault: true,
type: "dev_error",
},
BadContext: {
is_user_fault: true,
type: "permission",
},
ServerError: {
is_user_fault: false,
is_developer_fault: false,
type: "server_error",
},
BadSubjectPath: {
is_user_fault: true,
type: "bad_subject",
},
BadSubjectAction: {
is_user_fault: true,
type: "bad_subject_action",
},
};
for (const full_name in error_types){
const params = error_types[full_name];
SealiousErrors[full_name] = (function(params){
return function(message, data){
SealiousErrors.Error.call(this, message, params, data);
};
})(params);
SealiousErrors[full_name].prototype = Object.create(SealiousErrors.Error.prototype);
SealiousErrors[full_name].prototype.constructor = SealiousErrors[full_name];
}
module.exports = SealiousErrors;
diff --git a/lib/response/responses.js b/lib/response/responses.js
index 76fc69fb..27a8eedb 100644
--- a/lib/response/responses.js
+++ b/lib/response/responses.js
@@ -1,13 +1,18 @@
"use strict";
-"use strict";
const SealiousResponses = {};
SealiousResponses.NewSession = function(session_id){
this.status = "success";
this.message = "Logged in!";
Object.defineProperty(this, "metadata", {value: {session_id: session_id}});
this.data = {};
};
+SealiousResponses.ResourceCreated = function(resource_representation){
+ for(const i in resource_representation){
+ this[i] = resource_representation[i];
+ }
+};
+
module.exports = SealiousResponses;
diff --git a/lib/subject/predefined-subjects/collections-subject.js b/lib/subject/predefined-subjects/collections-subject.js
index 47b9b783..48fce025 100644
--- a/lib/subject/predefined-subjects/collections-subject.js
+++ b/lib/subject/predefined-subjects/collections-subject.js
@@ -1,41 +1,41 @@
"use strict";
const locreq = require("locreq")(__dirname);
const Promise = require("bluebird");
const Errors = locreq("lib/response/error.js");
-const ChipManager = locreq("lib/chip-types/chip-manager.js");
const Subject = locreq("lib/subject/subject.js");
const CollectionSubject = locreq("lib/subject/subject-types/collection-subject.js");
-const CollectionsSubject = function(){
+const CollectionsSubject = function(app){
this.resource_collections = null;
this._initialize_resource_collections = function(){
this.resource_collections = {};
- const collections = ChipManager.get_chips_by_type("collection");
+ const collections = app.ChipManager.get_chips_by_type("collection");
for (const collection_name in collections){
const collection = collections[collection_name];
- this.resource_collections[collection_name] = new CollectionSubject(collection);
+ this.resource_collections[collection_name] = new CollectionSubject(app, collection);
}
};
this.get_child_subject = function(key){
if (this.resource_collections === null || this.resource_collections[key] === undefined){
this._initialize_resource_collections();
}
if (this.resource_collections[key] === undefined){
- throw new Errors.BadSubjectPath(`Unknown resource type: '${key}'.`);
+ throw new Errors.BadSubjectPath(`Unknown collection: '${key}'.`);
}
return Promise.resolve(this.resource_collections[key]);
};
this.perform_action = function(context, action_name, args){
throw new Errors.BadSubjecAction("This subject does not provide any actions.");
};
};
CollectionsSubject.prototype = Object.create(Subject.prototype);
+CollectionsSubject.subject_name = "collections";
-module.exports = new CollectionsSubject();
+module.exports = CollectionsSubject;
diff --git a/lib/subject/predefined-subjects/me-subject.js b/lib/subject/predefined-subjects/me-subject.js
index a82059b2..38a157b8 100644
--- a/lib/subject/predefined-subjects/me-subject.js
+++ b/lib/subject/predefined-subjects/me-subject.js
@@ -1,17 +1,17 @@
"use strict";
const locreq = require("locreq")(__dirname);
const Subject = locreq("lib/subject/subject.js");
const Errors = locreq("lib/response/error.js");
-const MeSubject = function(){
+const MeSubject = function(app){
this.perform_action = function(context, action_name, params){
- return context.run_action(["resources", "user", context.user_id], action_name, params)
+ return app.run_action(context, ["collections", "users", context.user_id], action_name, params)
.catch({type: "not_found"}, function(error){
throw new Errors.InvalidCredentials("You're not logged in!");
});
};
};
MeSubject.prototype = Object.create(Subject.prototype);
-module.exports = new MeSubject();
+module.exports = MeSubject;
diff --git a/lib/subject/predefined-subjects/root-subject.js b/lib/subject/predefined-subjects/root-subject.js
index 693f0618..a9f2841f 100644
--- a/lib/subject/predefined-subjects/root-subject.js
+++ b/lib/subject/predefined-subjects/root-subject.js
@@ -1,34 +1,35 @@
"use strict";
const locreq = require("locreq")(__dirname);
const Errors = locreq("lib/response/error.js");
const Subject = locreq("lib/subject/subject.js");
-const ResourcesSubject = require("./collections-subject.js");
-const UsersSubject = require("./users-subject.js");
-const SessionsSubject = require("./sessions-subject.js");
-const UploadedFilesSubject = require("./uploaded-files.js");
+const CollectionsSubjectFn = require("./collections-subject.js");
+const SessionsSubjectFn = require("./sessions-subject.js");
+const UsersSubjectFn = require("./users-subject.js");
+const UploadedFilesSubjectFn = require("./uploaded-files.js");
-const RootSubject = function(){
+const child_subjects_generators = [CollectionsSubjectFn, SessionsSubjectFn, UsersSubjectFn, UploadedFilesSubjectFn];
- this.name = "Root";
+const RootSubject = function(app){
+
+ const child_subjects = {};
+
+ child_subjects_generators.forEach((subjectFn) => {
+ child_subjects[subjectFn.subject_name] = new subjectFn(app);
+ });
this.get_child_subject = function(key){
- switch (key){
- case "collections":
- return ResourcesSubject;
- case "users":
- return UsersSubject;
- case "sessions":
- return SessionsSubject;
- case "uploaded-files":
- return UploadedFilesSubject;
- default:
+ const ret = child_subjects[key];
+ if(ret === undefined){
throw new Errors.BadSubjectPath(`No child subject with key '${key}' in RootSubject`);
+ } else {
+ return ret;
}
};
};
RootSubject.prototype = Object.create(Subject.prototype);
+RootSubject.prototype.name = "Root";
-module.exports = new RootSubject();
+module.exports = RootSubject;
diff --git a/lib/subject/predefined-subjects/sessions-subject.js b/lib/subject/predefined-subjects/sessions-subject.js
index 0fba4cf2..3dfe0b60 100644
--- a/lib/subject/predefined-subjects/sessions-subject.js
+++ b/lib/subject/predefined-subjects/sessions-subject.js
@@ -1,113 +1,101 @@
"use strict";
const locreq = require("locreq")(__dirname);
const Promise = require("bluebird");
-const uuid = require("node-uuid");
const CurrentSessionSubject = require("../subject-types/current-session-subject.js");
const SuperContext = locreq("lib/super-context.js");
const Errors = locreq("lib/response/error.js");
const Responses = locreq("lib/response/responses.js");
const Subject = locreq("lib/subject/subject.js");
-const sessions = {};
-
-function is_auth_data_valid (username, password){
- return new SuperContext()
- .run_action(
- ["resources", "user"],
+function is_auth_data_valid (app, username, password){
+ return app.run_action(
+ new SuperContext(),
+ ["collections", "users"],
"show",
{filter:{username: username, password: password}}
).then(function(results){
if (results.length === 1){
return results[0];
} else {
throw new Errors.InvalidCredentials("User/password mismatch");
}
});
}
function user_exists (username){
return new SuperContext()
.run_action(
["users", username],
"show"
);
}
-function new_session (user_id){
- const session_id = uuid.v4();
- sessions[session_id] = user_id;
- return session_id;
-}
-
-function attemp_login (context, params){
+function attemp_login (app, context, params){
let username, password;
+ let user;
+ let session;
return Promise.try(function(){
username = params.username;
password = params.password;
if (!username){
throw new Errors.InvalidCredentials("Missing username!");
}
if (!password){
throw new Errors.InvalidCredentials("Missing password!");
}
})
.then(function(){
- return is_auth_data_valid(username, password)
+ return is_auth_data_valid(app, username, password)
.catch({type: "not_found"}, function(e){
return user_exists(username)
.then(function(){
throw new Errors.InvalidCredentials("Bad password");
})
.catch(Errors.Error, function(e){
throw new Errors.InvalidCredentials("Bad username");
});
});
})
- .then(function(user){
- const session_id = new_session(user.id);
- return new SuperContext().run_action(["resources", "user", user.id], "edit", {last_login_context: context})
- .then(function(){
- return new Responses.NewSession(session_id);
- });
+ .then(function(user_arg){
+ user = user_arg;
+ return app.run_action(new SuperContext(), ["collections", "sessions"], "create", {user: user.id, "session-id": null});
+ })
+ .then(function(session_arg){
+ session = session_arg;
+ return app.run_action(new SuperContext(), ["collections", "users", user.id], "edit", {last_login_context: context});
+ })
+ .then(function(){
+ return new Responses.NewSession(session.body["session-id"]);
});
}
-function get_user_id (context, session_id){
- if (context.is_super){
- return sessions[session_id];
- } else {
- throw new Errors.BadContext("You are not allowed to view session data");
- }
-}
-
-const SessionsSubject = function(){
+const SessionsSubject = function(app){
this.perform_action = function(context, action_name, params){
params = params || {};
switch (action_name){
case "create":
- return attemp_login(context, params);
- case "get_user_id":
- const session_id = params;
- return get_user_id(context, session_id);
+ return attemp_login(app, context, params);
default:
throw new Errors.DeveloperError(`Unknown/unsupported action '${action_name}' for Session Subject.`);
}
};
this.get_child_subject = function(key){
switch (key){
case "current":
- return new CurrentSessionSubject(sessions);
+ return new CurrentSessionSubject();
default:
throw new Errors.BadSubjectPath(`No child subject with key '${key}' in SessionSubject`);
}
};
};
SessionsSubject.prototype = Object.create(Subject.prototype);
-module.exports = new SessionsSubject();
+SessionsSubject.subject_name = "sessions";
+
+module.exports = SessionsSubject;
diff --git a/lib/subject/predefined-subjects/uploaded-files.js b/lib/subject/predefined-subjects/uploaded-files.js
index e71cbb48..6380cdd7 100644
--- a/lib/subject/predefined-subjects/uploaded-files.js
+++ b/lib/subject/predefined-subjects/uploaded-files.js
@@ -1,24 +1,26 @@
"use strict";
const locreq = require("locreq")(__dirname);
const Promise = require("bluebird");
const Subject = locreq("lib/subject/subject.js");
const Errors = locreq("lib/response/error.js");
const SingleFileSubject = locreq("lib/subject/subject-types/single-file-subject.js");
-const UploadedFilesSubject = function(){
+function UploadedFilesSubject(app){
this.get_child_subject = function(key){
const file_id = key;
- return Promise.resolve(new SingleFileSubject(file_id));
+ return Promise.resolve(new SingleFileSubject(app, file_id));
};
this.perform_action = function(context, action_name, args){
throw new Errors.BadSubjecAction("This subject does not provide any actions.");
};
-};
+}
UploadedFilesSubject.prototype = Object.create(Subject.prototype);
-module.exports = new UploadedFilesSubject();
+UploadedFilesSubject.subject_name = "uploaded-files";
+
+module.exports = UploadedFilesSubject;
diff --git a/lib/subject/predefined-subjects/users-subject.js b/lib/subject/predefined-subjects/users-subject.js
index 973b6d2f..2116598d 100644
--- a/lib/subject/predefined-subjects/users-subject.js
+++ b/lib/subject/predefined-subjects/users-subject.js
@@ -1,46 +1,48 @@
"use strict";
const locreq = require("locreq")(__dirname);
const Promise = require("bluebird");
const Subject = locreq("lib/subject/subject.js");
const Errors = locreq("lib/response/error.js");
const me_synonyms = require("../../misc/me-synonyms.json");
const MeSubject = require("./me-subject.js");
const RootSubject = locreq("lib/subject/predefined-subjects/root-subject.js");
const SuperContext = locreq("lib/super-context.js");
-const UsersSubject = function(){
+const UsersSubject = function(app){
this.perform_action = function(context, action_name, params){
params = params || {};
switch (action_name){
case "create":
- return context.run_action(["resources", "user"], "create", params);
+ return app.run_action(context, ["collections", "users"], "create", params);
case "show":
- return context.run_action(["resources", "user"], "show", params);
+ return app.run_action(context, ["collections", "users"], "show", params);
default:
return Promise.reject(new Errors.BadSubjectAction(`Unknown action for UsersSubject: '${action_name}'`));
}
};
this.get_child_subject = function(key){
if (me_synonyms.indexOf(key) !== -1){
- return MeSubject;
+ return new MeSubject(app);
} else {
const username = key;
- return new SuperContext().run_action(["resources", "user"], "show", {filter:{username:username}})
+ return app.run_action(new SuperContext(), ["collections", "users"], "show", {filter:{username:username}})
.then(function(result){
if (result.length === 0){
throw new Errors.BadSubjectPath(`Unknown username: '${username}'`);
} else {
const user = result[0];
- return RootSubject.get_subject(["resources", "user", user.id]);
+ return RootSubject.get_subject(["collections", "users", user.id]);
}
});
}
};
};
UsersSubject.prototype = Object.create(Subject.prototype);
-module.exports = new UsersSubject();
+UsersSubject.subject_name = "users";
+
+module.exports = UsersSubject;
diff --git a/lib/subject/subject-types/collection-subject.js b/lib/subject/subject-types/collection-subject.js
index 7f078d4f..1ff72aff 100644
--- a/lib/subject/subject-types/collection-subject.js
+++ b/lib/subject/subject-types/collection-subject.js
@@ -1,189 +1,198 @@
"use strict";
const locreq = require("locreq")(__dirname);
const Promise = require("bluebird");
const UUIDGenerator = require("shortid");
const merge = require("merge");
const clone = require("clone");
const expandHash = require("expand-hash");
+const Sealious = locreq("lib/main.js");
const SingleResource = require("./single-resource-subject.js");
-const ChipManager = locreq("lib/chip-types/chip-manager.js");
const Subject = locreq("lib/subject/subject.js");
const Errors = locreq("lib/response/error.js");
-const CollectionSubject = function(collection){
+function CollectionSubject(app, collection){
this.collection = collection;
this.name = "Collection";
-};
+
+
+ // these methods are here so they can havve access to 'app' variable
+
+ this.create_resource = function(context, body){
+ const self = this;
+ return CollectionSubject.prototype.__create_resource(app.ChipManager.get_datastore_chip(), self.collection, context, body);
+ };
+
+ this.list_resources = function(context, params){
+ const datastore = app.ChipManager.get_datastore_chip();
+ const self = this;
+ return CollectionSubject.prototype.__list_resources(datastore, self.collection, context, params);
+ };
+
+ this.get_child_subject = function(key){
+ const resource_id = key;
+ const single_resource_subject = new SingleResource(app, this.collection, resource_id);
+ return Promise.resolve(single_resource_subject);
+ };
+
+}
CollectionSubject.prototype = Object.create(Subject.prototype);
CollectionSubject.prototype.__create_resource = function(datastore, collection, context, body){
return collection.check_if_action_is_allowed(context, "create")
.then(function(){
return collection.validate_field_values(context, true, body);
}).then(function(){
return collection.encode_field_values(context, body);
}).then(function(encoded_body){
const newID = UUIDGenerator(10);
const resource_data = {
sealious_id: newID,
collection: collection.name,
body: encoded_body,
created_context: context,
last_modified_context: context,
};
return datastore.insert(collection.name, resource_data, {});
}).then(function(database_entry){
return collection.get_resource_representation(context, database_entry);
+ })
+ .then(function(representation){
+ return new Sealious.Responses.ResourceCreated(representation);
});
};
-CollectionSubject.prototype.create_resource = function(context, body){
- const self = this;
- return CollectionSubject.prototype.__create_resource(ChipManager.get_datastore_chip(), self.collection, context, body);
-};
-
CollectionSubject.prototype.__preprocess_resource_filter = function(collection, context, filter){
filter = clone(filter) || {};
const expanded_filter = expandHash(filter);
const processed_filter = {};
for (const field_name in expanded_filter){
if (collection.fields[field_name]){
const field = collection.fields[field_name];
const field_filter = expanded_filter[field_name];
processed_filter[field_name] = field.filter_to_query(context, field_filter);
}
}
return Promise.props(processed_filter);
};
const get_output_options = function(collection, params){
const output_options = {};
if (params.pagination){
const default_pagination_params = {
page: 1,
items: 10
};
const full_pagination_params = merge(default_pagination_params, params.pagination);
const must_be_int = ["items", "page"];
must_be_int.forEach(function(attribute_name){
if (isNaN(parseInt(full_pagination_params[attribute_name]))){
full_pagination_params[attribute_name] = default_pagination_params[attribute_name];
} else {
full_pagination_params[attribute_name] = parseInt(full_pagination_params[attribute_name]);
}
});
output_options.skip = (full_pagination_params.page - 1) * full_pagination_params.items;
output_options.amount = full_pagination_params.items;
} else {
if (params.skip){
output_options.skip = parseInt(params.skip);
}
if (params.amount){
output_options.amount = parseInt(params.count);
}
}
if (params.sort){
const full_sort_params = clone(params.sort);
for (const field_name in full_sort_params){
switch (full_sort_params[field_name]){
case "desc":
full_sort_params[field_name] = -1;
break;
case "asc":
full_sort_params[field_name] = 1;
break;
default:
delete full_sort_params[field_name];
}
}
output_options.sort = full_sort_params;
}
return output_options;
};
CollectionSubject.prototype.__list_resources = function(datastore, collection, context, params){
if (params === undefined || params === null){
params = {};
}
const access_strategy = collection.get_access_strategy("retrieve");
let decoded_items;
const output_options = get_output_options(this.collection, params);
return collection.check_if_action_is_allowed(context, "retrieve")
.then(function(){
return CollectionSubject.prototype.__preprocess_resource_filter(collection, context, params.filter);
}).then(function(body_filter){
const query = {};
for(const field_name in body_filter){
- query["body." + field_name] = body_filter[field_name];
+ query[`body.${ field_name}`] = body_filter[field_name];
}
if (params.search){
query.$text = {
$search: params.search.toString(),
$caseSensitive: false,
$diacriticSensitive: false,
};
}
return datastore.find(collection.name, query, {}, output_options);
})
.map(function(db_document){
return collection.get_resource_representation(context, db_document, params.format)
.catch({type: "permission"}, function(error){
return undefined;
});
}).filter((e)=> e !== undefined)
.then(function(result){
decoded_items = result;
return access_strategy.is_item_sensitive();
})
.then(function(is_item_sensitive){
if (is_item_sensitive){
return Promise.filter(decoded_items, function(item){
return access_strategy.check(context, item)
.then(function(){
return true;
}).catch({type: "permission"}, function(err){
return false;
});
});
} else {
return decoded_items;
}
});
};
-CollectionSubject.prototype.list_resources = function(context, params){
- const datastore = ChipManager.get_datastore_chip();
- const self = this;
- return CollectionSubject.prototype.__list_resources(datastore, self.collection, context, params);
-};
-
CollectionSubject.prototype.perform_action = function(context, action_name, args){
switch (action_name){
case "create":
return this.create_resource(context, args);
case "show":
return this.list_resources(context, args);
default:
- throw new Errors.DeveloperError("Unknown action for '" + this.collection.name + "' collection: '" + action_name + "'");
+ throw new Errors.DeveloperError(`Unknown action for '${ this.collection.name }' collection: '${ action_name }'`);
}
};
-CollectionSubject.prototype.get_child_subject = function(key){
- const resource_id = key;
- const single_resource_subject = new SingleResource(this.collection, resource_id);
- return Promise.resolve(single_resource_subject);
-};
+CollectionSubject.subject_name = "collection";
module.exports = CollectionSubject;
diff --git a/lib/subject/subject-types/single-file-subject.js b/lib/subject/subject-types/single-file-subject.js
index da6a2392..a80bf369 100644
--- a/lib/subject/subject-types/single-file-subject.js
+++ b/lib/subject/subject-types/single-file-subject.js
@@ -1,40 +1,40 @@
"use strict";
const locreq = require("locreq")(__dirname);
const Subject = locreq("lib/subject/subject.js");
const Errors = locreq("lib/response/error.js");
-const FileManager = locreq("lib/core-services/file-manager.js");
const FileHash = function(file_id){
this.name = "FileHash";
this.file_id = file_id;
};
FileHash.prototype = Object.create(Subject.prototype);
FileHash.prototype.get_child_subject = function(file_name){
return new SingleFileSubject(this.file_id, file_name);
};
-const SingleFileSubject = function(file_id, file_name){
+const SingleFileSubject = function(app, file_id, file_name){
this.name = "SingleFile";
this.file_id = file_id;
this.file_name = file_name;
-};
-
-SingleFileSubject.prototype = Object.create(Subject.prototype);
-SingleFileSubject.prototype.perform_action = function(context, action_name, args){
- switch (action_name){
- case "show":
- return FileManager.find(context, {id: this.file_id})
+ SingleFileSubject.prototype.perform_action = function(context, action_name, args){
+ switch (action_name){
+ case "show":
+ return app.FileManager.find(context, {id: this.file_id})
.then(function(results){
return results[0];
});
- default:
- throw new Errors.DeveloperError(`Unknown action for '${this.collection.name}' subject: '${action_name}'`);
- }
+ default:
+ throw new Errors.DeveloperError(`Unknown action for '${this.collection.name}' subject: '${action_name}'`);
+ }
+ };
+
};
+SingleFileSubject.prototype = Object.create(Subject.prototype);
+
module.exports = FileHash;
diff --git a/lib/subject/subject-types/single-resource-subject.js b/lib/subject/subject-types/single-resource-subject.js
index a583bd9b..82af6f27 100644
--- a/lib/subject/subject-types/single-resource-subject.js
+++ b/lib/subject/subject-types/single-resource-subject.js
@@ -1,120 +1,120 @@
"use strict";
const locreq = require("locreq")(__dirname);
const Promise = require("bluebird");
const Subject = locreq("lib/subject/subject.js");
-const ChipManager = locreq("lib/chip-types/chip-manager.js");
const Errors = locreq("lib/response/error.js");
const CollectionFieldSubject = require("./collection-field-subject.js");
-const SingleResource = function(collection, resource_id){
+const SingleResource = function(app, collection, resource_id){
this.collection = collection;
this.resource_id = resource_id;
this.name = "SingleResource";
+
+ this.get_resource = function(context, args){
+ const datastore = app.ChipManager.get_datastore_chip();
+ return SingleResource.prototype.__get_resource(datastore, this.collection, this.resource_id, context, args);
+ };
+
+ this.delete_resource = function(context, args){
+ const datastore = app.ChipManager.get_datastore_chip();
+ const self = this;
+ return SingleResource.prototype.__delete_resource(datastore, self.collection, self.resource_id, context, args);
+ };
+
+ this.edit_resource = function(context, values_to_patch, delete_empty_values){
+ const datastore = app.ChipManager.get_datastore_chip();
+ const self = this;
+ return SingleResource.prototype.__edit_resource(datastore, self.collection, self.resource_id, context, values_to_patch, delete_empty_values);
+ };
+
};
SingleResource.prototype = Object.create(Subject.prototype);
SingleResource.prototype.__get_resource = function(datastore, collection, resource_id, context, args){
args = args || {};
return datastore.find(collection.name, {sealious_id: resource_id}, {})
.then(function(db_entries){
if (db_entries[0] === undefined){
- throw new Errors.NotFound("resource of id " + resource_id + " not found");
+ throw new Errors.NotFound(`resource of id ${ resource_id } not found`);
} else {
return collection.get_resource_representation(context, db_entries[0], args.format);
}
}).then(function(resource_representation){
return collection.check_if_action_is_allowed(context, "retrieve", resource_representation)
.then(function(){
return resource_representation;
});
});
};
-SingleResource.prototype.get_resource = function(context, args){
- const datastore = ChipManager.get_datastore_chip();
- return SingleResource.prototype.__get_resource(datastore, this.collection, this.resource_id, context, args);
-};
-
SingleResource.prototype.__edit_resource = function(datastore, collection, resource_id, context, values_to_patch, delete_empty_values){
// replaces just the provided values. Equivalent of PATCH request
delete_empty_values = (delete_empty_values === undefined? false : delete_empty_values);
let resource_representation;
return SingleResource.prototype.__get_resource(datastore, collection, resource_id, context, {})
.then(function(resource_data){
resource_representation = resource_data;
return collection.check_if_action_is_allowed(context, "update", resource_representation);
}).then(function(){
return collection.validate_field_values(context, delete_empty_values, values_to_patch, resource_representation.body);
}).then(function(){
return collection.encode_field_values(context, values_to_patch, resource_representation.body);
}).then(function(encoded_values){
const query = {};
query.last_modified_context = context;
for (const field_name in encoded_values){
- query["body." + field_name] = encoded_values[field_name];
+ query[`body.${ field_name}`] = encoded_values[field_name];
}
return datastore.update(collection.name, {sealious_id: resource_id}, {$set: query});
}).then(function(patch_result){
if(patch_result.result.nModified !== 1){
throw new Error("Wrong amount of resources (!=1) modified");
}
return SingleResource.prototype.__get_resource(datastore, collection, resource_id, context, resource_id);
});
};
-SingleResource.prototype.edit_resource = function(context, values_to_patch, delete_empty_values){
- const datastore = ChipManager.get_datastore_chip();
- const self = this;
- return SingleResource.prototype.__edit_resource(datastore, self.collection, self.resource_id, context, values_to_patch, delete_empty_values);
-};
-
SingleResource.prototype.__delete_resource = function(datastore, collection, resource_id, context, args){
return SingleResource.prototype.__get_resource(datastore, collection, resource_id, context, {})
.then(function(resource_representation){
return collection.check_if_action_is_allowed(context, "delete", resource_representation);
}).then(function(){
return datastore.remove(collection.name, {
sealious_id: resource_id,
}, {});
})
.then(function(data){
return Promise.resolve();
});
};
-SingleResource.prototype.delete_resource = function(context, args){
- const datastore = ChipManager.get_datastore_chip();
- const self = this;
- return SingleResource.prototype.__delete_resource(datastore, self.collection, self.resource_id, context, args);
-};
-
SingleResource.prototype.perform_action = function(context, action_name, args){
switch (action_name){
case "show":
return this.get_resource(context, args);
case "edit":
return this.edit_resource(context, args, false);
case "replace":
return this.edit_resource(context, args, true);
case "delete":
return this.delete_resource(context, args);
default:
throw new Errors.DeveloperError(`Unknown action for '${this.collection.name}' resource: '${action_name}'`);
}
};
SingleResource.prototype.get_child_subject = function(key){
if (this.collection.fields[key].type.is_subject){
return new CollectionFieldSubject(this.collection, this.resource_id, key);
}
};
module.exports = SingleResource;
diff --git a/lib/utils/check-for-updates.js b/lib/utils/check-for-updates.js
index 1c8c8dc0..30150243 100644
--- a/lib/utils/check-for-updates.js
+++ b/lib/utils/check-for-updates.js
@@ -1,44 +1,42 @@
"use strict";
const locreq = require("locreq")(__dirname);
const request = require("request-promise");
-const Logger = locreq("lib/logger/logger.js");
const Errors = locreq("lib/response/error.js");
-function check_for_updates(pkg){
+function check_for_updates(Logger){
+ const pkg = require(locreq.resolve("./package.json"));
if (typeof pkg === "object"){
const pkg_split = pkg.version.split(".");
- const version = pkg_split[0] + "." + pkg_split[1];
- const url = "http://registry.npmjs.org/sealious/" + version;
+ const version = `${pkg_split[0] }.${ pkg_split[1]}`;
+ const url = `http://registry.npmjs.org/sealious/${ version}`;
let status = "warning";
let message;
return request(url)
.then(res => JSON.parse(res))
.then(function(sealious_npm){
if (sealious_npm.error){
message = `npm registry error when requesting info for version ${version}: ${sealious_npm.error}`;
} else if (!sealious_npm.version || sealious_npm === undefined){
message = `unknown npm registry error when requesting info for version ${version}`;
} else {
const sealious_npm_array = sealious_npm.version.split(".");
-
if ((sealious_npm.version !== pkg.version) && (parseInt(sealious_npm_array[2]) > parseInt(pkg_split[2]))){
message = `Sealious@${pkg.version} - update available. Run "npm install sealious@${sealious_npm.version}" to update.`;
} else {
status = "info";
message = `Sealious@${pkg.version} is up-to-date`;
}
}
return {status, message};
})
.catch(function(err){
Logger.warning("No network connection available! Unable to fetch information about Sealious updates.");
throw err;
});
- }
- else {
- throw new Errors.ValidationError("Wrong arguments was passed!");
+ } else {
+ throw new Errors.ValidationError("Wrong arguments!");
}
}
module.exports = check_for_updates;
diff --git a/lib/utils/get-datetime.js b/lib/utils/get-datetime.js
new file mode 100644
index 00000000..9f44f5bb
--- /dev/null
+++ b/lib/utils/get-datetime.js
@@ -0,0 +1,36 @@
+"use strict";
+/*
+ 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){
+ const date = new Date();
+
+ let hour = date.getHours();
+ hour = (hour < 10 ? "0" : "") + hour;
+
+ let min = date.getMinutes();
+ min = (min < 10 ? "0" : "") + min;
+
+ let sec = date.getSeconds();
+ sec = (sec < 10 ? "0" : "") + sec;
+
+ let milli = date.getMilliseconds();
+ milli = (milli < 10 ? "00" : "") + milli;
+ milli = (milli < 100 && milli >= 10 ? "0" : "") + milli;
+
+ const year = date.getFullYear();
+
+ let month = date.getMonth() + 1;
+ month = (month < 10 ? "0" : "") + month;
+
+ let 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}`;
+ }
+}
+
+module.exports = getDateTime;
diff --git a/lib/utils/run-action.js b/lib/utils/run-action.js
deleted file mode 100644
index 05b8a319..00000000
--- a/lib/utils/run-action.js
+++ /dev/null
@@ -1,11 +0,0 @@
-"use strict";
-const locreq = require("locreq")(__dirname);
-
-const RootSubject = locreq("lib/subject/predefined-subjects/root-subject.js");
-
-module.exports = function(context, subject_path, action_name, params){
- return RootSubject.get_subject(subject_path)
- .then(function(subject){
- return subject.perform_action(context, action_name, params);
- });
-};
diff --git a/package.json b/package.json
index 1cfec994..4865bc45 100644
--- a/package.json
+++ b/package.json
@@ -1,58 +1,58 @@
{
"name": "sealious",
"homepage": "http://sealious.github.io/",
"version": "0.7.11",
"description": "A declarative framework for fast & easy app development.",
"main": "./lib/main.js",
"scripts": {
"test": "mocha --recursive tests",
"cover": "istanbul cover --include-all-sources _mocha -- -R spec --recursive tests",
"show-coverage": "npm run cover && (xdg-open ./coverage/lcov-report/index.html || exit 0)",
"coveralls": "npm run cover && cat coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js",
"eslint": "eslint lib && echo \"There are no errors.\" || (echo \"Errors in code were found. Run \"npm run eslint-fix\" or repair the problems yourself.\" && exit 1)",
"eslint-fix": "eslint --fix lib \"There are no errors.\" || (echo \"Errors in code were found. Run \"npm run eslint-fix\" or repair the problems yourself.\" && exit 1)"
},
"repository": {
"type": "git",
"url": "https://github.com/sealcode/sealious"
},
"keywords": [
"sealious"
],
"author": "The Sealious team (http://github.com/Sealious)",
"license": "BSD-2-Clause",
"bugs": {
"url": "https://github.com/Sealious/Sealious/issues"
},
"dependencies": {
"bluebird": "^3.3.3",
"bluebird-events": "^2.0.0",
"clone": "^1.0.2",
"color": "latest",
"escape-html": "^1.0.3",
"expand-hash": "^0.2.2",
- "fs-extra": "^0.30.0",
+ "js-yaml": "^3.6.1",
"locreq": "^1.1.0",
"merge": "^1.2.0",
"mime-types": "^2.1.11",
"node-uuid": "^1.4.7",
"request-promise": "^4.0.2",
"resolve": "^1.1.7",
"sanitize-html": "^1.13.0",
"sealious-datastore-tingo": "github:sealcode/sealious-datastore-tingo#alpha",
"shortid": "^2.2.6",
"winston": "^1.0.0"
},
"devDependencies": {
"coveralls": "^2.11.4",
"deep-equal": "^1.0.1",
"eslint": "^3.1.1",
"istanbul": "^0.4.1",
"mocha": "*",
"mocha-istanbul": "^0.2.0",
"pre-commit": "^1.1.3"
},
"pre-commit": [
"eslint"
]
}
diff --git a/tests/unit-tests/app/config-manager.test.js b/tests/unit-tests/app/config-manager.test.js
new file mode 100644
index 00000000..b74e3543
--- /dev/null
+++ b/tests/unit-tests/app/config-manager.test.js
@@ -0,0 +1,27 @@
+"use strict";
+const locreq = require("locreq")(__dirname);
+const ConfigManager = locreq("lib/app/config-manager.js");
+const assert = require("assert");
+
+describe("ConfigManager", function(){
+
+ describe(".pure", function(){
+ describe(".set_config", function(){
+ it("handles nested data", function(){
+ const default_config = {a: "A"};
+ const config = {b: {c: "D"}};
+ const change = ConfigManager.pure.set_config(
+ default_config,
+ config,
+ "b.c",
+ {e: "f"}
+ );
+ assert.deepEqual(
+ change,
+ [default_config, {b: {c: {e: "f"}}}]
+ );
+ });
+ });
+ });
+
+});
diff --git a/tests/unit-tests/app/logger.test.js b/tests/unit-tests/app/logger.test.js
new file mode 100644
index 00000000..c8f1aac2
--- /dev/null
+++ b/tests/unit-tests/app/logger.test.js
@@ -0,0 +1,6 @@
+"use strict";
+
+const locreq = require("locreq")(__dirname);
+const assert = require("assert");
+const Logger = locreq("lib/app/logger.js");
+const ConfigManager = locreq("lib/app/config-manager.js");
diff --git a/tests/unit-tests/base-chips/access-strategy/logged-in.test.js b/tests/unit-tests/base-chips/access-strategy/logged-in.test.js
index ea42ff2a..f1096078 100644
--- a/tests/unit-tests/base-chips/access-strategy/logged-in.test.js
+++ b/tests/unit-tests/base-chips/access-strategy/logged-in.test.js
@@ -1,29 +1,29 @@
"use strict";
const locreq = require("locreq")(__dirname);
const assert = require("assert");
-const logged_in = locreq("lib/base-chips/access-strategy-types/logged_in.js");
+const logged_in = locreq("lib/app/base-chips/access-strategy-types/logged_in.js");
describe("AccessStrategy.Logged_In", function() {
it("returns the name of the access strategy", function() {
assert.strictEqual(logged_in.name, "logged_in");
});
it("resolves the checker function", function(done) {
logged_in.checker_function({user_id: true})
.then(function() {
done();
})
.catch(function(err) {
done(new Error(err));
});
});
it("rejects the checker function", function(done) {
logged_in.checker_function({user_id: false})
.then(function() {
done("It didn't reject the checker function!");
})
.catch(function(err) {
assert.notStrictEqual(err.indexOf("Only logged-in users can perform this action."), -1);
done();
});
});
});
diff --git a/tests/unit-tests/base-chips/access-strategy/noone.test.js b/tests/unit-tests/base-chips/access-strategy/noone.test.js
index 4ca9d6e4..2fa018d3 100644
--- a/tests/unit-tests/base-chips/access-strategy/noone.test.js
+++ b/tests/unit-tests/base-chips/access-strategy/noone.test.js
@@ -1,23 +1,23 @@
"use strict";
const locreq = require("locreq")(__dirname);
const assert = require("assert");
-const noone = locreq("lib/base-chips/access-strategy-types/noone.js");
+const noone = locreq("lib/app/base-chips/access-strategy-types/noone.js");
describe("AccessStrategy.Noone", function() {
it("returns the name of the access strategy", function(){
assert.strictEqual(noone.name, "noone");
});
it("rejects the checker_function", function(done) {
noone.checker_function()
.then(function() {
done(new Error("It didn't reject!"));
})
.catch(function(err) {
assert.notStrictEqual(err.indexOf("Noone gets in!"), -1);
done();
});
});
it("checks item_sensitive atribute", function() {
assert.strictEqual(noone.item_sensitive, false);
});
});
diff --git a/tests/unit-tests/base-chips/access-strategy/owner.test.js b/tests/unit-tests/base-chips/access-strategy/owner.test.js
index ccff2d10..517c5f31 100644
--- a/tests/unit-tests/base-chips/access-strategy/owner.test.js
+++ b/tests/unit-tests/base-chips/access-strategy/owner.test.js
@@ -1,34 +1,34 @@
"use strict";
const locreq = require("locreq")(__dirname);
const assert = require("assert");
const Context = locreq("lib/context.js");
-const owner = locreq("lib/base-chips/access-strategy-types/owner.js");
+const owner = locreq("lib/app/base-chips/access-strategy-types/owner.js");
const assert_no_error = locreq("tests/util/assert-no-error.js");
const assert_error = locreq("tests/util/assert-error.js");
describe("AccessStrategy.owner", function(){
it("checks if the user is the owner and returns true", function(done){
const context = new Context(undefined, "ip", "user_id");
const item = {
created_context: {
user_id: "user_id"
}
}
const result = owner.checker_function(context, {}, item);
assert_no_error(result, done);
});
it("throws if the owner id doesn't match the owner in the created_context", function(done){
const context = new Context(undefined, "ip", "user_id");
const item = {
created_context: {
user_id: "other_user_id"
}
}
const result = owner.checker_function(context, {}, item);
assert_error(result, done);
});
it("checks item_sensitive attribute", function() {
assert.strictEqual(owner.item_sensitive, true);
});
});
diff --git a/tests/unit-tests/base-chips/access-strategy/public.test.js b/tests/unit-tests/base-chips/access-strategy/public.test.js
index 3e0e8385..11785ffb 100644
--- a/tests/unit-tests/base-chips/access-strategy/public.test.js
+++ b/tests/unit-tests/base-chips/access-strategy/public.test.js
@@ -1,22 +1,22 @@
"use strict";
const locreq = require("locreq")(__dirname);
const assert = require("assert");
-const public_as = locreq("lib/base-chips/access-strategy-types/public.js");
+const public_as = locreq("lib/app/base-chips/access-strategy-types/public.js");
describe("AccessStrategy.Public", function() {
it("returns the name of the access strategy", function() {
assert.strictEqual(public_as.name, "public");
});
it("accepts everyone", function(done) {
public_as.checker_function()
.then(function() {
done();
})
.catch(function(err){
done(new Error(err));
});
});
it("checks item_sensitive attribute", function() {
assert.strictEqual(public_as.item_sensitive, false);
});
});
diff --git a/tests/unit-tests/base-chips/field-types/boolean.test.js b/tests/unit-tests/base-chips/field-types/boolean.test.js
index 41b33e69..fed8cd4e 100644
--- a/tests/unit-tests/base-chips/field-types/boolean.test.js
+++ b/tests/unit-tests/base-chips/field-types/boolean.test.js
@@ -1,82 +1,82 @@
"use strict";
const locreq = require("locreq")(__dirname);
-const field_type_boolean = locreq("lib/base-chips/field-types/boolean.js");
+const field_type_boolean = locreq("lib/app/base-chips/field-types/boolean.js");
const Context = locreq("lib/context.js");
const test_is_proper_value = locreq("tests/util/test-is-proper-value.js");
const assert = require("assert");
describe("FieldType.Boolean", function(){
test_is_proper_value({
field_type: field_type_boolean,
should_accept: [
["integer", 1],
["integer", 0],
["boolean", true],
["boolean", false],
["string", "true"],
["string", "True"],
["string", "false"],
["string", "False"],
],
should_reject: [
["random string of text", "o87at gfoi4sg6npw98sh"],
]
});
it("returns the name of the field type", function(){
assert.strictEqual(field_type_boolean.name, "boolean");
});
it("returns the description of the field type", function(){
assert.strictEqual(typeof field_type_boolean.get_description(), "string");
});
describe(".encode", function(){
it("encodes the value correctly (given boolean)", function(){
assert.strictEqual(field_type_boolean.encode(new Context(), {}, true), true);
});
it("encodes the value correctly (given 1)", function(){
assert.strictEqual(field_type_boolean.encode(new Context(), {}, 1), true);
});
it("encodes the value correctly (given 0)", function(){
assert.strictEqual(field_type_boolean.encode(new Context(), {}, 0), false);
});
it("encodes the value correctly (given \"false\")", function(){
assert.strictEqual(field_type_boolean.encode(new Context(), {}, "false"), false);
});
it("encodes the value correctly (given \"true\")", function(){
assert.strictEqual(field_type_boolean.encode(new Context(), {}, "true"), true);
});
it("encodes the value correctly (given \"true\")", function(){
assert.strictEqual(field_type_boolean.encode(new Context(), {}, "true"), true);
});
})
it("doesn't encode the value (given 5)", function(){
assert.strictEqual(field_type_boolean.encode(new Context(), {}, 5), undefined);
});
it("filters to query when filter is an empty string", function(){
assert.deepEqual(field_type_boolean.filter_to_query(new Context(), {}, ""), {$in: [true, false]});
});
it("filters to query when filter is null", function(){
assert.deepEqual(field_type_boolean.filter_to_query(new Context(), {}, null), {$in: [true, false]});
});
it("filters by encoding the value \"true\"", function(){
assert.strictEqual(field_type_boolean.filter_to_query(new Context, {}, "true"), true);
});
it("filters by encoding the value \"false\"", function(){
assert.strictEqual(field_type_boolean.filter_to_query(new Context, {}, "false"), false);
});
it("filters by encoding the value \"1\"", function(){
assert.strictEqual(field_type_boolean.filter_to_query(new Context, {}, "1"), true);
});
it("filters by encoding the value \"0\"", function(){
assert.strictEqual(field_type_boolean.filter_to_query(new Context, {}, "0"), false);
});
it("filters by encoding the value 0", function(){
assert.strictEqual(field_type_boolean.filter_to_query(new Context, {}, 0), false);
});
});
diff --git a/tests/unit-tests/base-chips/field-types/color.test.js b/tests/unit-tests/base-chips/field-types/color.test.js
index 73dfbbd9..5217a04b 100644
--- a/tests/unit-tests/base-chips/field-types/color.test.js
+++ b/tests/unit-tests/base-chips/field-types/color.test.js
@@ -1,41 +1,41 @@
"use strict";
const locreq = require("locreq")(__dirname);
-const field_type_color = locreq("lib/base-chips/field-types/color.js");
+const field_type_color = locreq("lib/app/base-chips/field-types/color.js");
const Context = locreq("lib/context.js");
const assert = require("assert");
const test_is_proper_value = locreq("tests/util/test-is-proper-value.js");
describe("FieldType.Color", function(){
test_is_proper_value({
field_type: field_type_color,
should_accept: [
["hex", "#ff00ff"],
["shorthex", "#fff"],
["hsl", "hsl(0, 0%, 0%)"],
["hsl", "hsl(240, 100%, 80%)"],
["named color", "red"],
["rgb string", "rgb(255, 255, 255)"],
["rgb object", {r: 255, g: 255, b: 255}],
["hsla string", "hsla(262, 59%, 81%, 0.5)"],
],
should_reject: [
["random string of text", "o87at gfoi4sg6npw98sh"],
["malformed hsl", "hsl(240, 100%, 80%"],
]
});
it("returns the name of the field type", function(){
assert.strictEqual(field_type_color.name, "color");
});
it("checks if encode works correctly", function(){
assert.strictEqual(field_type_color.encode(new Context(), {}, {r: 0, g: 0, b: 0}), "#000000");
});
it("checks if encode works correctly", function(){
assert.strictEqual(field_type_color.encode(new Context(), {}, "black"), "#000000");
});
it("checks if encode works correctly", function(){
assert.strictEqual(field_type_color.encode(new Context(), {}, "hsl(0,0%,0%)"), "#000000");
});
});
diff --git a/tests/unit-tests/base-chips/field-types/context.test.js b/tests/unit-tests/base-chips/field-types/context.test.js
index 9281b707..80ca1dae 100644
--- a/tests/unit-tests/base-chips/field-types/context.test.js
+++ b/tests/unit-tests/base-chips/field-types/context.test.js
@@ -1,27 +1,27 @@
"use strict";
const locreq = require("locreq")(__dirname);
-const field_type_context = locreq("lib/base-chips/field-types/context.js");
+const field_type_context = locreq("lib/app/base-chips/field-types/context.js");
const Context = locreq("lib/context.js");
const assert = require("assert");
const test_is_proper_value = locreq("tests/util/test-is-proper-value.js");
describe("FieldType.Context", function(){
test_is_proper_value({
field_type: field_type_context,
should_accept: [
["a Context instance", new Context()],
],
should_reject: [
["a random string of text", "asofihas9efbaw837 asd"],
["an object that is not a Context instance", {user_id: null}]
]
});
it("returns the name of the field type", function(){
assert.strictEqual(field_type_context.name, "context");
});
});
diff --git a/tests/unit-tests/base-chips/field-types/date.test.js b/tests/unit-tests/base-chips/field-types/date.test.js
index b747cd80..f87aefa0 100644
--- a/tests/unit-tests/base-chips/field-types/date.test.js
+++ b/tests/unit-tests/base-chips/field-types/date.test.js
@@ -1,29 +1,29 @@
"use strict";
const locreq = require("locreq")(__dirname);
const Context = locreq("lib/context.js");
-const field_type_date = locreq("lib/base-chips/field-types/date.js");
+const field_type_date = locreq("lib/app/base-chips/field-types/date.js");
const test_is_proper_value = locreq("tests/util/test-is-proper-value.js");
const assert = require("assert");
describe("FieldType.Date", function(){
test_is_proper_value({
field_type: field_type_date,
should_accept: [
["a proper YYYY-MM-DD date", "2016-08-12"],
],
should_reject: [
["a random string of text", "asofihas9efbaw837 asd"],
["an integer value", Date.now()]
]
});
it("returns the name of the field type", function(){
assert.strictEqual(field_type_date.name, "date");
});
it("returns the description of the field type", function(){
assert.strictEqual(typeof field_type_date.get_description(), "string");
});
});
diff --git a/tests/unit-tests/base-chips/field-types/datetime.test.js b/tests/unit-tests/base-chips/field-types/datetime.test.js
index 3141d776..c5a3de6e 100644
--- a/tests/unit-tests/base-chips/field-types/datetime.test.js
+++ b/tests/unit-tests/base-chips/field-types/datetime.test.js
@@ -1,33 +1,33 @@
"use strict";
const locreq = require("locreq")(__dirname);
const Context = locreq("lib/context.js");
-const field_type_datetime = locreq("lib/base-chips/field-types/datetime.js");
+const field_type_datetime = locreq("lib/app/base-chips/field-types/datetime.js");
const test_is_proper_value = locreq("tests/util/test-is-proper-value.js");
const assert = require("assert");
describe("FieldType.Datetime", function(){
test_is_proper_value({
field_type: field_type_datetime,
should_accept: [
["a proper timestamp", Date.now()],
["a timestamp in a string", Date.now().toString()]
],
should_reject: [
["a random string of text", "asofihas9efbaw837 asd"],
["a date in YYYY-MM-DD format", "2016-08-12"]
]
});
it("returns the name of the field type", function() {
assert.strictEqual(field_type_datetime.name, "datetime");
});
it("returns the description of the field type", function(){
assert.strictEqual(typeof field_type_datetime.get_description(), "string");
});
it("checks if encode works properly (given \"1\")", function(){
assert.strictEqual(field_type_datetime.encode(new Context(), {}, "1"), 1);
});
});
diff --git a/tests/unit-tests/base-chips/field-types/email.test.js b/tests/unit-tests/base-chips/field-types/email.test.js
index 7ffb2476..a2ddc98d 100644
--- a/tests/unit-tests/base-chips/field-types/email.test.js
+++ b/tests/unit-tests/base-chips/field-types/email.test.js
@@ -1,31 +1,31 @@
"use strict";
const locreq = require("locreq")(__dirname);
const Context = locreq("lib/context.js");
-const field_type_email = locreq("lib/base-chips/field-types/email.js");
+const field_type_email = locreq("lib/app/base-chips/field-types/email.js");
const test_is_proper_value = locreq("tests/util/test-is-proper-value.js");
const assert = require("assert");
describe("FieldType.Email", function(){
test_is_proper_value({
field_type: field_type_email,
should_accept: [
["a properly formatted email address", "kuba@sealcode.org"],
["an email with numbers in the username", "kuba123@sealcode.org"],
["an email with all sorts of weird but allowed characters", "kuba-_123@sealcode.org"],
],
should_reject: [
["a random string of text", "asofihas9efbaw837 asd"],
["an incomplete email address", "kuba@sealcode"],
]
});
it("returns the name of the field type", function(){
assert.strictEqual(field_type_email.name, "email");
});
it("returns the description of the field type", function(){
assert.strictEqual(typeof field_type_email.get_description(), "string");
});
});
diff --git a/tests/unit-tests/base-chips/field-types/file.test.js b/tests/unit-tests/base-chips/field-types/file.test.js
index 2fc54a93..a80ac4c5 100644
--- a/tests/unit-tests/base-chips/field-types/file.test.js
+++ b/tests/unit-tests/base-chips/field-types/file.test.js
@@ -1,42 +1,52 @@
"use strict";
const locreq = require("locreq")(__dirname);
const Context = locreq("lib/context.js");
-const field_type_file = locreq("lib/base-chips/field-types/file.js");
const test_is_proper_value = locreq("tests/util/test-is-proper-value.js");
const File = locreq("lib/data-structures/file.js");
const assert = require("assert");
+const field_type_file_fn = locreq("lib/app/base-chips/field-types/file.js");
+const app = {};
+
+const field_type_file = field_type_file_fn(app);
+
describe("FieldType.File", function(){
test_is_proper_value({
- field_type: field_type_file,
+ field_type: field_type_file_fn(app),
should_accept: [
["a File instance", new File()],
["an object with filename and data attributes", {
filename: "test_filename",
data: new Buffer(1)
}],
["a proper URL to a downloadable file", "http://example.com"],
],
should_reject: [
["a random string of text", "asofihas9efbaw837 asd"],
["an empty objec", {}],
["an object with 'filename', but without 'data'", {filename: "picture.jpg"}],
["a malformed http url", "htpp://example.com"],
["a properly formed, but non-existing http url", "http://www.da3bba42e1f6d77a63bd665d0a82ff32.org"],
]
});
- it("checks if encode works correctly (value_in_code is false)", function(){
- assert.strictEqual(field_type_file.encode(new Context(), {}, false), null);
- });
- it("checks if decode works correctly (value_in_database is false, params.no_file_value is not given)", function(){
- assert.strictEqual(field_type_file.decode(new Context(), {}, false), undefined);
+ describe("encode", function(){
+ it("returns 'null' if 'value_in_code' is false", function(){
+ assert.strictEqual(field_type_file.encode(new Context(), {}, false), null);
+ });
});
- it("checks if decode works correctly (value_in_database is false, params.no_file_value is given)", function(){
- assert.strictEqual(field_type_file.decode(new Context(), {no_file_value: "test"}, false), "test");
+
+ describe("decode", function(){
+ it("returns undefined if value_in_database and params.no_file_value is not set", function(){
+ assert.strictEqual(field_type_file.decode(new Context(), {}, false), undefined);
+ });
+
+ it("return 'params.no_file_value' if value_in_db is false", function(){
+ assert.strictEqual(field_type_file.decode(new Context(), {no_file_value: "test"}, false), "test");
+ });
});
});
diff --git a/tests/unit-tests/base-chips/field-types/float.test.js b/tests/unit-tests/base-chips/field-types/float.test.js
index 4992dd95..7f0c3ff8 100644
--- a/tests/unit-tests/base-chips/field-types/float.test.js
+++ b/tests/unit-tests/base-chips/field-types/float.test.js
@@ -1,36 +1,36 @@
"use strict";
const locreq = require("locreq")(__dirname);
const Context = locreq("lib/context.js");
-const field_type_float = locreq("lib/base-chips/field-types/float.js");
+const field_type_float = locreq("lib/app/base-chips/field-types/float.js");
const test_is_proper_value = locreq("tests/util/test-is-proper-value.js");
const assert = require("assert");
describe("FieldType.Float", function(){
test_is_proper_value({
field_type: field_type_float,
should_accept: [
["a normal float number", Math.PI],
["a 0", 0],
["a negative integer", -1],
["a negative float", -1.5],
],
should_reject: [
["a random string of text", "asofihas9efbaw837 asd"],
["an improperly formatted float number", "2.123123.12312"],
]
});
it("returns the name of the field type", function() {
assert.strictEqual(field_type_float.name, "float");
});
it("returns the description of the field type", function(){
assert.strictEqual(typeof field_type_float.get_description(), "string");
});
it("checks if encode works properly (given \"2\")", function(){
assert.strictEqual(field_type_float.encode(new Context(), {}, "2.5"), 2.5);
});
});
diff --git a/tests/unit-tests/base-chips/field-types/hashed-text.test.js b/tests/unit-tests/base-chips/field-types/hashed-text.test.js
index 03960c54..8cd0adc5 100644
--- a/tests/unit-tests/base-chips/field-types/hashed-text.test.js
+++ b/tests/unit-tests/base-chips/field-types/hashed-text.test.js
@@ -1,76 +1,76 @@
"use strict";
const locreq = require("locreq")(__dirname);
const Context = locreq("lib/context.js");
-const field_type_hashed_text = locreq("lib/base-chips/field-types/hashed-text.js");
+const field_type_hashed_text = locreq("lib/app/base-chips/field-types/hashed-text.js");
const test_is_proper_value = locreq("tests/util/test-is-proper-value.js");
const assert = require("assert");
const crypto = require("crypto");
describe("FieldType.HashedText", function(){
test_is_proper_value({
field_type: field_type_hashed_text,
should_accept: [
- ["any password, if no params are given", "password"],
+ ["any password, if no params are given", "password", undefined],
["a proper password when 3 digits are required", "pass1sw2rd1", {digits: 3}],
["a proper password when 3 capitals are required", "PASword", {capitals: 3}],
["a proper password when 3 capitals and and 3 digits are required", "PASSword123", {capitals: 3, digits: 3}],
],
should_reject: [
["a password with insufficient amount of digits", "password", {digits: 3}],
["a password with insufficient amount of capitals", "password", {capitals: 3}],
["a password with enough capitals, but not enough digits", "PASSword", {capitals: 3, digits: 3}]
]
});
it("returns the name of the field type", function(){
assert.strictEqual(field_type_hashed_text.name, "hashed-text");
});
it("returns the field type it extends from", function(){
assert.strictEqual(field_type_hashed_text.extends, "text");
});
it("returns the description of the field type", function(){
assert.strictEqual(typeof field_type_hashed_text.get_description(), "string");
});
it("returns the description of the field type with params", function(){
const desc = field_type_hashed_text.get_description(new Context, {digits: 4, capitals: 2});
assert.notStrictEqual(desc.indexOf("required digits: 4"), -1);
assert.notStrictEqual(desc.indexOf("required capitals: 2"), -1);
});
it("resolves with a hash (algorithm: 'md5', salt: '')", function(done){
field_type_hashed_text.encode(new Context(), {}, "test")
.then(function(result){
crypto.pbkdf2("test", "", 4096, 64, "md5", function(err, key){
if (err) done(new Error(err));
assert.strictEqual(key.toString("hex"), result);
done();
});
})
.catch(function(error){
done(new Error(error));
});
});
it("encodes the password with custom params", function(done){
field_type_hashed_text.encode(new Context(), {salt: "", algorithm: "md5"}, "test")
.then(function(result){
crypto.pbkdf2("test", "", 4096, 64, "md5", function(err, key){
if (err) done(new Error(err));
assert.strictEqual(key.toString("hex"), result);
done();
});
})
.catch(function(error){
done(new Error(error));
});
});
it("decodes the password - returns null", function(){
assert.strictEqual(field_type_hashed_text.decode(new Context(), {hide_hash: true}), null);
});
it("decodes the password - returns the value in the database", function(){
assert.strictEqual(field_type_hashed_text.decode(new Context(), false, "value_in_db"), "value_in_db");
});
});
diff --git a/tests/unit-tests/base-chips/field-types/html.test.js b/tests/unit-tests/base-chips/field-types/html.test.js
index 1e64598f..7294a817 100644
--- a/tests/unit-tests/base-chips/field-types/html.test.js
+++ b/tests/unit-tests/base-chips/field-types/html.test.js
@@ -1,64 +1,64 @@
"use strict";
const locreq = require("locreq")(__dirname);
const Context = locreq("lib/context.js");
-const field_type_html = locreq("lib/base-chips/field-types/html.js");
+const field_type_html = locreq("lib/app/base-chips/field-types/html.js");
const test_is_proper_value = locreq("tests/util/test-is-proper-value.js");
const assert = require("assert");
const crypto = require("crypto");
describe("FieldType.html", function(){
// test_is_proper_value({
// field_type: field_type_html,
// should_accept: [
// ["a basic text string", "hello"],
// ["Any html, actually: it should be pretty liberal (it's user input, after all)", "<h1>Hello!</h1>"],
// ["It should accept text that is of acceptable length according to params inherited from field_type_text", "<h1>abc</h1>", {max_length: 20}],
// ],
// should_reject: [
// ["An html string that's too long according to 'field_type_text' params", "<h1>Hello</h1>", {max_width: 1}],
// ]
// });
describe(".encode", function(){
it("removes <script> tags", function(){
const raw_html = "<script>alert(true)</script>Hello!";
const encoded_value = field_type_html.encode(new Context(), {}, raw_html);
assert.deepEqual(encoded_value, {
original: raw_html,
safe: "Hello!",
});
});
it("removes onhover attributes", function(){
const raw_html = '<h1 onhover="alert(true)">Hello!</h1>';
const encoded_value = field_type_html.encode(new Context(), {}, raw_html);
assert.deepEqual(encoded_value, {
original: raw_html,
safe: "<h1>Hello!</h1>",
});
});
});
describe(".format", function(){
it("should return the safe version by default", function(){
const result = field_type_html.format(new Context(), {original: "a", safe: "b"});
assert.equal(result, "b");
});
it("should return the original version when asked for 'unsafe' format", function(){
const result = field_type_html.format(new Context(), {original: "a", safe: "b"}, 'unsafe');
assert.equal(result, "a");
});
it("should return the original version when asked for 'original' format", function(){
const result = field_type_html.format(new Context(), {original: "a", safe: "b"}, 'original');
assert.equal(result, "a");
});
});
});
diff --git a/tests/unit-tests/base-chips/field-types/int.test.js b/tests/unit-tests/base-chips/field-types/int.test.js
index 9a241cbd..43a4f9cc 100644
--- a/tests/unit-tests/base-chips/field-types/int.test.js
+++ b/tests/unit-tests/base-chips/field-types/int.test.js
@@ -1,34 +1,87 @@
"use strict";
const locreq = require("locreq")(__dirname);
const Context = locreq("lib/context.js");
-const field_type_int = locreq("lib/base-chips/field-types/int.js");
+const field_type_int = locreq("lib/app/base-chips/field-types/int.js");
const test_is_proper_value = locreq("tests/util/test-is-proper-value.js");
const assert = require("assert");
describe("FieldType.Int", function(){
test_is_proper_value({
field_type: field_type_int,
should_accept: [
["a positive integer", 1],
["a negative integer", -1],
["a zero", 0],
],
should_reject: [
["a random string of text", "asofihas9efbaw837 asd"],
["a number with decimals", 2.5],
]
});
it("returns the name of the field type", function(){
assert.strictEqual(field_type_int.name, "int");
});
it("should return the description of the field type", function(){
assert.strictEqual(typeof field_type_int.get_description(), "string");
});
it("should check if encode works properly (given \"2\")", function(){
assert.strictEqual(field_type_int.encode(new Context(), {}, "2"), 2);
});
+
+ describe(".filter_to_query", function(){
+ it("returns {$eq: value} if field_filter is a Number", function(){
+ const result = field_type_int.filter_to_query(
+ new Context(),
+ {},
+ 3
+ );
+ assert.deepEqual(result, {$eq: 3});
+ });
+
+ it("returns {$eq: value} if field_filter is a Number-like string", function(){
+ const result = field_type_int.filter_to_query(
+ new Context(),
+ {},
+ "3"
+ );
+ assert.deepEqual(result, {$eq: 3});
+ });
+
+ it("returns {$eq: value} if field_filter is {'=': value}", function(){
+ const result = field_type_int.filter_to_query(
+ new Context(),
+ {},
+ {"=": "3"}
+ );
+ assert.deepEqual(result, {$eq: 3});
+ });
+
+ it("returns {$lt: value} if field_filter is {'<': value}", function(){
+ const result = field_type_int.filter_to_query(
+ new Context(),
+ {},
+ {"<": "3"}
+ );
+ assert.deepEqual(result, {$lt: 3});
+ });
+
+ it("throws an error if given an unknown comparator", function(){
+ try{
+ const result = field_type_int.filter_to_query(
+ new Context(),
+ {},
+ {"~": "3"}
+ );
+ }catch(error){
+ assert.equal(error.type, "validation");
+ return;
+ }
+ throw new Error("It didn't throw an error");
+ });
+
+ });
});
diff --git a/tests/unit-tests/base-chips/field-types/single_reference.test.js b/tests/unit-tests/base-chips/field-types/single_reference.test.js
index bb1f3d7d..b9345815 100644
--- a/tests/unit-tests/base-chips/field-types/single_reference.test.js
+++ b/tests/unit-tests/base-chips/field-types/single_reference.test.js
@@ -1,49 +1,58 @@
"use strict";
const locreq = require("locreq")(__dirname);
const Context = locreq("lib/context.js");
-const field_type_single_reference = locreq("lib/base-chips/field-types/single_reference.js");
+const Promise = require("bluebird");
+
+const field_type_single_reference_fn = locreq("lib/app/base-chips/field-types/single_reference.js");
+const app = {};
+const field_type_single_reference = field_type_single_reference_fn(app);
+
const assert = require("assert");
+const assert_error_type = locreq("tests/util/assert-error-type.js");
+const Errors = locreq("lib/response/error.js");
+const Collection = locreq("lib/chip-types/collection.js");
+
+describe("FieldType.single_reference", function(){
-describe("FieldType.Username", function(){
describe(".encode", function(){
it("should return the value unchanged if it is a string", function(){
let result = field_type_single_reference.encode(
new Context(),
{},
"randomid"
);
assert.equal(result, "randomid");
});
it("should return the .id attribute if given value is an object", function(){
let result = field_type_single_reference.encode(
new Context(),
{},
{id: "randomid"}
);
assert.equal(result, "randomid");
});
});
describe(".format", function(){
it("should return the decoded value unchanged if no format params are provided", function(){
let result = field_type_single_reference.format(
new Context(),
undefined,
"randomid"
- )
+ );
assert.equal(result, "randomid");
});
});
describe(".filter_to_query", function(){
it("should return the value (supposed to be a resource_id wrapped in {$eq: ''}", function(){
let result = field_type_single_reference.filter_to_query(
new Context(),
{},
"randomid"
);
assert.deepEqual(result, {$eq: "randomid"});
});
});
});
diff --git a/tests/unit-tests/base-chips/field-types/text.test.js b/tests/unit-tests/base-chips/field-types/text.test.js
index 61b3e120..72f23280 100644
--- a/tests/unit-tests/base-chips/field-types/text.test.js
+++ b/tests/unit-tests/base-chips/field-types/text.test.js
@@ -1,91 +1,91 @@
"use strict";
const locreq = require("locreq")(__dirname);
const Context = locreq("lib/context.js");
-const field_type_text = locreq("lib/base-chips/field-types/text.js");
+const field_type_text = locreq("lib/app/base-chips/field-types/text.js");
const assert_no_error = locreq("tests/util/assert-no-error.js");
const test_is_proper_value = locreq("tests/util/test-is-proper-value.js");
const assert = require("assert");
describe("FieldType.Text", function(){
test_is_proper_value({
field_type: field_type_text,
should_accept: [
["a string of text", "hello"],
["a string of text shorter than max_length", "hello", {max_length: 10}],
["a string of text longer than min_length", "hello", {min_length: 2}],
["a string of text longer than min_length and shorter than max_length", "abc", {min_length: 2, max_length: 4}],
],
should_reject: [
["a text that's too long", "hamster, a dentist", {max_length: 5}],
["a string of text shorter than min_length", "h", {min_length: 2}],
["a string of text shorter than max, but too short", "ab", {min_length: 3, max_length: 5}],
]
});
describe(".has_index", function(){
it("returns false if 'params.full_text_search' is not set", function(){
assert.strictEqual(field_type_text.has_index({}), false);
});
it("returns false if 'params.full_text_search' is set to 'false'", function(){
assert.strictEqual(field_type_text.has_index({full_text_search: false}), false);
});
it("returns 'text' if 'params.full_text_search' is set to 'false'", function(){
assert.strictEqual(field_type_text.has_index({full_text_search: true}), "text");
});
});
it("returns the name of the field type", function(){
assert.strictEqual(field_type_text.name, "text");
});
it("returns the description of the field type", function(){
assert.strictEqual(typeof field_type_text.get_description(new Context(), {max_length: 10}), "string");
});
it("checks if encode work properly (value_in_code is a string)", function(done){
field_type_text.encode(new Context, {}, "<a>string</a>")
.then(function(result){
assert.strictEqual(result.original, "<a>string</a>");
assert.strictEqual(result.safe, "&lt;a&gt;string&lt;/a&gt;");
assert.strictEqual(result.valueOf(), "<a>string</a>");
done();
})
.catch(function(err){
done(new Error(err));
});
});
it("checks if encode works properly (sanitizes html)", function(done){
field_type_text.encode(new Context(), {}, "outside<script>alert(\"a\")</script>")
.then(function(result){
assert.strictEqual(result.safe, "outside&lt;script&gt;alert(&quot;a&quot;)&lt;/script&gt;");
done();
})
.catch(function(error){
done(new Error(error));
});
});
it("resolved with null when value_in_code is null", function(done){
field_type_text.encode(new Context(), {}, null)
.then(function(result){
assert.strictEqual(result, null);
done();
})
.catch(function(error){
done(new Error(error));
});
});
it("checks if encode works properly", function(done){
field_type_text.encode(new Context(), {}, {})
.then(function(){
done();
})
.catch(function(error){
done(new Error(error));
});
});
});
diff --git a/tests/unit-tests/base-chips/field-types/username.test.js b/tests/unit-tests/base-chips/field-types/username.test.js
index 547a7324..9ae03eb4 100644
--- a/tests/unit-tests/base-chips/field-types/username.test.js
+++ b/tests/unit-tests/base-chips/field-types/username.test.js
@@ -1,29 +1,51 @@
"use strict";
const locreq = require("locreq")(__dirname);
const Context = locreq("lib/context.js");
-const field_type_username = locreq("lib/base-chips/field-types/username.js");
+const field_type_username_fn = locreq("lib/app/base-chips/field-types/username.js");
+const app = {};
+const field_type_username = field_type_username_fn(app);
const test_is_proper_value = locreq("tests/util/test-is-proper-value.js");
const assert = require("assert");
+const assert_error = locreq("tests/util/assert-error.js");
describe("FieldType.Username", function(){
test_is_proper_value({
field_type: field_type_username,
should_accept: [
["the same value as in old_value", "username", {}, "username"],
],
should_reject: [
["a reserced keyword", "me"],
]
});
+ it("rejects when the given username already exists and is a new value", function(done){
+ const mockup_app = {
+ run_action: function(){
+ return Promise.resolve(["i exist"]);
+ }
+ };
+
+ assert_error(
+ field_type_username_fn(mockup_app).is_proper_value(
+ new Context(),
+ {},
+ "username",
+ "different_username"
+ ),
+ done
+ );
+ });
+
+
it("returns the name of the field type", function(){
assert.strictEqual(field_type_username.name, "username");
});
it("returns the name of the field type it extends", function(){
assert.strictEqual(field_type_username.extends, "text");
});
});
diff --git a/tests/unit-tests/chip-types/access-strategy-type.test.js b/tests/unit-tests/chip-types/access-strategy-type.test.js
index 93892501..ab599538 100644
--- a/tests/unit-tests/chip-types/access-strategy-type.test.js
+++ b/tests/unit-tests/chip-types/access-strategy-type.test.js
@@ -1,152 +1,131 @@
"use strict";
const locreq = require("locreq")(__dirname);
const AccessStrategyType = locreq("lib/chip-types/access-strategy-type.js");
const SuperContext = locreq("lib/super-context.js");
const Context = locreq("lib/context.js");
const assert_no_error = locreq("tests/util/assert-no-error.js");
const assert_error_type = locreq("tests/util/assert-error-type.js");
const assert_error = locreq("tests/util/assert-error.js");
const assert = require("assert");
+const AST = AccessStrategyType;
const ASTP = AccessStrategyType.prototype;
+const app = {};
+
describe("AccessStrategyType", function(){
it("when the declaration is just an AST instance, returns it unchanged", function(){
- const AST = new AccessStrategyType({checker_function: ()=>true});
- assert.strictEqual(new AccessStrategyType(AST), AST);
+ const AST = new AccessStrategyType(app, {checker_function: ()=>true});
+ assert.strictEqual(new AccessStrategyType(app, AST), AST);
});
- describe(".prototype.__is_item_sensitive", function(){
+ describe(".pure.is_item_sensitive", function(){
it("should work with a boolean 'item_sensitive' value: false", function(done){
- ASTP.__is_item_sensitive({
+ AST.pure.is_item_sensitive({
item_sensitive: false
}).then(function(result){
assert.strictEqual(result, false);
done();
});
});
it("should work with a boolean 'item_sensitive' value: true", function(done){
- ASTP.__is_item_sensitive({
+ AST.pure.is_item_sensitive({
item_sensitive: true
}).then(function(result){
assert.strictEqual(result, true);
done();
});
});
it("should work with a function that returns a Boolean value: false", function(done){
- ASTP.__is_item_sensitive({
+ AST.pure.is_item_sensitive({
item_sensitive: () => false
}).then(function(result){
assert.strictEqual(result, false);
done();
});
});
it("should work with a function that returns a Boolean value: true", function(done){
- ASTP.__is_item_sensitive({
+ AST.pure.is_item_sensitive({
item_sensitive: () => true
}).then(function(result){
assert.strictEqual(result, true);
done();
});
});
it("should work with a function that returns a Boolean Promise value: false", function(done){
- ASTP.__is_item_sensitive({
+ AST.pure.is_item_sensitive({
item_sensitive: () => Promise.resolve(false)
}).then(function(result){
assert.strictEqual(result, false);
done();
});
});
it("should work with a function that returns a Boolean Promise value: true", function(done){
- ASTP.__is_item_sensitive({
+ AST.pure.is_item_sensitive({
item_sensitive: () => Promise.resolve(true)
}).then(function(result){
assert.strictEqual(result, true);
done();
});
});
});
- describe(".prototype.__check", function(){
+ describe(".pure.check", function(){
it("should resolve if given an instance of SuperContext", function(done){
const sc = new SuperContext();
- const result = ASTP.__check({}, sc);
+ const result = AST.pure.check({}, sc);
assert_no_error(result, done);
});
it("should resolve with undefined if the strategy is item_sensitive but no item is provided", function(done){
- ASTP.__check({item_sensitive: true}, new Context(), {})
+ AST.pure.check({item_sensitive: true}, new Context(), {})
.then(function(result){
assert.strictEqual(result, undefined);
done();
});
});
it("should accept 'false' as a return value in checker_function", function(done){
const declaration = {checker_function: () => false};
- const result = ASTP.__check(declaration, new Context(), {});
+ const result = AST.pure.check(declaration, new Context(), {});
assert_error_type(result, "permission", done);
});
it("should accept 'true' as a return value in checker_function", function(done){
const declaration = {checker_function: () => true};
- const result = ASTP.__check(declaration, new Context(), {});
+ const result = AST.pure.check(declaration, new Context(), {});
assert_no_error(result, done);
});
it("should throw an error raised inside checker_function", function(done){
const declaration = {checker_function: function(){
throw new Error("Eat my shorts");
}};
- const result = ASTP.__check(declaration, new Context(), {});
+ const result = AST.pure.check(declaration, new Context(), {});
assert_error(result, done);
});
it("should pass item as argument if the strategy is item_sensitive", function(done){
const item = {};
- ASTP.__check(
+ AST.pure.check(
{
item_sensitive: true,
checker_function: function(context, params, _item){
assert.strictEqual(_item, item);
done();
}
},
new Context(),
{},
item
- )
- });
- });
-
- describe("the bridges between the pure methods", function(){
- it("properly connects the __check method", function(done){
- const smth = {}
- const declaration = {
- checker_function: () => true
- };
-
- const strategy_type = new AccessStrategyType(declaration);
- const result = strategy_type.check(new Context(), {}, {});
- assert_no_error(result, done);
- });
-
- it("properly connects the __is_item_sensitive method", function(done){
- const smth = {}
- const declaration = {
- item_sensitive: () => true
- };
-
- const strategy_type = new AccessStrategyType(declaration);
- const result = strategy_type.is_item_sensitive({});
- assert_no_error(result, done);
+ );
});
});
});
diff --git a/tests/unit-tests/chip-types/chip-manager.test.js b/tests/unit-tests/chip-types/chip-manager.test.js
index 658bf236..8e2bf40e 100644
--- a/tests/unit-tests/chip-types/chip-manager.test.js
+++ b/tests/unit-tests/chip-types/chip-manager.test.js
@@ -1,54 +1,35 @@
"use strict";
const locreq = require("locreq")(__dirname);
-const ChipManager = locreq("lib/chip-types/chip-manager.js");
+const ChipManager = locreq("lib/app/chip-manager.js");
const assert = require("assert");
describe("ChipManager", function(){
const chips = {
collection: {
test: {},
test2: {}
}
};
it("gets all resource types", function(){
- const names = ChipManager.__get_all_collections(chips);
+ const names = ChipManager.pure.get_all_collections(chips);
assert.notStrictEqual(names.indexOf("test"), -1);
assert.notStrictEqual(names.indexOf("test2"), -1);
});
- it("gets chip by longid (longid exists)", function(){
- const chip = ChipManager.__get_chip_by_longid(chips, "collection.test");
- assert.strictEqual(chip, chips.collection.test);
- });
-
- it("throws an error when get_chip_by_longid has non existent longid", function(){
- assert.throws(
- function() {
- ChipManager.__get_chip_by_longid(chips, "doesn't exist");
- },
- function(err) {
- if (err.type === "validation"){
- return true;
- }
- },
- "unexpected error"
- );
- });
-
it("gets chip amount by type and returns 0 (non existent type)", function(){
- const amount = ChipManager.__get_chip_amount_by_type(chips, "non existent");
+ const amount = ChipManager.pure.get_chip_amount_by_type(chips, "non existent");
assert.strictEqual(amount, 0);
});
it("gets chips by type (type exists)", function(){
- const received_chips = ChipManager.__get_chips_by_type(chips, "collection");
+ const received_chips = ChipManager.pure.get_chips_by_type(chips, "collection");
assert.strictEqual(received_chips.test, chips.collection.test);
});
it("gets chips by type (type doesn't exist)", function(){
- const chips = ChipManager.get_chips_by_type("troll_type");
+ const chips = ChipManager.pure.get_chips_by_type({}, "troll_type");
assert.strictEqual(chips, undefined);
});
})
diff --git a/tests/unit-tests/chip-types/field-structures/single.test.js b/tests/unit-tests/chip-types/field-structures/single.test.js
deleted file mode 100644
index 16387978..00000000
--- a/tests/unit-tests/chip-types/field-structures/single.test.js
+++ /dev/null
@@ -1,25 +0,0 @@
-"use strict";
-const locreq = require("locreq")(__dirname);
-const assert = require("assert");
-const Promise = require("bluebird");
-
-const Single = locreq("lib/chip-types/field-structures/single.js");
-const HashedText = locreq("lib/base-chips/field-types/hashed-text.js");
-HashedText.params = {};
-
-describe("Sealious.FieldStructures.Single", function() {
- it("properly returns .encode() value of another field", function(done){
- const promises = [
- HashedText.encode(null, {}, "test"),
- Single.encode(null, HashedText, "test")
- ];
- Promise.all(promises)
- .then(function(result) {
- assert.strictEqual(result[0], result[1]);
- done();
- }).catch(done);
- });
- it("properly returns .decode() value of another field", function() {
- assert.strictEqual(Single.decode(null, HashedText, "test"), "test");
- });
-});
diff --git a/tests/unit-tests/chip-types/field-type.test.js b/tests/unit-tests/chip-types/field-type.test.js
index 604972fd..ccebc59d 100644
--- a/tests/unit-tests/chip-types/field-type.test.js
+++ b/tests/unit-tests/chip-types/field-type.test.js
@@ -1,31 +1,32 @@
const assert = require("assert");
const locreq = require("locreq")(__dirname);
const FieldType = locreq("lib/chip-types/field-type.js");
+const app = {};
describe("Sealious.FieldType", function(){
it("loads a predefined chip", function(done){
- const int = locreq("lib/base-chips/field-types/int.js");
- const field_type = new FieldType(int);
+ const int = locreq("lib/app/base-chips/field-types/int.js");
+ const field_type = new FieldType(app, int);
assert.strictEqual(field_type.name, "int");
field_type.get_description()
.then(function(description){
assert.strictEqual(description, "An integer number.");
}).catch(done);
field_type.is_proper_value(null, null, 2)
.then(function(){
}).catch(done);
field_type.encode(null, null, "2")
.then(function(result){
assert.strictEqual(result, 2);
});
field_type.is_proper_value(null, null, "a")
.then(function(){
done(new Error("It didn't reject"));
})
.catch(function(err){
assert.strictEqual(err, "Value 'a' is not a int number format.");
done();
});
});
});
diff --git a/tests/unit-tests/config/config-manager.test.js b/tests/unit-tests/config/config-manager.test.js
deleted file mode 100644
index b3d1a23e..00000000
--- a/tests/unit-tests/config/config-manager.test.js
+++ /dev/null
@@ -1,80 +0,0 @@
-"use strict";
-const locreq = require("locreq")(__dirname);
-const ConfigManager = locreq("lib/config/config-manager.js");
-const assert = require("assert");
-
-describe("ConfigManager", function(){
-
- it("sets a new config and then gets it", function(){
- ConfigManager.set_config(
- "test.config", {
- "test_key_object": {
- "my_key": "my_value"
- }
- }
- );
- const config = ConfigManager.get_config("test.config");
- assert.deepEqual(config, { test_key_object: { my_key: "my_value" }});
- });
-
- it("sets a default config, modifies it and then gets it", function(){
- ConfigManager.set_default_config(
- "test.config", {
- "test_key_object": {
- "my_key": "my_value"
- }
- }
- );
- ConfigManager.set_config(
- "test.config", {
- "test_key_object2": {
- "my_key2": "my_value2"
- }
- }
- );
- const config = ConfigManager.get_config("test.config");
- assert.deepEqual(config, { test_key_object: { my_key: "my_value" }, test_key_object2: { my_key2: "my_value2" } });
- });
-
- it("sets such a config that Object.assign will not parse it correctly", function(){
- ConfigManager.set_default_config(
- "test.config2", {
- foo: {
- bar: "baz",
- bat: "bax"
- }
- }
- );
- ConfigManager.set_config(
- "test.config2", {
- foo: {
- bam: "bak"
- }
- }
- );
- const config = ConfigManager.get_config("test.config2");
- assert.deepEqual(config, { foo: { bar: "baz", bat: "bax", bam: "bak" } });
- });
-
- it("gets configuration", function(){
- ConfigManager.set_default_config(
- "test_config", {
- test_field: "test_value",
- is_test: true,
- });
- const config = ConfigManager.get_config().test_config;
- assert.strictEqual(config.test_field, "test_value");
- assert.strictEqual(config.is_test, true);
- });
-
- it("gets dispatcher config", function(){
- const dispatcher_config = ConfigManager.get_dispatcher_config();
- assert.strictEqual(dispatcher_config instanceof Object, true);
- assert.strictEqual(Object.getOwnPropertyNames(dispatcher_config).length, 0);
- });
-
- it("gets non existent chip config and returns undefined", function(){
- const dispatcher_config = ConfigManager.get_chip_config("some_non_existent_longid");
- assert.strictEqual(dispatcher_config, undefined);
- });
-});
diff --git a/tests/unit-tests/logger/logger.test.js b/tests/unit-tests/logger/logger.test.js
deleted file mode 100644
index d524d0db..00000000
--- a/tests/unit-tests/logger/logger.test.js
+++ /dev/null
@@ -1,26 +0,0 @@
-"use strict";
-
-const locreq = require("locreq")(__dirname);
-const assert = require("assert");
-const Logger = locreq("lib/logger/logger.js");
-const ConfigManager = locreq("lib/config/config-manager.js");
-
-describe("Sealious.Logger", function(){
- it("gets default config of Logger", function(){
- const config = ConfigManager.get_config().logger_config;
- assert.strictEqual(config.logger_level, "info");
- assert.strictEqual(config.logger_color, true);
- assert.strictEqual(config.logger_file, null);
- assert.strictEqual(config.logger_dirname, ".");
- assert.strictEqual(config.logger_to_json, false);
- assert.strictEqual(config.logger_rotation, ".yyyy-MM-Tdd");
- });
- it("checks if levels are correct", function(){
- assert.strictEqual(Logger.levels.lazyseal, 0);
- assert.strictEqual(Logger.levels.info, 1);
- assert.strictEqual(Logger.levels.debug, 2);
- assert.strictEqual(Logger.levels.warning, 3);
- assert.strictEqual(Logger.levels.error, 4);
- assert.strictEqual(Logger.levels.no_output, 5);
- });
-});
diff --git a/tests/unit-tests/response/error.test.js b/tests/unit-tests/response/error.test.js
index f58795e1..33d6d006 100644
--- a/tests/unit-tests/response/error.test.js
+++ b/tests/unit-tests/response/error.test.js
@@ -1,91 +1,71 @@
"use strict";
const locreq = require("locreq")(__dirname);
const Errors = locreq("lib/response/error.js");
const assert = require("assert");
describe("Sealious.Errors", function(){
it("transforms an Error to an object", function() {
const error = new Errors.Error("Example error");
const error_to_object = error.to_object();
- assert.strictEqual(error_to_object.message, "Example error");
- assert.strictEqual(error_to_object.type, "error");
- assert.deepEqual(error_to_object.data, {});
+ assert.strictEqual(error_to_object.message.content, "Example error");
+ assert.strictEqual(error_to_object.message.type, "error");
+ assert.deepEqual(error_to_object.message.data, {});
});
it("throws a Sealious.Errors.Error", function(){
const erronous = function() {
throw new Errors.Error("This is just an error", {type: "test_error"});
- }
- const checkError = function(err) {
- if (err.type === "test_error") {
- return true;
- }
- }
+ };
+ const checkError = (err) => err.type === "test_error";
assert.throws(erronous, checkError, "Unexpected error");
});
it("throws a Sealious.Errors.ValidationError", function(){
const erronous = function() {
throw new Errors.ValidationError("This is just an error");
- }
+ };
const checkError = function(err) {
- if (err.type === "validation") {
- return true;
- }
- }
+ return err.type === "validation";
+ };
assert.throws(erronous, checkError, "Unexpected error");
});
it("throws a Sealious.Errors.ValueExists", function(){
const erronous = function() {
throw new Errors.ValueExists("This is just an error");
- }
+ };
const checkError = function(err) {
- if (err.type === "value_exists") {
- return true;
- }
- }
+ return err.type === "value_exists";
+ };
assert.throws(erronous, checkError, "Unexpected error");
});
it("throws a Sealious.Errors.InvalidCredentials", function(){
const erronous = function() {
throw new Errors.InvalidCredentials("This is just an error");
- }
- const checkError = function(err) {
- if (err.type === "invalid_credentials") {
- return true;
- }
- }
+ };
+ const checkError = (err) => err.type === "invalid_credentials";
assert.throws(erronous, checkError, "Unexpected error");
});
it("throws a Sealious.Errors.NotFound", function(){
const erronous = function() {
throw new Errors.NotFound("This is just an error");
- }
- const checkError = function(err) {
- if (err.type === "not_found") {
- return true;
- }
- }
+ };
+ const checkError = (err) => err.type === "not_found";
assert.throws(erronous, checkError, "Unexpected error");
});
it("throws a Sealious.Errors.DeveloperError", function(){
const erronous = function() {
throw new Errors.DeveloperError("This is just an error");
- }
- const checkError = function(err) {
- if (err.type === "dev_error") {
- return true;
- }
- }
+ };
+ const checkError = (err) => err.type === "dev_error";
assert.throws(erronous, checkError, "Unexpected error");
});
it("throws a Sealious.Errors.BadContext", function(){
const erronous = function() {
throw new Errors.BadContext("This is just an error");
- }
+ };
const checkError = function(err) {
if (err.type === "permission") {
return true;
}
- }
+ };
assert.throws(erronous, checkError, "Unexpected error");
});
});
diff --git a/tests/unit-tests/response/response.test.js b/tests/unit-tests/response/response.test.js
index 9c9def9d..73ddee8f 100644
--- a/tests/unit-tests/response/response.test.js
+++ b/tests/unit-tests/response/response.test.js
@@ -1,25 +1,25 @@
"use strict";
const locreq = require("locreq")(__dirname);
const Response = locreq("lib/response/response.js");
const Errors = locreq("lib/response/error.js");
const Context = locreq("lib/context.js");
const assert = require("assert");
describe("Sealious.Response", function(){
it("returns a Response object", function(){
const response = new Response({test: 1}, false, "my_type", "my_status_message");
assert.deepEqual(response.data, {test: 1});
assert.strictEqual(response.status, "success");
assert.strictEqual(response.type, "my_type");
assert.strictEqual(response.status_message, "my_status_message");
});
it("returns a Response object from an error", function() {
const error = new Errors.BadContext("This is an error", "test_data");
const response = Response.fromError(error);
assert.strictEqual(response.data, "test_data");
- assert.strictEqual(response.type, "permission");
- assert.strictEqual(response.status_message, "This is an error");
+ assert.strictEqual(response.message.type, "permission");
+ assert.strictEqual(response.status_message.content, "This is an error");
});
});
diff --git a/tests/unit-tests/utils/check-version.test.js b/tests/unit-tests/utils/check-version.test.js
deleted file mode 100644
index 1f970cb2..00000000
--- a/tests/unit-tests/utils/check-version.test.js
+++ /dev/null
@@ -1,62 +0,0 @@
-"use strict";
-const locreq = require("locreq")(__dirname);
-const check_for_updates = locreq("lib/utils/check-for-updates.js");
-const request = require("request-promise");
-const assert = require("assert");
-
-describe("Sealious.check_for_updates", function(){
- it("says there are no updates to Sealious", function(done){
- request("http://registry.npmjs.org/sealious/0.7")
- .then(res => JSON.parse(res))
- .then(sealious_npm => check_for_updates(sealious_npm))
- .then(function(response){
- const status = response.status;
- const message = response.message;
- assert.strictEqual(status, "info");
- assert.notStrictEqual(message.indexOf("up-to-date"), -1);
- done();
- })
- .catch(function(err){
- done(new Error(err));
- });
- });
- it("says there are updates to Sealious", function(done){
- const pkg = {version: "0.7.1"};
- check_for_updates(pkg)
- .then(function(response){
- const status = response.status;
- const message = response.message;
- assert.strictEqual(status, "warning");
- assert.notStrictEqual(message.indexOf("update available"), -1);
- done();
- })
- .catch(function(err){
- done(new Error(err));
- });
- });
- it("throws an error because an invalid argument was passed", function(){
- assert.throws(function(){
- check_for_updates("troll");
- },
- function(err){
- if (err.type === "validation"){
- return true;
- }
- },
- "Unexpected error");
- });
- it("throws an error because a nonexisiting version was given", function(done){
- check_for_updates({version: "0.888888.10"})
- .then(function(){
- done(new Error("It didn't throw the error!"));
- })
- .catch(function(err){
- if (err.statusCode === 404){
- done();
- }
- else {
- done(new Error(err));
- }
- });
- });
-});
diff --git a/tests/util/assert-error-type.js b/tests/util/assert-error-type.js
index aa987020..6c3f5976 100644
--- a/tests/util/assert-error-type.js
+++ b/tests/util/assert-error-type.js
@@ -1,15 +1,16 @@
"use strict";
function assert_error_type (promise, error_type, done) {
promise.then(function(){
done(new Error("But it didn't throw any error at all!"));
}).catch(function(error){
+ console.log(error);
if (error.type === error_type){
done();
} else {
console.error(error);
done(new Error(`But it threw an error of wrong type: should be: '${error_type}', was: '${error.type}'`));
}
});
}
module.exports = assert_error_type;
diff --git a/tests/util/test-is-proper-value.js b/tests/util/test-is-proper-value.js
index bd2e4ceb..42cb55c2 100644
--- a/tests/util/test-is-proper-value.js
+++ b/tests/util/test-is-proper-value.js
@@ -1,39 +1,45 @@
"use strict";
const locreq = require("locreq")(__dirname);
const assert_no_error = locreq("tests/util/assert-no-error.js");
const assert_error = locreq("tests/util/assert-error.js");
const Context = locreq("lib/context.js");
module.exports = function(options){
const field_type = options.field_type;
const should_accept = options.should_accept;
const should_reject = options.should_reject;
describe(".is_proper_value", function(){
for(let i in should_accept){
const _case = should_accept[i];
it(`accepts ${_case[0]}: ${_case[1]}`, function(done){
+ let params;
+ if(!_case[2] && _case.length>=3){
+ params = _case[2];
+ }else{
+ params = _case[2] || {};
+ }
const result = field_type.is_proper_value(
new Context(),
- _case[2] || {}, // params
+ params,
_case[1], // new_value
_case[3] // old_value
);
assert_no_error(result, done);
});
}
for(let i in should_reject){
const _case = should_reject[i];
it(`rejects ${_case[0]}: ${_case[1]}`, function(done){
const result = field_type.is_proper_value(
new Context(),
_case[2] || {}, // params
_case[1], // new_value
_case[3] // old_value
);
assert_error(result, done);
});
}
});
}

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
1230155
Default Alt Text
(217 KB)

Event Timeline