Page MenuHomeSealhub

No OneTemporary

Authored By
Unknown
Size
432 KB
Referenced Files
None
Subscribers
None
This file is larger than 256 KB, so syntax highlighting was skipped.
diff --git a/.eslintrc.json b/.eslintrc.json
new file mode 100644
index 00000000..6fc396be
--- /dev/null
+++ b/.eslintrc.json
@@ -0,0 +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-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/.gitignore b/.gitignore
index e4e96d0b..13f3dc14 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,15 +1,17 @@
*~
*.sublime-workspace
npm-debug.log
sealious.sublime-workspace
node_modules
./node_modules/
./node_modules
./node_modules/*
node_modules/*
coverage/*
coverage.html
db
db/*
lib-cov/*
-coverage.html
\ No newline at end of file
+coverage.html
+\#*
+.\#*
diff --git a/.jscsrc b/.jscsrc
deleted file mode 100644
index 2d0d7625..00000000
--- a/.jscsrc
+++ /dev/null
@@ -1,39 +0,0 @@
-{
- "validateIndentation": "\t",
- "requireSpaceAfterBinaryOperators": true,
- "requireSpaceBeforeBinaryOperators": true,
- "disallowSpacesInAnonymousFunctionExpression": {
- "beforeOpeningRoundBrace": true,
- "beforeOpeningCurlyBrace": true
- },
- "disallowNewlineBeforeBlockStatements" : true,
- "requireSpacesInNamedFunctionExpression": {
- "beforeOpeningRoundBrace": true,
- "beforeOpeningCurlyBrace": true
- },
- "disallowSpacesInCallExpression": true,
- "requireSpacesInFunctionDeclaration": {
- "beforeOpeningRoundBrace": true,
- "beforeOpeningCurlyBrace": true
- },
- "requireSpacesInForStatement": true,
- "requireSpaceBeforeKeywords": [
- "else",
- "while",
- "catch"
- ],
- "requireSpaceAfterKeywords": [
- "do",
- "for",
- "if",
- "else",
- "switch",
- "case",
- "try",
- "catch",
- "while",
- "with",
- "return",
- "typeof"
- ]
-}
diff --git a/.jshintrc b/.jshintrc
deleted file mode 100644
index 24a95534..00000000
--- a/.jshintrc
+++ /dev/null
@@ -1,75 +0,0 @@
-// NOTE: I added the .js extension to this gist so it would have syntax highlighting. This file should have NO file extension
-
-{
-
- // Predefined globals whom JSHint will ignore.
- "browser" : true, // Standard browser globals e.g. `window`, `document`.
-
- "node" : true,
- "rhino" : false,
- "couch" : false,
- "wsh" : false, // Windows Scripting Host.
-
-
- "predef" : [ // Custom globals.
- //"exampleVar",
- //"anotherCoolGlobal",
- //"iLoveDouglas"
- ],
-
-
- // Development.
- "debug" : false, // Allow debugger statements e.g. browser breakpoints.
- "devel" : true, // Allow developments statements e.g. `console.log();`.
-
-
- // ECMAScript 5.
- "strict" : false, // Require `use strict` pragma in every file.
- "globalstrict" : true, // Allow global "use strict" (also enables 'strict').
-
- // ECMAScript 6
- "esnext" : true,
-
-
-
-
- // The Good Parts.
- "asi" : true, // Tolerate Automatic Semicolon Insertion (no semicolons).
- "laxbreak" : false, // Tolerate unsafe line breaks e.g. `return [\n] x` without semicolons.
- "bitwise" : true, // Prohibit bitwise operators (&, |, ^, etc.).
- "boss" : false, // Tolerate assignments inside if, for & while. Usually conditions & loops are for comparison, not assignments.
- "curly" : true, // Require {} for every new block or scope.
- "eqeqeq" : true, // Require triple equals i.e. `===`.
- "eqnull" : false, // Tolerate use of `== null`.
- "evil" : false, // Tolerate use of `eval`.
- "expr" : false, // Tolerate `ExpressionStatement` as Programs.
- "forin" : false, // Tolerate `for in` loops without `hasOwnPrototype`.
- "immed" : true, // Require immediate invocations to be wrapped in parens e.g. `( function(){}() );`
- "latedef" : true, // Prohipit variable use before definition.
- "loopfunc" : true, // Allow functions to be defined within loops.
- "noarg" : true, // Prohibit use of `arguments.caller` and `arguments.callee`.
- "regexp" : true, // Prohibit `.` and `[^...]` in regular expressions.
- "regexdash" : false, // Tolerate unescaped last dash i.e. `[-...]`.
- "scripturl" : true, // Tolerate script-targeted URLs.
- "shadow" : false, // Allows re-define variables later in code e.g. `var x=1; x=2;`.
- "supernew" : true, // Tolerate `new function () { ... };` and `new Object;`.
- "undef" : true, // Require all non-global variables be declared before they are used.
-
- "globals" : {
- "Promise" : true
- },
-
-
- // Personal styling preferences.
- "newcap" : false, // Require capitalization of all constructor functions e.g. `new F()`.
- "noempty" : true, // Prohibit use of empty blocks.
- "nonew" : true, // Prohibit use of constructors for side-effects.
- "nomen" : true, // Prohibit use of initial or trailing underbars in names.
- "onevar" : true, // Allow only one `var` statement per function.
- "plusplus" : false, // Prohibit use of `++` & `--`.
- "sub" : true, // Tolerate all forms of subscript notation besides dot notation e.g. `dict['key']` instead of `dict.key`.
- "trailing" : true, // Prohibit trailing whitespaces.
- "white" : false, // Check against strict whitespace and indentation rules.
- "indent" : 4, // Specify indentation spacing
- "mocha" : true
-}
\ No newline at end of file
diff --git a/.npmignore b/.npmignore
new file mode 100644
index 00000000..20b3b2b0
--- /dev/null
+++ b/.npmignore
@@ -0,0 +1,4 @@
+tests/
+docs/
+dev-setup.sh
+.eslintrc.json
diff --git a/.travis.yml b/.travis.yml
index 7eddce1b..046ddf2b 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,18 +1,36 @@
language: node_js
sudo: false
node_js:
-- '4.0.0'
-script: npm install && npm test
+- '4.4.7'
+script:
+- npm test
+- cd ../integration-tests
+- npm run integration-tests
+- cd ../sealious
+cache:
+ bundler: true
+ directories:
+ - node_modules
+install:
+- npm install
+- npm link .
+- npm link sealious
+- cd ../
+- git clone https://github.com/sealcode/sealious-integration-tests.git integration-tests
+- cd integration-tests
+- npm install
+- npm link sealious
+- cd ../sealious
after_success:
- npm run coveralls
after_deploy:
- npm dist-tag add sealious@`npm view sealious version` next
deploy:
provider: npm
email: kontakt@jakub-orlik.pl
api_key:
secure: jRcAYLwKjkAlM7Im2vZsYiGS/4EAaVhs9XD3toL4Hlt+9CopRhydyKJtOBxgylfe+XBEhFzjRhfqZNjIS5dgm9f9YeCAkmuPNlrYDDYRwRoGEFvvtUVHy06tn6mRv1N7prdH9cblicwY94iu0C7Rbv3XUGQPi506cdj5H4qjR9k=
on:
tags: true
repo: Sealious/sealious
branch: next
diff --git a/docs/reference.md b/docs/reference.md
index 6ff45f76..e302b26b 100644
--- a/docs/reference.md
+++ b/docs/reference.md
@@ -1,555 +1,61 @@
-# Reference
+# Sealious reference
-## Chip Types
+## SubjectPath
-### Access Strategy
+Represents a path in Subject graph. May or may not lead to an existing subject.
-Access strategies are functions that take a context as an argument and based on it either allow or deny access to certain resources or operations.
+### API
-#### Simple access strategy example:
+#### Constructor
-```js
-var Public = new Sealious.ChipTypes.AccessStrategy({
- name: "public",
- checker_function: function(context){
- return true;
- }
-});
-```
-
-This access strategy accepts any context.
-
-#### AccessStrategy: Constructor
-
-The `AccessStrategy` constructor takes one argument, which is an object with attributes:
-
- * `name` - string, **required**. The name of the access strategy - it has to be a string unique amongst any other access strategies in your application.
- * `checker_function` - function, **required**. It's a function that takes a context instance as an argument and implements the logic of the access strategy. Its return values can be:
- - `boolean` - `true` for granting the access and `false` for denying.
- - a `Promise` - that resolves when the access is granted and rejects otherwise. Use promises only when the decision depends on a result of an asynchronous function.
- * `item_sensitive` - boolean, defaults to `false`. If set to `true`, the `checker_function` is provided with a second argument, which contains an object representing the resource being requested.
-
-#### A more advanced example
-
-```js
-var _is_number = /^[0-9]/;
-
-new Sealious.ChipTypes.AccessStrategy({
- name: "id_starts_with_digit",
- checker_function: function(context, item){
- return new Promise(function(resolve, reject){
- if(_is_number.test(item.id)){
- resolve("id ok!");
- }else{
- reject("bad id");
- }
- });
- },
- item_sensitive: true,
-});
-```
-
-It's a slightly more complex access strategy, that allows access only if given resource's id starts with a digit. Note that it was not necessary to use a Promise in the above `checker_function`, but it was included for example's sake.
-
-TODO: example of a checker_function that uses contexts.
-
-TODO: example of how ResourceTypes use access strategies.
-
-### Channel
-
-A channel's responsibility is to take any input it wants to (keyboard, http request, open socket, anything) and translate it to Sealious resource method calls.
-
-Considering it's structure, it's the most flexible of all chip types.
-
-You don't need a channel to create an application in Sealious, as Sealious gives you a programmatic API for CRUD operations on all of the resources (see ResourceManager), though channels are good for abstracting out the workings of an external API (such as REST, SMTP, XMPP etc.) and turning it into a reusable plugin.
-
-The only method that Sealious will invoke on a channel is the optional `start` method, called on `Sealious.start()`.
-
-#### Existing channels
-
-Some noteworthy plugins that contain useful channels are:
-
-* [sealious-www-server](https://github.com/Sealious/sealious-www-server) - it can also automatically generate high-quality REST API.
-
-#### Channel: Constructor
-
-```js
-var Sealious = require("sealious");
-var CliChannel = new Sealious.ChipTypes.Channel("cli");
-```
-
-The constructor takes only one argument, which is a string that represents the channel's name and has to be unique amongst all other channels.
-
-The constructor returns an object (which has a Chip as its prototype). This object can be extended with any desired methods.
-
-#### Simple Channel example: command-line-interface
-
-We're going to create a simple channel, that reads from standard input and listens for a simple command:
-
-> `list [resource_type_name]` - lists all resources of given type
-
-We'll be using the `readline` module, which is built-in into node.
-
-Consider following code:
-
-```js
-var Sealious = require("sealious");
-var readline = require("readline");
-
-var CliChannel = new Sealious.ChipTypes.Channel("cli");
-
-CliChannel.start = function(){
- console.log("Welcome to Sealious CLI Channel. Your wish is my command.")
- console.log("Please enter your wish:");
- var rl = readline.createInterface({
- input: process.stdin,
- });
-
- function process_line(line){
- var words = line.split(" ");
- switch(words[0]){
- case "list":
- var resource_type_name = words[1];
- var context = new Sealious.Context();
- Sealious.ResourceManager.list_by_type(context, resource_type_name)
- .then(function(list){
- console.log(list);
- })
- break;
- }
- }
-
- rl.on("line", process_line);
-}
-```
-
-The main functionality of the channel is contained within the line:
-
-```js
-Sealious.ResourceManager.list_by_type(context, resource_type_name)
-```
-
-`ResourceManager.list_by_type` is an asynchronous method that returns a Promise that resolves to an array of objects representing all of the resources of a given type that are accessible in presence of a given `context`. We're using a simple, empty context, that can be thought of as representing an unauthorized user. You can read more about contexts [here](# context)
-
-### Datastore
-
-Datastores are chips responsible for all the data storage for your application. Currently Sealious supports only one active datastore at a time, but it's subject to change in future versions.
-
-#### Datastore: Constructor
-
-```
-var my_datastore = new Sealious.ChipTypes.Datastore("my_datastore");
-```
-
-In above code snippet the `my_datastore` variable contains a Datastore object, that needs to be extended with methods which signatures are described below.
-
-IMPORTANT! All these methods need to return a promise that resolves on success.
-
-* `find` - Retrieves documents from datastore. Its promise has to resolve with an array of documents (objects). A function with signature
-
- ```
- find : function(collection_name: String, query: Object, options: Object, output_options: Object) => Object
- ```
-
- where:
-
- * `collection_name` (string) - the name of the desired collection.
-
- * `query` (object) - an object containing db-query in [MongoDB query syntax](http://docs.mongodb.org/manual/tutorial/query-documents/)
-
- * `options` - optional argument. In MongoDB datastore it is passed as `projection` argument to `find` method. Currently no core Sealious code uses that parameter
-
- * `output_options` (object) - allows to further filter or sort the query result. It can contain the following properties:
- * `sort` (object) - uses [MongoDB Sort syntax](http://docs.mongodb.org/manual/reference/method/cursor.sort/). Allows to sort the query results using any amount of attributes (fields);
- * `skip` (number) - how many documents from the beginning to omit (analogous to the first argument in SQL's "LIMIT" statement)
- * `amount` (number) - how many documents to return at most (analogous to to the second argument in SQL's "LIMIT" statement)
-
-* `insert` - Inserts a document to a datastore. **Resolves with the inserted document.** A function with signature
+* `new Sealious.SubjectPath(path: String)`
+ * `path: String`: a dot-delimeted string representing a sequence of edge labels that lead to the desired subject
+ Example:
+ ```js
+ var path = new Sealious.SubjectPath("resources.users.82fc0dc12a");
```
- insert: function(collection_name: String, to_insert: Object, options: Object) => void
- ```
-
- where:
-
- * `collection_name` (string) - the name of the desired collection
- * `to_insert` (object) - an object containing key-value pairs describing what to insert
- * `options` (object) - currently not used
-
-* `update` - Updates a document in datastore. A function with signature
-
- ```
- update: function(collection_name: String, query: Object, new_value: Object) => void
- ```
-
- where:
-
- * `collection_name` (string) - the name of the desired collection
- * `query` (object) - datastore query, which defines which document to update. Uses [MongoDB find query syntax](http://docs.mongodb.org/manual/reference/method/db.collection.find/)
- * `new_value` (object) - what changes to apply to the document. Uses [MongoDB update syntax](http://docs.mongodb.org/manual/reference/method/db.collection.update/# example-update-specific-fields)
-
-* `remove` - removes a specified document from the datastore. A function with signature
-
- ```
- remove : function(collection_name: String, query: Object, just_one: Boolean) => void
- ```
-
- where:
- * `collection_name` (string) - the name of the desired collection
- * `query` (object) - datastore query, which defines which document to remove. Uses [MongoDB find query syntax](http://docs.mongodb.org/manual/reference/method/db.collection.find/)
- * `just_one` (boolean) - if set to true, datastore has to remove only one element matching the `query`. It might need to be removed in future versions.
-
-#### Built-in datastore methods
-
-As all [chips](https://github.com/Sealious/Sealious#structure), initiated datastores have two default methods:
-
- * `start` - takes no arguments and is meant to be called automatically by Sealious. Usually of no concern for a developer.
- * `test` - perfoms unit tests on the datastore.
-
-#### Multiple Datastores
-
-Because of the fact that Sealious currently supports only one active datastore at a time, you have the ability to manually select which one it is. You can do so by invoking
-```js
-Sealious.ConfigManager.set_config("datastore_chip_name", "my_datastore")
-```
-before calling `Sealious.start()`;
-
-There's no need to specify which datastore to use if there's only one datastore available.
-#### Example Datastore
+* `new Sealious.SubjectPath(path: Array[String])`
+ * `path: Array[String]`: a list of edge labels that lead to the desired subject
-We've created a simple file-based datastore for demonstratory purposes:
+ Example:
+ ```js
+ var path = new Sealious.SubjectPath(["resources", "users", "82fc0dc12a"]);
+ ```
-> [Sealious-datastore-file](https://github.com/Sealious/sealious-datastore-file)
+* `new Sealious.SubjectPath(path: SubjectPath)`
+ * `path: SubjectPath`: an instance of SubjectPath representing the desired subject
-It's not the most efficient one (for any real-life applications the currently default datastore-mongo is recommended), but it highlights all the necessary inner workings of a Datastore, so it makes a good starting point if you want to create your own Datastore.
+ This constructor will create a copy of the SubjectPath passed as an argument.
-### Field-type
+ Example:
+ ```js
+ var path = new Sealious.SubjectPath(["resources", "users", "82fc0dc12a"]);
+ var path_copy = new Sealious.SubjectPath(path);
+ ```
-Each "field" in a [ResourceType](#resource-type) must be assigned a field-*type*.
-Field-types describe which values can and which cannot be assigned to a field.
-Field-type's behaviour can be adjusted using field-type parameters.
+#### Methods
-A field-type can accept or reject a value, with appropriate error message.
+* `subject_path.clone() => SubjectPath`
-It's a field-type's responsibility to describe how to store it's values in a datatore.
+ Returns a copy of the path
-Some field-types that come bundled with Sealious:
- * text - for storing strings of chars.
- * email - like text, but accepts only valid email addresses as values
- * int - for storing integer numbers
- * float - for storing real numbers
- * file - for storing managed user-submitted files
- * reference - for storing a reference to a resource. This field-type can be adjusted to only accept references to certain resource types.
-
-You can find out more about built-in field-types and other chips in the "Chips that come bundled with Sealious" section.
-
-#### Creating a field-type
-
-Field types are a little bit different from other chips, as they are to be instantiated multiple times for different fields in multiple resource types.
-
-##### A simple Field-Type example
-
-Let's review a simple code sample:
-
-```js
-var Sealious = require("sealious");
-var Promise = require("bluebird");
-var Color = require("color");
-
-var field_type_color = new Sealious.ChipTypes.FieldType({
- name: "color",
- get_description: function(context, params){
- return "Accepts colors, in various formats - rgb, hex, hsl, rgba, and html color name. Example correct values: `#ff0000`, `red`, `rgba(255, 0, 0, 1)`, `hsl(0, 100%, 50%)`."
- },
- is_proper_value: function(accept, reject, context, params, new_value){
- try{
- Color(new_value.toLowerCase());
- } catch(e){
- return reject("Value `" + new_va + "` could not be parsed as a color.");
- }
- accept();
- },
- encode: function(context, params, value_in_code){
- var color = Color(value_in_code);
- return Promise.resolve(color.hexString())
- }
-});
-```
-
-The above is a simple field-type that accepts color values in various notations (html color names, hex, rgba, hsl...). It will reject any value that does not name a color.
-
-This field-type uses the very useful [color](https://www.npmjs.com/package/color) package.
-
-What's important to note here is the `encode` method - it takes any value already validated by `is_proper_value` and converts it to hex - that way all the color values in the database are uniform and easily searchable.
-
-The `decode` method is not declared here, so the default one will be used - one that returns the value from the database unchanged. In this case `decode` will always return the color in hex format (because that's how the values are stored).
-
-#### Field-type methods and attributes
-
-##### The constructor
-To create a field-type, call the FieldType constructor function:
-
-```
-Sealious.ChipTypes.FieldType: (declaration: FieldTypeDeclaration)
-```
-
-Usage:
-
-```js
-new Sealiuos.ChipTypes.FieldType({
- //...
-})
-```
-
-##### FieldTypeDeclaration
-
-```
-type fieldTypeDeclaration: {
- get_description?: (
- context: Context,
- params: Object
- ) => String|FieldTypeDescription,
- is_proper_value?: (
- accept: ()=>void,
- reject: (error_message: String)=>void,
- context: Context,
- params: Object,
- new_value: Any,
- old_value: Any
- ) => void,
- encode?: (context: Context, params: Object, value_in_code: Any, old_value: Any),
- decode?: (context: Context, params: Object, value_in_database: Any)
-}
-```
-
-
-##### is_proper_value
-
-```
-is_proper_value: (
- accept: ()=>void,
- reject: (error_message: String)=>void,
- context: Context,
- params: Object,
- new_value: Any,
- old_value: Any
-) => void,
-```
-
-This method should check if the `new_value` variable contains a value that is correct for the field-type. If the value is correct, the method should call `accept`, otherwise it should call `reject`, passing the error message.
-
-Specifying this method is **optional**. If this method is not defined in a field-type, a default one is used - one that accepts any value.
-
-A simple example of `is_proper_value` method:
-
-```js
-new Sealious.ChipTypes.FieldTypes({
- name: "only_event_numbers",
- is_proper_value: function(accept, reject, context, params, new_value){
- if(new_value%2==0){
- accept();
- }else{
- reject("Only even numbers are accepted.");
- }
- }
-})
-```
-
-This method wil be given the following arguments:
- * `accept: ()=>void` - call it if the `new_value` is a correct value
- * `reject: (error_message: String)=>void` - call it if the `new_value` is not a correct value.
- * `context: Context` - a Context object representing the context in which the value was submitted. The field-type may or may not take context into consideration.
- * `params: Object` - an object representing the [params passed to the field declaration](#field-type-parameters) referencing this field type
- * `new_value: Any` - Represents the value to be checked. Usually directly represents user input.
- * `old_value: Any` - represents the value previously residing in in a field that this field-type is assigned to. This argument can be used e. g. for creating a field type that accepts only values that are higher than the current value.
-
- **Important!** For performance reasons, this argument is automatically set to `undefined`, unless Sealious is specifically instructed to provide this field-type with previous values. See `old_value_sensitive` section below for more details
-
-##### encode
-
-```
-my_field_type.prototype.encode: (
- context: Context,
- params: Object,
- new_value: Any,
- old_value: Any
-) => Promise<Any>|Any
-```
-
-This method takes a field value (usually coming from user input) and encodes it in something that the datastore can understand. There's no set restrictions on how the encoding process works. What this method returns will be stored in the datastore and passed on to `decode` when reading the resource's contents.
-
-Specifying this method is **optional**. If this method is not defined in a field-type, a default one is used - one that returns `new_value` unchanged.
-
-It takes the following arguments:
- * `context: Context` - a Context object representing the context in which the value was submitted. The field-type may or may not take context into consideration.
- * `params: Object` - an object representing the [params passed to the field declaration](#field-type-parameters) referencing this field type
- * `new_value: Any` - can be of any type. Represents the value to be encoded. Usually directly represents user input.
- * `old_value: Any` - represents the value previously residing in in a field that this field-type is assigned to.
-
- **Important!** For performance reasons, this argument is automatically set to `undefined`, unless Sealious is specifically instructed to provide this field-type with previous values. See `old_value_sensitive` section below for more details
-
-##### decode
-
-```
-my_field_type.prototype.decode: (
- context: Context,
- params: Object,
- value_in_datastore: Any
-) => Promise<Any>|Any
-```
-
-This method is used to transform a value stored in a datastore(encoded by calling the `encode` method of the field-type) into something more readable or user-friendly. It's return value is usually what the users of the API will see. It can be thought of as the reverse of `encode` function, but that doesn't have to be the case.
-
-In most cases the return value of this method should be the same as the value passed to the `encode` method for that particular field/value combination.
-
-Specifying this method is **optional**. If this method is not defined in a field-type, a default one is used - one that returns `value_in_datstore` unchanged.
-
-It takes the following arguments:
- * `context` - a `Context` object representing the context in which the value is read. The field-type may or may not take context into consideration.
- * `params: Object` - an object representing the [params passed to the field declaration](#field-type-parameters) referencing this field type
- * `value_in_datastore` - a raw value that the datastore returned. Encoded by calling the field-type's `encode` method.
-
-##### old_value_sensitive
-
-```
-old_value_sensitive_methods: Boolean|{
- is_proper_value: Boolean,
- encode: Boolean
-}
-```
-
-Set to `false` for each field-type by default, for performance reasons.
-
-When it's set to `true`, Sealious will provide the `is_proper_value` and `encode` methods with the current value of the requested/modified field by passing it as `old_value` argument.
-
-#### Field-type parameters
-
-Each field has to have a field-type assigned.
-Optionally, a field declaration can contain parameters that will be accessible from within the fiel-type methods.
-These parameters can affect which values for the field are considered correct, how the values are encoded, etc.
-
-##### Passing parameters to field-type instance
-
-Parameters are passed from the field declaration, like so:
-```js
-//a single field declaration in ResourceType constructor:
-{
- name: "article_content",
- type: "text",
- params: {
- strip_html: true
- }
-}
-```
-
-Note the `params` attribute.
-
-Text entered in the field described by the above snippet will have any html tags stripped on user submission.
-
-##### Accessing field-type parameters
-
-Parameters are accessible as `this.params` in every field-type method, like so:
-
-```js
-my_field_type.is_proper_value = function(context, new_value){
- if(this.params.max_length){
- if(new_value.length>this.params.max_length){
- return false;
- }
- }else{
- return true;
- }
-}
-```
-
-### Resource-type
-
-Every time a user interacts with a Sealious application, they interact with resources. A Resource in Sealious can be thought of as an equivalent of a row in a SQL database table. A Resource-type would be the columns for said table - a list of fields, each with its name and type.
-
-A Resource-type is construted based on a Resource-type description.
-
-#### Creating a resource-type
-
-Creating a resource-type is very straightforward - you only have to provide the constructor with a proper resource-type description.
-
-##### A simple resource-type example
-
-```js
-var Sealious = require("sealious");
-
-new Sealious.ChipTypes.ResourceType({
- name: "person",
- fields: [
- {name: "first-name", type: "text", required: true},
- {name: "age", type: "int"}
- ]
-})
-```
-
-There's not much to analyze here, except for the syntax of the resource-type description, which is discussed below.
-
-#### Resource-type description syntax
-
-Every resource type is described by a hashmap:
-
-```js
-{
- name: String,
- fields: Array<FieldDeclaration>,
- access_strategy?: AccessStrategyDescription
-}
-```
-
-* `name`, **required** - the name of the resource-type. It becomes the name of the [chip](https://github.com/Sealious/Sealious/blob/dev/README.md#structure) representing the resource type, as well. It has to be unique amongst all other resource-types.
-* `fields`, **required** - an array of field descriptions. You can read about field description syntax below.
-* `access_strategy`, optional. A hashmap or string compatible with access strategy description syntax, described below. **Defaults to `public`**.
-
-#### FieldDeclaration
-
-A field-type description is a hashmap, as well. It looks like this:
-
-```js
-{
- name: String,
- type: FieldTypeName,
- human_readable_name?: String,
- params?: Object
-}
-```
-
-* `name`, **required** - a string representing the machine-readable name for the field. Should be short. No spaces allowed. All lower-case letters, the `_` and `-` symbols are allowed.
-* `human_readable_name`, optional - a string representing a human-readable version of the field's name. No restrictions on what is and what is not allowed here. **When not specified, the value of 'name' attribute is used instead**.
-* `type`, **required** - a string representing a resource-type name that is already registred in your Sealious application.
-* `params`, optional - a hashmap of parameters that will be passed to the field-type. These parameters are also a part of the field's signature. **Defaults to `{}`.**
-
-#### Resource-type methods and attributes
-
-##### The constructor
-
-## Plugins
+* `subject_path.head() => String`
+
+ Returns the first element of the path
-Plugins are npm modules that can be required and used within a Sealious application. Usually a plugin just registers some new [chips](https://github.com/Sealious/Sealious/blob/dev/README.md#structure) in Sealious' ChipManager.
+* `subject_path.tail() => Array[String]`
+
+ Returns an array of path elements, without its first element
-### Creating a plugin
-In order for Sealious to recognize an npm module as a plugin, the plugin has to contain a `"sealious-plugin"` keyword in it's `package.json`.
+## Subjects
-Example `package.json` content:
+All user actions in Sealious should be translated to a certain action on a can certain subject. Subjects can be thought of as nodes in a directed graph. You can read more about them in the Sealious Handbook
-```json
-{
- "name": "sealious-cli-channel",
- "version": "0.1.0",
- "description": "",
- "main": "index.js",
- "keywords": [
- "sealious-plugin"
- ],
- /* other usual package.json fields here */
-}
-```
+Each subject is identified by a Subject Path
-### Installing an existing plugin
-In order for Sealious to detect a plugin, the plugin has to be installed in your application's `node_modules` directory and it has to be present in your application's `package.json`'s `dependencies` attribute. It's usually achievable by running `npm install [plugin-name]` in your application's directory.
+### Subject types
-## Chips that come bundled with Sealious
+There are 2 built-in subject types:
+
\ No newline at end of file
diff --git a/jsdoc.json b/jsdoc.json
deleted file mode 100644
index 510717a4..00000000
--- a/jsdoc.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "tags": {
- "allowUnknownTags": true
- },
- "source": {
- //"include": ["./bin/node_modules"],
- "exclude": [ "./bin/node_modules/.bin", "./bin/node_modules/Set", "./bin/node_modules/boom", "./bin/node_modules/glue", "./bin/node_modules/hapi", "./bin/node_modules/http", "./bin/node_modules/ip", "./bin/node_modules/mongodb", "./bin/node_modules/open", "./bin/node_modules/promise", "./bin/node_modules/query-string", "./bin/node_modules/request", "./bin/node_modules/simpleargs", "./bin/node_modules/socket.io", "./bin/node_modules/socket.io-client"],
- "includePattern": ".+\\.js(doc)?$",
- "excludePattern": "(^|\\/|\\\\)_"
- },
- "plugins": [],
- "templates": {
- "cleverLinks": false,
- "monospaceLinks": false
- }
-}
-
diff --git a/lib/action.js b/lib/action.js
new file mode 100644
index 00000000..7f331229
--- /dev/null
+++ b/lib/action.js
@@ -0,0 +1,26 @@
+"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){
+ 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);
+
+ return Promise.try(function(){
+ return RootSubject.get_subject(self.subject_path)
+ .then(function(subject){
+ return subject.perform_action.apply(subject, [context, self.action_name].concat(args));
+ });
+ });
+};
+
+
+
+module.exports = Action;
diff --git a/lib/base-chips/_base-chips.js b/lib/base-chips/_base-chips.js
index 1d77d2f4..98b3da25 100644
--- a/lib/base-chips/_base-chips.js
+++ b/lib/base-chips/_base-chips.js
@@ -1,26 +1,41 @@
-/*
-var fs = require("fs");
-var path = require("path");
-
-fs.readdirSync(__dirname).forEach(function(filename){
- if(filename[0]!="_"){
- require("./" + filename);
- }
-})
-
-*/
-require("./access_strategy.noone.js");
-require("./access_strategy.public.js");
-require("./access_strategy.just_owner.js");
-require("./field_type.date.js");
-require("./field_type.datetime.js");
-require("./field_type.boolean.js");
-require("./field_type.email.js");
-require("./field_type.int.js");
-require("./field_type.float.js");
-require("./field_type.text.js");
-require("./field_type.hashed-text.js")
-require("./field_type.color.js");
-require("./field_type.file.js");
-require("./field_type.reference.js");
-require("./resource_type.user.js");
\ No newline at end of file
+"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 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",
+];
+
+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);
+}
+
+
+require("./resource_type.user.js");
diff --git a/lib/base-chips/access-strategy-types/and.js b/lib/base-chips/access-strategy-types/and.js
new file mode 100644
index 00000000..abdd544e
--- /dev/null
+++ b/lib/base-chips/access-strategy-types/and.js
@@ -0,0 +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({
+ 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/base-chips/access-strategy-types/logged_in.js
new file mode 100644
index 00000000..33c64372
--- /dev/null
+++ b/lib/base-chips/access-strategy-types/logged_in.js
@@ -0,0 +1,13 @@
+"use strict";
+const Promise = require("bluebird");
+
+module.exports = {
+ name: "logged_in",
+ checker_function: function(context){
+ if (context.user_id){
+ return Promise.resolve();
+ } else {
+ return Promise.reject("Only logged-in users can perform this action.");
+ }
+ },
+};
diff --git a/lib/base-chips/access-strategy-types/noone.js b/lib/base-chips/access-strategy-types/noone.js
new file mode 100644
index 00000000..92e6816b
--- /dev/null
+++ b/lib/base-chips/access-strategy-types/noone.js
@@ -0,0 +1,10 @@
+"use strict";
+const Promise = require("bluebird");
+
+module.exports = {
+ name: "noone",
+ checker_function: function(){
+ return Promise.reject("Noone gets in!");
+ },
+ item_sensitive: false
+};
diff --git a/lib/base-chips/access-strategy-types/not.js b/lib/base-chips/access-strategy-types/not.js
new file mode 100644
index 00000000..6818fb24
--- /dev/null
+++ b/lib/base-chips/access-strategy-types/not.js
@@ -0,0 +1,27 @@
+"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({
+ 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/base-chips/access-strategy-types/or.js
new file mode 100644
index 00000000..db4d98ca
--- /dev/null
+++ b/lib/base-chips/access-strategy-types/or.js
@@ -0,0 +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({
+ 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/base-chips/access-strategy-types/owner.js
new file mode 100644
index 00000000..dd6e018f
--- /dev/null
+++ b/lib/base-chips/access-strategy-types/owner.js
@@ -0,0 +1,14 @@
+"use strict";
+const Promise = require("bluebird");
+
+module.exports = {
+ name: "owner",
+ checker_function: function(context, params, item){
+ if (context.user_id === item.created_context.user_id){
+ return Promise.resolve();
+ } else {
+ return Promise.reject("Only the owner of this resource can perform this operation on this item.");
+ }
+ },
+ item_sensitive: true
+};
diff --git a/lib/base-chips/access-strategy-types/public.js b/lib/base-chips/access-strategy-types/public.js
new file mode 100644
index 00000000..993196bb
--- /dev/null
+++ b/lib/base-chips/access-strategy-types/public.js
@@ -0,0 +1,10 @@
+"use strict";
+const Promise = require("bluebird");
+
+module.exports = {
+ name: "public",
+ checker_function: function(){
+ return Promise.resolve("Everybody is a winner!");
+ },
+ item_sensitive: false
+};
diff --git a/lib/base-chips/access-strategy-types/super.js b/lib/base-chips/access-strategy-types/super.js
new file mode 100644
index 00000000..87290875
--- /dev/null
+++ b/lib/base-chips/access-strategy-types/super.js
@@ -0,0 +1,18 @@
+"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({
+ 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/base-chips/access-strategy-types/themselves.js
new file mode 100644
index 00000000..abee145b
--- /dev/null
+++ b/lib/base-chips/access-strategy-types/themselves.js
@@ -0,0 +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({
+ 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/base-chips/access_strategy.just_owner.js b/lib/base-chips/access_strategy.just_owner.js
deleted file mode 100644
index d3360267..00000000
--- a/lib/base-chips/access_strategy.just_owner.js
+++ /dev/null
@@ -1,14 +0,0 @@
-var Sealious = require("sealious");
-var Promise = require("bluebird");
-
-var JustOwner = new Sealious.ChipTypes.AccessStrategy({
- name: "just_owner",
- checker_function: function(context, item){
- if (context.get("user_id") === item.created_context.user_id) {
- return Promise.resolve();
- } else {
- return Promise.reject("Only the owner of this resource can perform this operation on this item.");
- }
- },
- item_sensitive: true
-});
\ No newline at end of file
diff --git a/lib/base-chips/access_strategy.noone.js b/lib/base-chips/access_strategy.noone.js
deleted file mode 100644
index 9825beb1..00000000
--- a/lib/base-chips/access_strategy.noone.js
+++ /dev/null
@@ -1,10 +0,0 @@
-var Sealious = require("sealious");
-var Promise = require("bluebird");
-
-var Public = new Sealious.ChipTypes.AccessStrategy({
- name: "noone",
- checker_function: function(context){
- return Promise.reject("Noone gets in!");
- },
- item_sensitive: false,
-});
\ No newline at end of file
diff --git a/lib/base-chips/access_strategy.public.js b/lib/base-chips/access_strategy.public.js
deleted file mode 100644
index 4c745fd5..00000000
--- a/lib/base-chips/access_strategy.public.js
+++ /dev/null
@@ -1,10 +0,0 @@
-var Sealious = require("sealious");
-var Promise = require("bluebird");
-
-var Public = new Sealious.ChipTypes.AccessStrategy({
- name: "public",
- checker_function: function(context){
- return Promise.resolve("Everybody is a winner!");
- },
- item_sensitive: false,
-});
\ No newline at end of file
diff --git a/lib/base-chips/field-types/boolean.js b/lib/base-chips/field-types/boolean.js
new file mode 100644
index 00000000..9d246489
--- /dev/null
+++ b/lib/base-chips/field-types/boolean.js
@@ -0,0 +1,40 @@
+"use strict";
+module.exports = {
+ name: "boolean",
+ get_description: function(){
+ return "Boolean value. True or false. Can be a string: \"true\" or \"false\".";
+ },
+ is_proper_value: function(accept, reject, context, params, value){
+ if (typeof value === "boolean"){
+ accept();
+ } else if (value.toString() === "1" || value.toString() === "0"){
+ accept();
+ } else if (typeof value === "string" && (value.toLowerCase() === "true" || value.toLowerCase() === "false")){
+ accept();
+ } else {
+ reject(`Value '${value}' is not boolean format.`);
+ }
+ },
+ encode: function(context, params, value){
+ if (typeof value === "boolean"){
+ return value;
+ } else if (value.toString() === "1"){
+ return true;
+ } else if (value.toString() === "0"){
+ return false;
+ } else if (typeof value === "string"){
+ if (value.toLowerCase() === "true"){
+ return true;
+ } else if (value.toLowerCase() === "false"){
+ return false;
+ }
+ }
+ },
+ filter_to_query: function(context, params, filter){
+ if (filter === "" || filter === null){
+ return {$in: [true, false]};
+ } else {
+ return this.encode(context, params, filter);
+ }
+ },
+};
diff --git a/lib/base-chips/field_type.color.js b/lib/base-chips/field-types/color.js
similarity index 52%
rename from lib/base-chips/field_type.color.js
rename to lib/base-chips/field-types/color.js
index 253aad64..b4a7b57f 100644
--- a/lib/base-chips/field_type.color.js
+++ b/lib/base-chips/field-types/color.js
@@ -1,23 +1,22 @@
-var Sealious = require("sealious");
-var Promise = require("bluebird");
-var Color = require("color");
+"use strict";
+const Color = require("color");
-var field_type_color = new Sealious.ChipTypes.FieldType({
+module.exports = {
name: "color",
is_proper_value: function(accept, reject, context, params, new_value){
try {
if (typeof (new_value) === "string"){
Color(new_value.toLowerCase());
} else {
Color(new_value);
}
+ accept();
} catch (e){
- reject("Value `" + new_value + "` could not be parsed as a color.");
+ reject(`Value '${new_value}' could not be parsed as a color.`);
}
- accept();
},
encode: function(context, params, value_in_code){
- var color = Color(value_in_code);
+ const color = Color(value_in_code);
return color.hexString();
- }
-});
+ },
+};
diff --git a/lib/base-chips/field-types/context.js b/lib/base-chips/field-types/context.js
new file mode 100644
index 00000000..3266f94e
--- /dev/null
+++ b/lib/base-chips/field-types/context.js
@@ -0,0 +1,14 @@
+"use strict";
+const locreq = require("locreq")(__dirname);
+const Context = locreq("lib/context.js");
+
+module.exports ={
+ name: "context",
+ is_proper_value: function(accept, reject, context, params, value){
+ if (value instanceof Context){
+ accept();
+ } else {
+ reject("Provided value is not an instance of Sealious.Context");
+ }
+ },
+};
diff --git a/lib/base-chips/field-types/date.js b/lib/base-chips/field-types/date.js
new file mode 100644
index 00000000..808b06fe
--- /dev/null
+++ b/lib/base-chips/field-types/date.js
@@ -0,0 +1,18 @@
+"use strict";
+module.exports = {
+ name: "date",
+ get_description: function(){
+ return "Date standard ISO 8601 (YYYY-MM-DD)";
+ },
+ is_proper_value: function(accept, reject, context, params, date){
+ const date_in_string = date.toString();
+
+ const regex = /^([0-9]{4})-(0?[1-9]|1[0-2])-([0-2]?[0-9]|30|31)$/; // granulation_per_day
+
+ if (regex.test(date_in_string) === false || isNaN(Date.parse(date_in_string))){
+ reject(`Value "${date}" is not date calendar format. Expected value standard IS0 8601 (YYYY-MM-DD)`);
+ } else {
+ accept();
+ }
+ },
+};
diff --git a/lib/base-chips/field-types/datetime.js b/lib/base-chips/field-types/datetime.js
new file mode 100644
index 00000000..53150913
--- /dev/null
+++ b/lib/base-chips/field-types/datetime.js
@@ -0,0 +1,18 @@
+"use strict";
+module.exports = {
+ name: "datetime",
+ get_description: function(){
+ return "Timestamp - amount of miliseconds since epoch.";
+ },
+ is_proper_value: function(accept, reject, context, params, datetime){
+ if (isNaN(datetime) === true || datetime % 1 !== 0){
+ reject(`Value '${datetime}' is not datetime format. Only timestamps are accepted.`);
+ } else {
+ accept();
+ }
+ },
+ encode: function(context, params, value_in_code){
+ const parsed_datetime = parseInt(value_in_code);
+ return parsed_datetime;
+ },
+};
diff --git a/lib/base-chips/field-types/email.js b/lib/base-chips/field-types/email.js
new file mode 100644
index 00000000..be008485
--- /dev/null
+++ b/lib/base-chips/field-types/email.js
@@ -0,0 +1,18 @@
+"use strict";
+module.exports = {
+ name: "email",
+ get_description: function(){
+ return "Email address, like something@something.sth";
+ },
+ is_proper_value: function(accept, reject, context, params, value){
+ const address = value;
+
+ const regex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
+
+ if (!regex.test(address)){
+ reject(`${address} is a not valid e-mail address.`);
+ } else {
+ accept();
+ }
+ },
+};
diff --git a/lib/base-chips/field-types/file.js b/lib/base-chips/field-types/file.js
new file mode 100644
index 00000000..74732e8a
--- /dev/null
+++ b/lib/base-chips/field-types/file.js
@@ -0,0 +1,68 @@
+"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");
+
+module.exports = {
+ name: "file",
+ handles_large_data: true,
+ is_proper_value: function(accept, reject, context, params, value){
+ if (value === undefined){
+ return undefined;
+ }
+ if (value === null
+ || value === ""
+ || (value instanceof File)
+ || (value.filename !== undefined && value.data instanceof Buffer)
+ ){
+ accept();
+ } else {
+ let type;
+ if (value instanceof Array){
+ type = "<Array>. If you want to upload multiple files, use array field types.";
+ } else {
+ type = typeof data;
+ }
+ reject(`Wrong file data format. Should be Sealious.File, but received ${type}`);
+ }
+ },
+ encode: function(context, params, value_in_code){
+ // it doesn't check what the value_in_code really is
+ 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/float.js b/lib/base-chips/field-types/float.js
new file mode 100644
index 00000000..aa05e576
--- /dev/null
+++ b/lib/base-chips/field-types/float.js
@@ -0,0 +1,19 @@
+"use strict";
+module.exports = {
+ name: "float",
+ get_description: function(){
+ return "Float number.";
+ },
+ is_proper_value: function(accept, reject, context, params, number){
+ const test = parseFloat(number);
+ if (test === null || isNaN(test) || isNaN(number) === true){
+ reject(`Value '${number}' is not a float number format.`);
+ } else {
+ accept();
+ }
+ },
+ encode: function(context, params, value_in_code){
+ const parsed_float = parseFloat(value_in_code);
+ return parsed_float;
+ },
+};
diff --git a/lib/base-chips/field-types/hashed-text.js b/lib/base-chips/field-types/hashed-text.js
new file mode 100644
index 00000000..08607d02
--- /dev/null
+++ b/lib/base-chips/field-types/hashed-text.js
@@ -0,0 +1,78 @@
+"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(accept, reject, context, params, new_value){
+ const pattern_array = [];
+ if (typeof params === "object"){
+ 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){
+ accept();
+ }
+ else {
+ const digits = params.digits || "0";
+ const capitals = params.capitals || "0";
+ reject(`It didn't fulfill the requirements: required digits - ${digits} , required capitals ${capitals}`);
+ }
+ }
+ else {
+ accept();
+ }
+ },
+ 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/int.js b/lib/base-chips/field-types/int.js
new file mode 100644
index 00000000..ebe9431c
--- /dev/null
+++ b/lib/base-chips/field-types/int.js
@@ -0,0 +1,18 @@
+"use strict";
+module.exports = {
+ name: "int",
+ get_description: function(){
+ return "An integer number.";
+ },
+ is_proper_value: function(accept, reject, context, params, new_value){
+ if (new_value === null || isNaN(new_value) === true || new_value % 1 !== 0){
+ reject(`Value '${new_value}' is not a int number format.`);
+ } else {
+ accept();
+ }
+ },
+ encode: function(context, params, value_in_code){
+ const parsed_int = parseInt(value_in_code);
+ return parsed_int;
+ },
+};
diff --git a/lib/base-chips/field-types/single_reference.js b/lib/base-chips/field-types/single_reference.js
new file mode 100644
index 00000000..00f017ae
--- /dev/null
+++ b/lib/base-chips/field-types/single_reference.js
@@ -0,0 +1,60 @@
+"use strict";
+const locreq = require("locreq")(__dirname);
+const ResourceType = locreq("lib/chip-types/resource-type.js");
+const Action = locreq("lib/action.js");
+
+module.exports = {
+ name: "single_reference",
+ is_proper_value: function(accept, reject, context, params, new_value){
+ const resource_type = new ResourceType(params.resource_type);
+ 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(["resources", resource_type.name, resource_id], "show");
+ action.perform(context).then(accept)
+ .catch({type: "not_found"}, (error) => reject(error));
+ },
+ 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 resource_type = new ResourceType(params.resource_type);
+ const resource_id = decoded_value;
+ const action = new Action(["resources", resource_type.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 resource_type = new ResourceType(params.resource_type);
+ return context.run_action(["resources", resource_type.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/base-chips/field-types/text.js
new file mode 100644
index 00000000..5d1bbfce
--- /dev/null
+++ b/lib/base-chips/field-types/text.js
@@ -0,0 +1,59 @@
+"use strict";
+const Promise = require("bluebird");
+const escape = require("escape-html");
+
+module.exports = {
+ name: "text",
+ full_text_search_enabled: function(params){
+ if (params && params.include_in_search){
+ return true;
+ } else if (params && params.max_length > 200){
+ return true;
+ } else {
+ return false;
+ }
+ },
+ get_description: function(context, params){
+ return `Text with maximum length ${params.max_length}`;
+ },
+ is_proper_value: function(accept, reject, context, params, new_value){
+ if (params === undefined || (params.max_length === undefined && params.min_length === undefined)){
+ accept();
+ }
+ else if (params.max_length !== undefined){
+ if (new_value.length <= params.max_length){
+ accept();
+ } else {
+ reject(`Text '${new_value}' has exceeded max length of ${params.max_length} chars`);
+ }
+ }
+ else if (params.min_length !== undefined){
+ if (new_value.length >= params.min_length){
+ accept();
+ } else {
+ reject(`Text '${new_value}' is too short, minimum length is ${params.max_length} chars.`);
+ }
+ }
+ else if (params.min_length !== undefined && params.max_length !== undefined){
+ if (new_value.length >= params.min_length && new_value.length <= params.max_length){
+ accept();
+ } else {
+ reject(`Text '${new_value}' length should be between ${params.min_length} and ${params.max_length}.`);
+ }
+ }
+ },
+ encode: function(context, params, value_in_code){
+ if (typeof value_in_code === "string" && value_in_code !== null){
+ const result = {
+ "original": value_in_code,
+ "safe": escape(value_in_code),
+ valueOf: function(){
+ return value_in_code;
+ },
+ };
+ return Promise.resolve(result);
+ } else {
+ return Promise.resolve(null);
+ }
+ },
+};
diff --git a/lib/base-chips/field-types/username.js b/lib/base-chips/field-types/username.js
new file mode 100644
index 00000000..f31a213d
--- /dev/null
+++ b/lib/base-chips/field-types/username.js
@@ -0,0 +1,26 @@
+"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(accept, reject, context, params, new_value, old_value){
+ if (old_value === new_value){
+ accept();
+ } else if (me_synonyms.indexOf(new_value) !== -1){
+ 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){
+ accept();
+ } else {
+ reject("Username already taken");
+ }
+ });
+ }
+ },
+};
diff --git a/lib/base-chips/field_type.boolean.js b/lib/base-chips/field_type.boolean.js
deleted file mode 100644
index 0c4d3d6b..00000000
--- a/lib/base-chips/field_type.boolean.js
+++ /dev/null
@@ -1,35 +0,0 @@
-var Sealious = require("sealious");
-var Promise = require("bluebird");
-
-var field_type_boolean = new Sealious.ChipTypes.FieldType({
- name: "boolean",
- get_description: function(context, params){
- return "Boolean value. True or false. Can be a string: \"true\" or \"false\".";
- },
- is_proper_value: function(accept, reject, context, params, value){
- if (typeof value === "boolean") {
- accept();
- } else if (value.toString() === "1" || value.toString() === "0") {
- accept();
- } else if (typeof value === "string" && (value.toLowerCase() === "true" || value.toLowerCase() === "false")) {
- accept();
- } else {
- reject(`Value '${value}' is not boolean format.`);
- }
- },
- encode: function(context, params, value){
- if (typeof value === "boolean") {
- return value;
- } else if (value.toString() === "1") {
- return true;
- } else if (value.toString() === "0") {
- return false;
- } else if (typeof value === "string") {
- if (value.toLowerCase() === "true") {
- return true;
- } else if (value.toLowerCase() === "false") {
- return false
- }
- }
- }
-});
diff --git a/lib/base-chips/field_type.date.js b/lib/base-chips/field_type.date.js
deleted file mode 100644
index 5cfacb6c..00000000
--- a/lib/base-chips/field_type.date.js
+++ /dev/null
@@ -1,20 +0,0 @@
-var Sealious = require("sealious");
-var Promise = require("bluebird");
-
-var field_type_date = new Sealious.ChipTypes.FieldType({
- name: "date",
- get_description: function(context, params){
- return "Date standard ISO 8601 (YYYY-MM-DD)";
- },
- is_proper_value: function(accept, reject, context, params, date){
- var date_in_string = date.toString();
-
- var regex = /^([0-9]{4})-(0?[1-9]|1[0-2])-([0-2]?[0-9]|30|31)$/; //granulation_per_day
-
- if (regex.test(date_in_string) === false || isNaN(Date.parse(date_in_string))) {
- reject("Value `" + date + "`" + " is not date calendar format. Expected value standard IS0 8601 (YYYY-MM-DD)");
- } else {
- accept();
- }
- }
-});
diff --git a/lib/base-chips/field_type.datetime.js b/lib/base-chips/field_type.datetime.js
deleted file mode 100644
index d33ad85b..00000000
--- a/lib/base-chips/field_type.datetime.js
+++ /dev/null
@@ -1,20 +0,0 @@
-var Sealious = require("sealious");
-var Promise = require("bluebird");
-
-var field_type_datetime = new Sealious.ChipTypes.FieldType({
- name: "datetime",
- get_description: function(context, params){
- return "Timestamp - amount of miliseconds since epoch."
- },
- is_proper_value: function(accept, reject, context, params, datetime){
- if (isNaN(datetime) === true || datetime % 1 !== 0) {
- reject("Value `" + datetime + "`" + " is not datetime format. Only timestamps are accepted.");
- } else {
- accept();
- }
- },
- encode: function(context, params, value_in_code){
- var parsed_datetime = parseInt(value_in_code);
- return parsed_datetime;
- }
-});
\ No newline at end of file
diff --git a/lib/base-chips/field_type.email.js b/lib/base-chips/field_type.email.js
deleted file mode 100644
index e31767af..00000000
--- a/lib/base-chips/field_type.email.js
+++ /dev/null
@@ -1,20 +0,0 @@
-var Sealious = require("sealious");
-var Promise = require("bluebird");
-
-var field_type_email = new Sealious.ChipTypes.FieldType({
- name: "email",
- get_description: function(context, params){
- return "Email address, like something@something.sth"
- },
- is_proper_value: function(accept, reject, context, params, value){
- var address = value;
-
- var regex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
-
- if (!regex.test(address)) {
- reject(address + " is not valid e-mail address.");
- } else {
- accept();
- }
- }
-});
\ No newline at end of file
diff --git a/lib/base-chips/field_type.file.js b/lib/base-chips/field_type.file.js
deleted file mode 100644
index 701ad9db..00000000
--- a/lib/base-chips/field_type.file.js
+++ /dev/null
@@ -1,42 +0,0 @@
-var Sealious = require("sealious");
-var Promise = require("bluebird");
-
-var FieldFileType = new Sealious.ChipTypes.FieldType({
- name: "file",
- handles_large_data: true,
- is_proper_value: function(accept, reject, context, params, value){
- if (value === undefined) {
- return undefined;
- }
- if ((value instanceof Sealious.File) || (value.filename !== undefined && value.data instanceof Buffer)) {
- accept();
- } else {
- var type;
- if (value instanceof Array) {
- type = "<Array>. If you want to upload multiple files, use array field types.";
- } else {
- type = typeof data;
- }
- reject("Wrong file data format. Should be Sealious.File, but received " + type);
- }
- },
- encode: function(context, params, value_in_code){
- // it doesn't check what the value_in_code really is
- if (value_in_code) {
- return Sealious.FileManager.save_file(value_in_code);
- } else {
- return null;
- }
- },
- decode: function(context, params, value_in_database){
- if (value_in_database) {
- return Promise.resolve(new Sealious.File.Reference(value_in_database.id, value_in_database.filename));
- } else {
- if (params.no_file_value) {
- return params.no_file_value;
- } else {
- return undefined;
- }
- }
- }
-});
\ No newline at end of file
diff --git a/lib/base-chips/field_type.float.js b/lib/base-chips/field_type.float.js
deleted file mode 100644
index 290fe933..00000000
--- a/lib/base-chips/field_type.float.js
+++ /dev/null
@@ -1,21 +0,0 @@
-var Sealious = require("sealious");
-var Promise = require("bluebird");
-
-var field_type_float = new Sealious.ChipTypes.FieldType({
- name: "float",
- get_description: function(context, params){
- return "Float number."
- },
- is_proper_value: function(accept, reject, context, params, number){
- var test = parseFloat(number);
- if (test === null || isNaN(test) || isNaN(number) === true) {
- reject("Value `" + number + "` is not a float number format.");
- } else {
- accept();
- }
- },
- encode: function(context, params, value_in_code){
- var parsed_float = parseFloat(value_in_code);
- return parsed_float;
- }
-});
diff --git a/lib/base-chips/field_type.hashed-text.js b/lib/base-chips/field_type.hashed-text.js
deleted file mode 100644
index f3617031..00000000
--- a/lib/base-chips/field_type.hashed-text.js
+++ /dev/null
@@ -1,71 +0,0 @@
-var Sealious = require('sealious');
-var Promise = require("bluebird");
-var crypto = require("crypto");
-
-var field_type_hashed_text = new Sealious.ChipTypes.FieldType({
- name: "hashed-text",
- extends: "text",
- get_description: function(context, params){
- var 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(accept, reject, context, params, new_value){
- var pattern_array = [];
- if (params instanceof Object){
- if (params.required_digits){
- pattern_array.push(new RegExp("(.*[0-9]+.*){" + params.required_digits + "}"));
- }
- if (params.required_capitals){
- pattern_array.push(new RegExp("(.*[A-Z]+.*){" + params.required_capitals + "}"));
- }
-
- var isAccepted = pattern_array.map(n => n.test(new_value)).reduce( (a,b) => a && b, true);
-
- if (isAccepted) {
- accept();
- }
- else {
- var digits = params.required_digits || "0";
- var capitals = params.required_capitals || "0";
- reject("It didn't fulfill the requirements: required digits - " + digits + ", required capitals " + capitals);
- }
- }
- else {
- accept();
- }
- },
- encode: function(context, params, value_in_code){
- var 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'))
- }
- });
- })
- }
-})
diff --git a/lib/base-chips/field_type.int.js b/lib/base-chips/field_type.int.js
deleted file mode 100644
index b23f7bba..00000000
--- a/lib/base-chips/field_type.int.js
+++ /dev/null
@@ -1,20 +0,0 @@
-var Sealious = require("sealious");
-var Promise = require("bluebird");
-
-var field_type_int = new Sealious.ChipTypes.FieldType({
- name: "int",
- get_description: function(context, params){
- return "An integer number."
- },
- is_proper_value: function(accept, reject, context, params, new_value){
- if (new_value === null || isNaN(new_value) === true || new_value % 1 !== 0) {
- reject("Value `" + new_value + "` is not a int number format.");
- } else {
- accept();
- }
- },
- encode: function(context, params, value_in_code){
- var parsed_int = parseInt(value_in_code);
- return parsed_int;
- }
-});
diff --git a/lib/base-chips/field_type.reference.js b/lib/base-chips/field_type.reference.js
deleted file mode 100644
index 3ec591c4..00000000
--- a/lib/base-chips/field_type.reference.js
+++ /dev/null
@@ -1,90 +0,0 @@
-var Sealious = require("sealious");
-var Promise = require("bluebird");
-var clone = require("clone");
-
-var field_type_reference = new Sealious.ChipTypes.FieldType({
- name: "reference",
- is_proper_declaration: function(declaration){
- var required_declaration_fields = {
- "name": "string",
- "allowed_types": "array"
- };
- for (var attribute_name in required_declaration_fields) {
- if (declaration[attribute_name] === undefined) {
- throw new Sealious.Errors.DeveloperError("Missing `" + attribute_name + "` attribute in reference declaration.");
- }
- }
- for (var i in declaration.allowed_types) {
- var type_name = declaration.allowed_types[i];
- if (!Sealious.ChipManager.chip_exists("resource_type", type_name)) {
- throw new Sealious.Errors.DeveloperError("Unknown allowed type in declaration of reference: " + type_name);
- }
- }
- },
- is_proper_value: function(accept, reject, context, params, value){
- if (typeof value === "object") {
- //validate object's values as values for new resource
- var type = value.type;
- if (type === undefined) {
- reject("Reference resource type undefined. `type` attribute should be set to one of these values: " + params.allowed_types.join(", ") + ".");
- } else if (params.allowed_types.indexOf(type) === -1) {
- reject("Incorrect reference resource type: `" + type + "`. Allowed resource types for this reference are:" + params.allowed_types.join(", ") + ".");
- } else {
- var resource_type_object = Sealious.ChipManager.get_chip("resource_type", type);
- var access_strategy = resource_type_object.get_access_strategy();
-
- return access_strategy.check(context, value.type, value.data)
- .then(function(){
- return resource_type_object.validate_fiel0d_values(context, true, value.data);
- })
- }
- } else {
- //value is uid. Check if it is proper
- var supposed_resource_id = value;
- return Sealious.ResourceManager.get_by_id(context, supposed_resource_id)
- .then(function(resource){
- if (params.allowed_types.indexOf(resource.type) >= 0) {
- accept(resource);
- } else {
- reject("Resource of id `" + supposed_resource_id + "` is not of allowed type. Allowed types are: [" + this.params.allowed_types.join(", ") + "]");
- }
- }.bind(this))
- .catch(function(error){
- if (error.type === "not_found") {
- reject(error.status_message);
- } else {
- reject(error);
- }
- }.bind(this));
- }
- },
- encode: function(context, params, value_in_code){
- //decide whether to create a new resource (if so, do create it). Resolve with id of referenced resource.
- if (value_in_code instanceof Object) {
- return Sealious.ResourceManager.create(context, value_in_code.type, value_in_code.data).then(function(resource){
- return Promise.resolve(resource.id);
- })
- } else {
- //assuming the provided id already exists
- return Promise.resolve(value_in_code);
- }
- },
- get_description: function(context, params){
- var params_copy = clone(params, false);
- params_copy.allowed_types = {};
- for (var i in params.allowed_types) {
- var type_name = params.allowed_types[i];
- var type_object = Sealious.ChipManager.get_chip("resource_type", type_name);
- var type_schema = Sealious.ChipManager.get_chip("resource_type", type_name).get_specification();
- params_copy.allowed_types[type_name] = type_schema;
- }
- return params_copy;
- },
- decode: function(context, params, value_in_db){
- if (value_in_db === undefined) {
- return Promise.resolve(undefined);
- } else {
- return Sealious.ResourceManager.get_by_id(context, value_in_db);
- }
- }
-});
\ No newline at end of file
diff --git a/lib/base-chips/field_type.text.js b/lib/base-chips/field_type.text.js
deleted file mode 100644
index d6a6f97f..00000000
--- a/lib/base-chips/field_type.text.js
+++ /dev/null
@@ -1,54 +0,0 @@
-var Sealious = require("sealious");
-var Promise = require("bluebird");
-var sanitizeHtml = require("sanitize-html");
-
-var field_type_text = new Sealious.ChipTypes.FieldType({
- name: "text",
- get_description: function(context, params){
- return "Text with a maximum length " + params.max_length
- },
- is_proper_value: function(accept, reject, context, params, new_value){
- if (params === undefined || (params.max_length === undefined && params.min_length === undefined)) {
- accept()
- } else {
- if (params.max_length !== undefined) {
- if (new_value.length <= params.max_length) {
- accept()
- } else {
- reject("Text '" + new_value + "' has exceeded max length of " + params.max_length + " chars.");
- }
- }
- else if (params.min_length !== undefined) {
- if (new_value.length >= params.min_length) {
- accept();
- } else {
- reject("Text '" + new_value + "' is too short, minimum length is " + params.max_length + " chars.");
- }
- }
- else if (params.min_length !== undefined && params.max_length !== undefined) {
- if (new_value.length >= params.min_length && new_value.length <= params.max_length) {
- accept();
- } else {
- reject("Text '" + new_value + "' length should be between " + params.min_length + " and " + params.max_length + ".");
- }
-
- }
- }
- },
- encode: function(context, params, value_in_code){
- if (params && params.strip_html === true) {
- var stripped = sanitizeHtml(value_in_code.toString(), {
- allowedTags: []
- })
- return Promise.resolve(stripped);
- } else {
- if (value_in_code instanceof Object) {
- return Promise.resolve(JSON.stringify(value_in_code));
- } else if (value_in_code === null) {
- return Promise.resolve(null);
- } else {
- return Promise.resolve(value_in_code.toString());
- }
- }
- }
-});
\ No newline at end of file
diff --git a/lib/base-chips/resource_type.user.js b/lib/base-chips/resource_type.user.js
index 0768b148..8b871805 100644
--- a/lib/base-chips/resource_type.user.js
+++ b/lib/base-chips/resource_type.user.js
@@ -1,19 +1,30 @@
-var Sealious = require("sealious");
-var user = new Sealious.ChipTypes.ResourceType({
+"use strict";
+module.exports = {
name: "user",
fields: [{
name: "username",
- type: "text",
- required: true
+ type: "username",
+ required: true,
}, {
name: "email",
- type: "email"
+ type: "email",
}, {
name: "password",
- type: "text",
- required: true
+ type: "hashed-text",
+ params: {
+ min_length: 6,
+ hide_hash: true,
+ },
+ required: true,
}, {
name: "status",
- type: "text"
- }, ]
-});
+ type: "text",
+ }, {
+ name: "last_login_context",
+ type: "context",
+ }],
+ access_strategy: {
+ default: "public",
+ retrieve: "themselves",
+ },
+};
diff --git a/lib/chip-types/access-strategy-type.js b/lib/chip-types/access-strategy-type.js
new file mode 100644
index 00000000..54ecc448
--- /dev/null
+++ b/lib/chip-types/access-strategy-type.js
@@ -0,0 +1,70 @@
+"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");
+
+function AccessStrategyType(declaration){
+ if (declaration instanceof AccessStrategyType){
+ return declaration;
+ } else if (typeof declaration === "string"){
+ return 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;
+ if (declaration){
+ this._process_declaration(declaration);
+ }
+}
+
+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);
+ }
+ });
+ });
+ }
+ }).catch(function(error){
+ if (typeof error === "string"){
+ return Promise.reject(new Errors.BadContext(error));
+ } else {
+ return Promise.reject(error);
+ }
+ });
+};
+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";
+
+module.exports = AccessStrategyType;
diff --git a/lib/chip-types/access-strategy.js b/lib/chip-types/access-strategy.js
index 89dda26a..a35fa50c 100644
--- a/lib/chip-types/access-strategy.js
+++ b/lib/chip-types/access-strategy.js
@@ -1,73 +1,28 @@
-var Sealious = require("../main.js");
-var Promise = require("bluebird");
-var Chip = require("./chip.js");
-
-function AccessStrategy (declaration) {
- if (typeof declaration.name !== "string") {
- throw new Sealious.Errors.DeveloperError("Access strategy declaration has an invalid or missing `name` attribute");
- }
- Chip.call(this, true, "access_strategy", declaration.name);
- this.checker_function = null;
- this.item_sensitive = false;
- if (declaration) {
- this._process_declaration(declaration);
- }
-}
-
-AccessStrategy.prototype = new function(){
-
-
- /*
- Process declaration of access strategy. Gives new access strategy checker_function and item_sensitive from declaration.
- @param {object} delcaration - is an object with attributes:
- name - string, required. The name of the access strategy - it has to be a string unique amongst any other access strategies in your application.
- checker_function - function, required. It’s a function that takes a context instance as an argument and implements the logic of the access strategy. Its return values can be:
- * boolean - true for granting the access and false for denying.
- * a Promise - that resolves when the access is granted and rejects otherwise. Use promises only when the decision depends on a result of an asynchronous function.
- item_sensitive - boolean, defaults to false. If set to true, the checker_function is provided with a second argument, which contains an object representing the resource being requested.
- */
- this._process_declaration = function(declaration){
- this.checker_function = declaration.checker_function === undefined ? null : declaration.checker_function;
- if (declaration.item_sensitive !== undefined) {
- this.item_sensitive = declaration.item_sensitive;
- }
- }
-
- /*
- Setter of checker function.
- @param {function} checker_function - function to be set as checker function of this access strategy.
- return void
- */
- this.set_checker_function = function(checker_function){
- this.checker_function = checker_function;
- }
-
-
- /*
- Calls checker function and returns Promise if checker function resolves or error if it doesn't.
- @param {object} context - context in which item will be checked
- @param {object} item - item to be checked by checker function
- return Promise
- */
- this.check = function(context, item){
- var arguments_to_check_function = arguments;
- return this.checker_function.apply(this, arguments_to_check_function)
- .then(function(){
- return Promise.resolve(item);
- }).catch(function(error_message){
- if (typeof error_message === "string") {
- return Promise.reject(new Sealious.Errors.BadContext(error_message));
- } else {
- return Promise.reject(error_message);
- }
- });
+"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){
+ if (declaration instanceof Array){
+ this.type = new AccessStrategyType(declaration[0]);
+ this.params = declaration[1] || {};
+ } else if (typeof declaration === "string" || declaration instanceof AccessStrategyType){
+ this.type = new AccessStrategyType(declaration);
+ this.params = {};
+ } else {
+ this.type = new AccessStrategyType(declaration.type);
+ this.params = declaration.params || {};
}
-}
+};
-// odrzucanie i przyjmowanie wartości za pomocą checker_function, która zwraca Promisa
-// odrzucanie i przyjmowanie wartości za pomocą checker_function, która zwraca Booleana
+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);
+};
-AccessStrategy.type_name = "access_strategy";
-module.exports = AccessStrategy;
\ No newline at end of file
+module.exports = AccessStrategy;
diff --git a/lib/chip-types/channel.js b/lib/chip-types/channel.js
index e77084e2..0dd2f92d 100644
--- a/lib/chip-types/channel.js
+++ b/lib/chip-types/channel.js
@@ -1,19 +1,21 @@
-var Sealious = require("../main.js");
-var chip = require("./chip.js");
+"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) {
+function channel (name){
this.name = name;
- this.longid = "channel." + name;
+ this.longid = `channel.${name}`;
this.default_configuration = {};
- Sealious.ChipManager.add_chip("channel", this.name, this);
+ ChipManager.add_chip("channel", this.name, this);
}
channel.prototype = new chip();
-module.exports = channel;
\ No newline at end of file
+module.exports = channel;
diff --git a/lib/chip-types/chip-manager.js b/lib/chip-types/chip-manager.js
index 5cb2b04e..7927ea5f 100644
--- a/lib/chip-types/chip-manager.js
+++ b/lib/chip-types/chip-manager.js
@@ -1,165 +1,154 @@
-var Sealious = require("../main.js");
+"use strict";
+const locreq = require("locreq")(__dirname);
+const Errors = locreq("lib/response/error.js");
+const Logger = locreq("lib/logger/logger.js");
-var fs = require("fs");
-var path = require('path')
-var Promise = require("bluebird");
+const Promise = require("bluebird");
-var ConfigurationManager = require("../config/config-manager.js");
+const ConfigurationManager = require("../config/config-manager.js");
-var chip_type_functions = {
- channel: require("./channel.js"),
- resource_type: require("./resource-type.js"),
- field_type: require("./field-type.js"),
- datastore: require("./datastore.js")
-}
+// const chip_type_functions = {
+// channel: require("./channel.js"),
+// resource_type: require("./resource-type.js"),
+// field_type: require("./field-type.js"),
+// datastore: require("./datastore.js")
+// };
-var chips_by_module = {};
+const chips = {};
-var chips = {};
+const chip_type_start_order = ["access_strategy", "field_type", "resource_type", "channel"];
-var chip_type_start_order = ["datastore", "access_strategy", "field_type", "resource_type", "channel"];
-
-var ChipManager = new function(){
+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
*/
- this.start_chips = function(){
- Sealious.Logger.info("Starting all chips:");
- var promises = [];
- for (var i in chip_type_start_order){
- var type = chip_type_start_order[i];
- Sealious.Logger.info(" " + type + ":");
- for (var name in chips[type]){
- var chip = chips[type][name];
- Sealious.Logger.info("\t \u2713 " + name);
+ 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){
- var promise = chip.start();
+ promise = chip.start();
promises.push(promise);
}
} catch (error){
- Sealious.Logger.error("\t " + "couldn't start `" + name + "`");
+ Logger.error(`\t " + "couldn't start "${name}"`);
return Promise.reject(error);
}
}
}
return Promise.all(promises);
- }
-
- /**
- * Adds chip to chips array and chips_by_module array
- * @param {string} type - chip type ex. access-strategy, channel
- * @param {string} name - chip name
- * @param {object} chip - chip itselfs
- * @returns void
- */
- this.add_chip = function(type, name, chip){
-
- if (chips[type] === undefined) {
+ },
+ 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.
*/
-
- this.get_all_resource_types = function(){
- var names = [];
- for (var resource_type in chips.resource_type) {
+ __get_all_resource_types: function(chips){
+ const names = [];
+ for (const resource_type in chips.resource_type){
names.push(resource_type);
}
-
return names;
- }
+ },
+ get_all_resource_types: function(){
+ return this.__get_all_resource_types(chips);
+ },
/**
* Checks if chip exists
* @param {string} type - chip type
* @param {string} name - chip name
* @returns {boolean} true if exists, otherwise false
*/
- this.chip_exists = function(type, name){
+ chip_exists: function(type, name){
if (chips[type] && chips[type][name]){
return true;
} else {
return false;
}
- }
-
- /**
- * Gets chip
- * @param {string} type - chip type
- * @param {string} name - chip name
- * @returns {object} requested chip or throws error
- */
- this.get_chip = function(type, name){
+ },
+ __get_chip: function(chips, type, name){
try {
- var ret = chips[type][name];
+ const ret = chips[type][name];
if (ret === undefined){
- throw new Error("Chip of type " + type + " and name " + name + " has not yet been registered.");
+ throw new Error(`Chip of type ${type} and name ${name} has not yet been registered`);
}
return ret;
} catch (e){
- throw new Sealious.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"});
+ 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
*/
- this.get_chip_by_longid = function(longid){
- var type = longid.split(".")[0];
- var name = longid.split(".")[1];
- return this.get_chip(type, name);
- }
-
- /*
- Gets amount of chips in given type
- * @param {string} type - type name ex. chanell, access_strategy
- * @returns {integer} amount of chips of this type
- */
- this.get_chip_amount_by_type = function(type){
+ __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
*/
- this.get_datastore_chip = function(){
- var datastore_chip_amount = this.get_chip_amount_by_type("datastore");
+ get_datastore_chip: function(){
+ const datastore_chip_amount = this.get_chip_amount_by_type("datastore");
if (datastore_chip_amount === 0){
- throw new Sealious.Errors.Error("Chip manager was requested to return the datastore chip, but no chips of type `datastore` have been registered.")
+ 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]]
+ return chips["datastore"][Object.keys(chips["datastore"])[0]];
} else {
- var datastore_chip_name = ConfigurationManager.get_config().datastore_chip_name;
+ const datastore_chip_name = ConfigurationManager.get_config().datastore_chip_name;
if (datastore_chip_name === undefined){
- throw new Sealious.Errors.Error("Chip manager was requested to return a datastore chip. Multiple chips of type `datastore` have been registered, and no default provided in configuration.")
+ 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);
- }
+ }
}
- }
- /**
- * Gets all chips of given type
- * @param {string} chip type name ex. channel, access_strategy
- * @returns {array} Array of chips of given type.
- */
-
- this.get_chips_by_type = function(chip_type){
+ },
+ __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 7d71d022..82a363a1 100644
--- a/lib/chip-types/chip.js
+++ b/lib/chip-types/chip.js
@@ -1,54 +1,50 @@
-var Promise = require("bluebird");
+"use strict";
+const Promise = require("bluebird");
-var ChipManager = null;
+let ChipManager;
-var chip = function(add_to_chip_manager, type, name){
+const Chip = function(type, name){
this.configuration = {};
Object.defineProperty(this, "default_configuration", {
- set: this.apply_default_settings
- })
+ set: this.apply_default_settings,
+ });
this.type = type;
this.name = name;
- this.longid = type + "." + name;
+ this.longid = `${type}.${name}`;
- if (add_to_chip_manager) {
- var ChipManager = ChipManager || require("./chip-manager.js");
+ if (name){
+ ChipManager = ChipManager || require("./chip-manager.js");
ChipManager.add_chip(type, name, this);
}
-}
+};
-chip.prototype = new function(){
-
- this.apply_default_settings = function(default_config){
- for (var i in default_config) {
- if (!this.configuration[i]) {
- this.configuration[i] = default_config[i];
- }
+Chip.prototype.apply_default_settings = function(default_config){
+ for (const i in default_config){
+ if (!this.configuration[i]){
+ this.configuration[i] = default_config[i];
}
}
-
- this.configure = function(config){
- config = config || {};
- this.configuration = config;
- }
-
- this.start = function(){
- //to be overwritten
- return Promise.resolve();
- }
-
- this.test = function(){
- if (this.test_compatibility) {
- console.log("Starting compatibility tests for chip: `" + this.name + "`");
- this.test_compatibility().then(function(){
- console.log("\t✓ Compatibility test successfull!");
- })
- }
- }
-}
-
-
-
-module.exports = chip;
\ No newline at end of file
+};
+
+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/datastore.js b/lib/chip-types/datastore.js
index 6eb4c527..f0949459 100644
--- a/lib/chip-types/datastore.js
+++ b/lib/chip-types/datastore.js
@@ -1,251 +1,255 @@
-var assert = require("assert");
-var Sealious = require("../main.js");
-var Chip = require("./chip.js");
-var Promise = require("bluebird");
+"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
*/
-var Datastore = function(name){
+const Datastore = function(name){
this.name = name;
- this.longid = "datastore." + name;
+ this.longid = `datastore.${name}`;
this.default_configuration = {};
- Sealious.ChipManager.add_chip("datastore", this.name, this);
-}
+ ChipManager.add_chip("datastore", this.name, this);
+};
Datastore.prototype = new Chip();
/**
- * Defines functions datastore need to implement,
+ * Defines functions datastore need to implement,
* then ensures that if one of these function will not be implemented Selious will throw an informative error.
*/
-var needs_to_implement = ["find", "insert", "update", "remove"]
+const needs_to_implement = ["find", "insert", "update", "remove"];
Datastore.prototype.return_not_implemented = function(fn_name){
return function(){
- throw new Sealious.Errors.DeveloperError("Function ", fn_name, "not implemented in ", this.longid, ", aborting.");
- }
-}
+ throw new Errors.DeveloperError("Function ", fn_name, "not implemented in ", this.longid, ", aborting.");
+ };
+};
-for (var i in needs_to_implement) {
- var fn_name = needs_to_implement[i];
- Datastore.prototype[fn_name] = Datastore.prototype.return_not_implemented(fn_name)
+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(){
- var self = this;
+ const self = this;
this.start();
- var rand = Math.random();
+ const rand = Math.random();
- var test_collection_name = "_test";
+ const test_collection_name = "_test";
return Promise.resolve()
.then(function(){
- //.insert method should respond with the created document
- var to_insert = {
+ // .insert method should respond with the created document
+ const to_insert = {
value: 1,
- random: rand
+ 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
+ // 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");
+ assert(documents instanceof Array, `datastore.${self.name}.find should resolve with an array`);
return Promise.resolve();
});
}).then(function(){
- //check if amount of created documents checks out
- var creates = [
+ // check if amount of created documents checks out
+ const creates = [
self.insert(test_collection_name, {
value: 2,
- random: rand
+ random: rand,
}),
self.insert(test_collection_name, {
value: 3,
- random: rand
+ random: rand,
}),
self.insert(test_collection_name, {
value: 4,
- random: -rand
+ random: -rand,
}),
- ]
+ ];
- var created_so_far = 4;
+ 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()");
+ assert(documents.length === created_so_far, `Inserted ${created_so_far} documents so far, but ${documents.length} were returned on .find()`);
return Promise.resolve(created_so_far);
});
}).then(function(created_so_far){
- //check if there is a proper amount of documents with random value set to rand
- var documents_with_rand = created_so_far - 1;
+ // 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
- }, {})
+ 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 + "})");
+ assert(documents.length === documents_with_rand, `Inserted ${documents_with_rand} documents with "random" set to "${rand}" so far, but ${documents.length} were returned on .find({random: ${rand}})`);
return Promise.resolve();
});
}).then(function(){
- //Should store a complex object
- var complex_object = {
+ // Should store a complex object
+ const complex_object = {
id: "aseoifaoeina",
body: {
name: "Anna",
- surname: "Fontanna"
- }
+ 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
- })
+ 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
+ // Should handle dot-notation nested queries
return self.find(test_collection_name, {
- "body.name": complex_object.body.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
- }
- })
+ 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
+ // .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
- })
+ id: complex_object.id,
+ }, {
+ "body.name": complex_object.body.name,
+ })
.then(function(){
return self.find(test_collection_name, {
- id: complex_object.id
+ 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
+ // .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
- }
- })
+ id: complex_object.id,
+ }, {
+ body: {
+ name: complex_object.body.name,
+ },
+ })
.then(function(){
return self.find(test_collection_name, {
- id: complex_object.id
+ 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)
+ // .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
- }
- })
+ id: complex_object.id,
+ }, {
+ body: {
+ other: complex_object.body.other,
+ },
+ })
.then(function(){
return self.find(test_collection_name, {
- id: complex_object.id
+ 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
+ // .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),
+ self.insert(test_collection_name, complex_object)
]).then(function(){
- //all the "complex_object" documents have the same id
+ // all the "complex_object" documents have the same id
return self.remove(test_collection_name, {
- id: complex_object.id
+ id: complex_object.id,
}, true);
}).then(function(){
return self.find(test_collection_name, {
- id: complex_object.id
+ 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
+ // .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),
+ self.insert(test_collection_name, complex_object)
]).then(function(){
- //all the "complex_object" documents have the same id
+ // all the "complex_object" documents have the same id
return self.remove(test_collection_name, {
- id: complex_object.id
+ id: complex_object.id,
}, false);
}).then(function(){
return self.find(test_collection_name, {
- id: complex_object.id
+ id: complex_object.id,
});
}).then(function(results){
assert(results.length === 0, ".remove should remove all matching documents when 'just_one' is falsy");
return Promise.resolve(complex_object);
});
}).then(function(){
self.clear_collection(test_collection_name);
- }).catch(function(err){
+ }).catch(function(){
self.clear_collection(test_collection_name);
- return Promise.reject("Compatibility test unsuccesfull")
+ return Promise.reject("Compatibility test unsuccesfull");
});
};
-module.exports = Datastore;
\ No newline at end of file
+module.exports = Datastore;
diff --git a/lib/chip-types/field-structures.js b/lib/chip-types/field-structures.js
new file mode 100644
index 00000000..2a2744a3
--- /dev/null
+++ b/lib/chip-types/field-structures.js
@@ -0,0 +1,6 @@
+"use strict";
+const FieldStructures = {
+ single: require("./field-structures/single.js")
+};
+
+module.exports = FieldStructures;
diff --git a/lib/chip-types/field-structures/single.js b/lib/chip-types/field-structures/single.js
new file mode 100644
index 00000000..29769410
--- /dev/null
+++ b/lib/chip-types/field-structures/single.js
@@ -0,0 +1,14 @@
+"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-default-methods.js b/lib/chip-types/field-type-default-methods.js
new file mode 100644
index 00000000..ba3db04f
--- /dev/null
+++ b/lib/chip-types/field-type-default-methods.js
@@ -0,0 +1,35 @@
+"use strict";
+const Promise = require("bluebird");
+
+const FieldTypeDescription = require("../data-structures/field-type-description.js");
+
+const default_methods = {
+ is_proper_value: function(context, params, new_value, old_value){
+ return Promise.resolve();
+ },
+ format: function(context, params, decoded_value, format_params){
+ return Promise.resolve(decoded_value);
+ },
+ encode: function(context, params, value_in_code){
+ return Promise.resolve(value_in_code);
+ },
+ get_description: function(context, params){
+ return new FieldTypeDescription(this.name);
+ },
+ decode: function(context, params, value_in_database){
+ return value_in_database;
+ },
+ filter_to_query: function(context, params, query){
+ return Promise.resolve(this.encode(context, params, query))
+ .then(function(encoded_value){
+ return {
+ $eq: encoded_value,
+ };
+ });
+ },
+ full_text_search_enabled: function(){
+ return false;
+ }
+};
+
+module.exports = default_methods;
diff --git a/lib/chip-types/field-type.js b/lib/chip-types/field-type.js
index cf25f2fd..20e0b6ae 100644
--- a/lib/chip-types/field-type.js
+++ b/lib/chip-types/field-type.js
@@ -1,196 +1,74 @@
-var Sealious = require("../main.js");
-var Promise = require("bluebird");
-var merge = require("merge");
-
-var Chip = require("./chip.js");
-
-var FieldTypeDescription = require("../data-structures/field-type-description.js");
-
-/**
- * Stores field type metadata, as well as validation methods
- * @class
- */
-
-function FieldType (declaration) {
- Chip.call(this, true, "field_type", declaration.name);
-
- this.old_value_sensitive_methods = declaration.old_value_sensitive_methods || false;
-
- this.process_declaration(declaration);
+"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");
+const methods_with_accept_reject_interface = new Set(["is_proper_value"]);
+
+
+function wrap_method_in_accept_reject (declaration, method_name){
+ return function(){
+ const that = this;
+ const arguments_array = Object.keys(arguments).map((key)=>arguments[key]);
+ return new Promise(function(resolve, reject){
+ const accept = resolve;
+ const new_reject = function(error){
+ if (typeof error === "string"){
+ reject(new Errors.ValidationError(error));
+ } else {
+ reject(error);
+ }
+ };
+ arguments_array.unshift(accept, new_reject);
+ declaration[method_name].apply(this, arguments_array);
+ });
+ };
}
-FieldType.prototype = new function(){
-
- this.process_declaration = function(declaration){
- this.declaration = declaration;
- this.name = declaration.name;
- this.handles_large_data = declaration.handles_large_data === undefined? false : true;
+function wrap_method_in_promise (declaration, method_name){
+ return function(){
+ return Promise.resolve(declaration[method_name].apply(this, arguments));
+ };
+}
- if (declaration.extends) {
- this.parent_field_type = Sealious.ChipManager.get_chip("field_type", declaration.extends);
- } else {
- this.parent_field_type = null;
+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
+ let self;
+
+ if (declaration instanceof FieldType){
+ return declaration;
+ } else if (typeof declaration === "string"){
+ return ChipManager.get_chip("field_type", declaration);
+ } else if (declaration.extends){
+ const parent_field_type = 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];
}
+ }
- // var method_names = ["is_proper_value", "valudate_declaration", "encode", "decode", ""];
-
- // method_names.forEach(function(method_name){
- // if(declaration[method_name]){
- // this[method_name] = declaration[method_name];
- // }else{
- // this[method_name] = this["_"+method_name];
- // }
- // });
+ if (declaration.name){
+ ChipManager.add_chip("field_type", declaration.name, self);
}
- this.is_old_value_sensitive = function(method_name){
- if (method_name === undefined) {
- if (typeof this.old_value_sensitive_methods === "boolean") {
- return this.old_value_sensitive_methods;
+ for (const prop_name in declaration){
+ if (default_methods[prop_name] !== undefined){
+ if (methods_with_accept_reject_interface.has(prop_name)){
+ self[prop_name] = wrap_method_in_accept_reject(declaration, prop_name);
} else {
- for (var i in this.old_value_sensitive_methods) {
- if (this.old_value_sensitive_methods[i]) {
- return true;
- }
- }
- return false;
+ self[prop_name] = wrap_method_in_promise(declaration, prop_name);
}
} else {
- if (typeof this.old_value_sensitive_methods === "boolean") {
- return this.old_value_sensitive_methods;
- } else {
- return this.old_value_sensitive_methods[method_name];
- }
- }
- }
-
- this.get_method = function(method_name){
- var ret;
- if (this.declaration[method_name]) {
- ret = this.declaration[method_name];
- } else {
- ret = this["_" + method_name].bind(this);
- }
- return Promise.method(ret);
- }
-
- /**
- * Whether a given value can be stored in this field type instance
- * @memberOf FieldType
- * @abstract
- * @param {any} value - value of this variable will be tested for compatibility with this field
- * @return {Promise}
- */
- //to be decorated
- this._is_proper_value = function(accept){
- accept();
- }
-
- /**
- * Whether a given declariation is proper
- * @memberOf FieldType
- * @abstract
- * @param {object} declaration - value of this variable will be tested for compatibility with this field
- * @returns {Promise|Boolean}
- *
- */
- //to be decorated
- this.is_proper_declaration = function(declaration){
- return true;
- }
-
- /**
- * Encodes value given by user
- * @memberOf FieldType
- * @abstract
- * @param {any} value_in_code - value to be encoded in proper format
- * @returns {Promise|Boolean}
- */
- //to be decorated
- this._encode = function(context, params, value_in_code){
- return value_in_code;
- }
-
- //to be decorated
- this._get_description = function(){
- return new FieldTypeDescription(this.name);
- }
-
- this._encode.uses_context = false;
-
- /**
- * Decodes value from database
- * @memberOf FieldType
- * @abstract
- * @param {Context} context
- * @param {object} param - field params
- * @param {any} value_in_database - value to be decoded to proper format
- * @return {Promise}
- */
- //to be decorated
- this._decode = function(context, param, value_in_database){
- return value_in_database;
- }
-
- this._decode.uses_context = false;
-
- this.is_proper_value = function(context, params, new_value, old_value){
- var self = this;
- var validate_in_parent;
- if (this.declaration.extends) {
- validate_in_parent = this.parent_field_type.is_proper_value(context, params, new_value, old_value);
- } else {
- validate_in_parent = Promise.resolve();
+ self[prop_name] = declaration[prop_name];
}
- return validate_in_parent.then(function(){
- return new Promise(function(resolve, reject){
- var new_reject = function(error_message){
- reject(new Sealious.Errors.ValidationError(error_message));
- }
- self.get_method("is_proper_value")(resolve, new_reject, context, params, new_value, old_value);
- });
- });
}
- /**
- * If a field-type has defined .decode method, use it. Otherwise use it's parent's or the default one
- **/
- this.decode = function(context, params, value_in_database){
- if (this.declaration.extends && this.declaration.decode === undefined) {
- return this.parent_field_type.decode(context, params, value_in_database);
- } else {
- return this.get_method("decode")(context, params, value_in_database);
- }
- }
-
- /**
- * If a field-type has defined .decode method, use it. Otherwise use it's parent's or the default one
- **/
- this.encode = function(context, params, value_in_code){
- if (this.declaration.extends && this.declaration.encode === undefined) {
- return this.parent_field_type.encode(context, params, value_in_code);
- } else {
- return this.get_method("encode")(context, params, value_in_code);
- }
- }
-
- this.get_description = function(params){
- if (this.declaration.extends && this.declaration.get_description === undefined) {
- return this.parent_field_type.get_description(params)
- } else {
- return this.get_method("get_description")(params)
- .then(function(description){
- if (typeof description === "string") {
- return Promise.resolve(new FieldTypeDescription(description));
- } else {
- return Promise.resolve(description);
- }
- });
- }
- }
-}
-
-FieldType.type_name = "field_type";
+ return self;
+};
-module.exports = FieldType;
\ No newline at end of file
+module.exports = FieldType;
diff --git a/lib/chip-types/field.js b/lib/chip-types/field.js
new file mode 100644
index 00000000..ef78ef7a
--- /dev/null
+++ b/lib/chip-types/field.js
@@ -0,0 +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){
+
+ this.name = declaration.name;
+ this.declaration = declaration;
+ this.type = new FieldType(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, this.params);
+ return self.type[method_name].apply(self.type, arguments_array);
+ };
+ })(method_name);
+ }
+
+}
+
+module.exports = Field;
diff --git a/lib/chip-types/resource-representation.js b/lib/chip-types/resource-representation.js
deleted file mode 100644
index f3153464..00000000
--- a/lib/chip-types/resource-representation.js
+++ /dev/null
@@ -1,42 +0,0 @@
-/**
- * Represents a particular resource in database. Constructed by database entry.
- * @class
- * @param {object} database_entry
- */
-function ResourceRepresentation (database_entry) {
- this.database_entry = database_entry;
-}
-
-ResourceRepresentation.prototype = new function(){
- /**
- * Returns an object representing the resource, ready to be output for the public, e.g. as JSON
- * @alias Resource#getData
- * @return {object}
- */
- this.getData = function(){
- var data = this.database_entry.body || {};
- data.owner_id = this.database_entry.owner;
- data.id = this.database_entry.sealious_id;
- data.access_mode = this.database_entry.access_mode;
- data.type = this.database_entry.type;
-
- return data;
- }
-
- /**
- * Encodes Resource's data into JSON
- * @alias Resource#toString
- * @return {string} contains the json-encoded data
- */
- this.toString = function(){
- return JSON.stringify(this.getData());
- }
- /**
- access_mode are not used in current version of Sealious, this code should be removed
- */
- this.get_access_mode = function(){
- return this.database_entry.access_mode;
- }
-}
-
-module.exports = ResourceRepresentation;
diff --git a/lib/chip-types/resource-type-field.js b/lib/chip-types/resource-type-field.js
deleted file mode 100644
index e768eeab..00000000
--- a/lib/chip-types/resource-type-field.js
+++ /dev/null
@@ -1,126 +0,0 @@
-var Sealious = require("../main.js");
-
-var Promise = require("bluebird");
-
-/**
- * !! resource_type is optional, needen only for nice errors
- *
- */
-
-function ResourceTypeField (declaration, resource_type) {
- this.name = declaration.name;
- this.type_name = declaration.type;
- this.human_readable_name = declaration.human_readable_name || null;
-
- if (!Sealious.ChipManager.chip_exists("field_type", this.type_name)) {
- throw new Sealious.Errors.DeveloperError("In declaration of resource type '" + resource_type.name + "': unknown field type '" + this.type_name + "' in field '" + this.name + "'.");
- }
- this.params = declaration.params;
- this.default_value = declaration.default_value;
- this.type = Sealious.ChipManager.get_chip("field_type", declaration.type);
-
- if (this.type.init) {
- this.type.init();
- }
- this.required = declaration.required || false;
- this.derived = declaration.derived || false;
-}
-
-ResourceTypeField.prototype = new function(){
- /**
- * Shorthand for ResourceTypeField.type.isProperValue
- * @alias ResourceTypeField#isProperValue
- * @param {object} value
- * @return {Promise}
- */
- this.check_value = function(context, value, old_value){
- return this.type.is_proper_value(context, this.params, value, old_value);
- }
- /**
- * Creates map object.name = value
- * @param {String} name
- * @param {String} value
- * @return {Promise} resolving with object, where object.name = value
- */
- function to_map (name, value) {
- var obj = {};
- obj[name] = value;
- return Promise.resolve(obj);
- }
-
- /**
- * Checks if field has previous value sensitive methods
- * @params method_name:String - which field-type method to check
- * @return {Boolean}
- */
- this.is_old_value_sensitive = function(method_name){
- return this.type.is_old_value_sensitive(method_name);
- }
-
-
- /**
- * It's a wrapper, which checks if encode_value function uses context or previous value, and if it does adds it to arguments.
- * @return {} encoded value
- */
- this.encode_value = function(context, new_value, old_value){
- return this.type.encode(context, this.params, new_value, old_value);
- }
-
- /**
- * It's a wrapper, which checks if decode_value function uses context, and if it does adds it to arguments.
- * @returns {} decoded value
- */
- this.decode_value = function(context, value_in_database){
- return this.type.decode(context, this.params, value_in_database);
- }
-
- /**
- * Gets field signature: name, type, required, human redable name, params, validator function, default value
- * @param {Boolean} with validator - - whether to include validator function in field description.
- * Warning! If set to true, the output is not serializable in JSON.
- * @returns {} field signature
- */
- this.get_specification = function(with_validator){
- //with_validator:boolean - whether to include validator function in field description. Warning! If set to true, the output is not serializable in JSON.
- var field_specification = {};
- field_specification.name = this.name;
- field_specification.type = this.type_name;
- field_specification.required = this.required;
- field_specification.human_readable_name = (typeof this.human_readable_name === "string") ? this.human_readable_name : undefined;
- field_specification.params = this.params;
- field_specification.validate = this.check_value.bind(this);
- field_specification.default_value = this.default_value;
- return field_specification;
- }
-
- this.get_nice_name = function(){
- return this.human_readable_name || this.name;
- }
-}
-
-ResourceTypeField.test_start = function(){
- describe("ResourceTypeField", function(){
- describe("constructor", function(){
- it("should throw a nice error when non-existent field type is provided in declaration", function(done){
- try {
- var test_field = new ResourceTypeField({
- name: "test_field",
- type: "truly_non_existent_field_type",
- }, {
- name: "fake_resource_type"
- });
- } catch (error) {
- if (error.is_developer_fault === true) {
- done();
- } else {
- done(new Error("But it threw a non-nice error."));
- }
- return;
- }
- done(new Error("But it didn't throw any error at all"));
- });
- })
- })
-}
-
-module.exports = ResourceTypeField;
\ No newline at end of file
diff --git a/lib/chip-types/resource-type.js b/lib/chip-types/resource-type.js
index f4b67b8f..6fb63db7 100644
--- a/lib/chip-types/resource-type.js
+++ b/lib/chip-types/resource-type.js
@@ -1,313 +1,280 @@
-var Sealious = require("../main.js");
-var Promise = require("bluebird");
+"use strict";
+const locreq = require("locreq")(__dirname);
+const Promise = require("bluebird");
-var merge = require("merge");
+const merge = require("merge");
+const clone = require("clone");
-var Chip = require("./chip.js");
-var ResourceTypeField = require("./resource-type-field.js");
+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");
-/**
-ResourceType constructor
-@constructor
-@params {object} declaration
-Resource-type declaration syntax:
-{
- name: String,
- fields: Array<FieldDescription>,
- access_strategy?: AccessStrategyDescription
-}
-* name, required - the name of the resource-type. It becomes the name of the chip representing the resource type, as well. It has to be unique amongst all other resource-types.
-* fields, required - an array of field descriptions. You can read about field description syntax below.
-* access_strategy, optional. A hashmap or string compatible with access strategy description syntax, described below. Defaults to public.
-*/
-var ResourceType = function(declaration){
- if (typeof declaration !== "object"){
- throw new Sealious.Errors.DeveloperError("Tried to create a resource-type without a declaration");
+const ResourceType = function(declaration){
+ if (typeof declaration === "string"){
+ return ChipManager.get_chip("resource_type", declaration);
+ } else if (declaration instanceof ResourceType){
+ return declaration;
}
- Chip.call(this, true, "resource_type", declaration.name);
+ Chip.call(this, "resource_type", declaration.name);
this.name = declaration.name;
this.human_readable_name = declaration.human_readable_name;
this.summary = declaration.summary;
this.fields = {};
- this.references = {};
this.access_strategy = {
- default: Sealious.ChipManager.get_chip("access_strategy", "public")
+ default: new AccessStrategy("public", {}),
};
this._process_declaration(declaration);
-}
-
-ResourceType.prototype = new function(){
-
- /*
- Process declaration, creates fields and sets access strategy
- @param {object} declaration - consistnent with resource type declaration syntax
- @returns void
- */
- this._process_declaration = function(declaration){
- if (declaration){
- if (declaration.fields){
- for (var i = 0; i < declaration.fields.length; i++){
- if (declaration.fields[i].params) {
- if (typeof declaration.fields[i].params !== "object") {
- throw new Sealious.Errors.ValidationError("In field `" + declaration.fields[i].name + "`: `params` is of wrong type, it should be an object")
- }
+};
+ResourceType.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);
+ this.add_fields(declaration.fields);
}
+ this.set_access_strategy(declaration.access_strategy);
}
-
- /*
- Adds field to resource type
- @param {object} field_declaration - consistnent with field declaration syntax
- {
- name: String,
- type: FieldTypeName,
- human_readable_name?: String,
- params?: Object
- }
- * name, required - a string representing the machine-readable name for the field. Should be short. No spaces allowed. All lower-case letters, the _ and - symbols are allowed.
- * human_readable_name, optional - a string representing a human-readable version of the field’s name. No restrictions on what is and what is not allowed here. When not specified, the value of ‘name’ attribute is used instead.
- * type, required - a string representing a resource-type name that is already registred in your Sealious application.
- * params, optional - a hashmap of parameters that will be passed to the field-type. These parameters are also a part of the field’s signature. Defaults to {}.
- @returns void
- */
- this.add_field = function(field_declaration){
- var field_object = new ResourceTypeField(field_declaration, this);
- var field_name = field_object.name;
- if (!this.fields[field_name]) {
- this.fields[field_name] = field_object;
- }
- else {
- throw new Sealious.Errors.DeveloperError("Duplicate field names: '" + field_name + "' in resource: '" + this.name + "'" );
- }
- }
- /*
- Adds multiple fields to resource type
- @param {array} field_declarations_array - array of declarations consistnent with field declaration syntax
- @returns void
- */
- this.add_fields = function(field_declarations_array){
- for (var i in field_declarations_array){
- var declaration = field_declarations_array[i];
- this.add_field(declaration);
- }
+};
+ResourceType.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;
}
- /*
- Checks if resource type has_previous_value_sensitive_fields
- @returns {boolean}
- */
- this.has_previous_value_sensitive_fields = function(){
- for (var field_name in this.fields){
- if (this.fields[field_name].has_previous_value_sensitive_methods()){
- return true;
- }
- }
- return false;
+ else {
+ throw new Errors.DeveloperError("Duplicate field names: '" + field_name + "' in resource: '" + this.name + "'");
}
- /*
- Checks if all values from given array are represented as fields resource type
- @params {array} values - array of names of fields, which resource type should have
- @returns {hashmap} validation_errors - hashmap of errors, if there was an unknown field there would be entry under key "missing_field_name" with value "unknown_field"
- */
- function ensure_no_unknown_fields (values) {
- var validation_errors = {};
- for (var field_name in values){
-
- if (this.fields[field_name] === undefined) {
- validation_errors[field_name] = "unknown_field";
- }
+};
+ResourceType.prototype.add_fields = function(field_declarations_array){
+ for (const i in field_declarations_array){
+ const declaration = field_declarations_array[i];
+ this.add_field(declaration);
+ }
+};
+ResourceType.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;
}
- return validation_errors;
}
-
-
-
- this.extend_with_missing_field_values_errors = function(current_validation_errors, values){
- for (var i in this.fields) {
- var field = this.fields[i];
- if (field.required && values[field.name] === undefined){
- current_validation_errors[field.name] = new Sealious.Errors.ValidationError("Missing value for field `" + field.get_nice_name() + "`");
- }
+ return false;
+};
+ResourceType.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}`);
}
}
+ return validation_errors;
+};
+ResourceType.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;
+ };
+ }
+};
+ResourceType.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);
- this.validate_field_values = function(context, check_missing, values, old_values){
- var self = this;
- var existing_field_names = Object.keys(this.fields);
- var validation_errors = {};
- var validation_tasks = [];
-
- for (var key in values){
- var validation_promise;
- if (values[key] === undefined){
- //if this field is required, it will be detected by extend_with_missing_field_values_errors called below
- continue;
- }
- var value = values[key];
- if (existing_field_names.indexOf(key) === -1){
- validation_errors[key] = new Sealious.Errors.ValidationError("Wrong field name: '" + key + "'");
- } else {
- var old_value = old_values ? old_values[key] : undefined;
- validation_promise = self.fields[key].check_value(context, value, old_value).catch((function(key){
- return function(error){
- validation_errors[key] = error;
- return Promise.resolve();
- }
- })(key));
- }
- validation_tasks.push(validation_promise);
+ return Promise.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;
+ });
+};
+ResourceType.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({type: "validation"}, (function(field_name){
+ return function(error){
+ errors[field_name] = error;
+ };
+ })(field_name));
+ promises.push(promise);
}
-
- return Promise.all(validation_tasks)
- .then(function(){
- if (check_missing){
- self.extend_with_missing_field_values_errors(validation_errors, values);
- }
- var has_errors = false;
- for (var key in validation_errors) {
- //validation_errors is not an empty object
- has_errors = true;
- var error = validation_errors[key];
- if (error.is_user_fault) {
- validation_errors[key] = error.message;
- } else {
- return Promise.reject(error);
- }
- }
- if (has_errors) {
- return Promise.reject(new Sealious.Errors.ValidationError("There are problems with some of the provided values", validation_errors));
- } else {
- //validation_errors is empty, resolve
- return Promise.resolve();
- }
- });
}
+ return Promise.all(promises)
+ .then(function(){
+ return errors;
+ });
+};
+ResourceType.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)
+ ];
- this.encode_field_values = function(context, body, old_body){
- var promises = {};
- for (var field_name in body){
- var current_value = body[field_name];
- if (current_value === undefined){
- promises[field_name] = null;
+ 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 {
- var old_value = old_body && old_body[field_name];
- promises[field_name] = this.fields[field_name].encode_value(context, current_value, old_value);
+ non_user_errors[field_name] = error;
}
}
- return Promise.props(promises);
- }
-
- /**
- * Gets resource type specification
- * @param {Boolean} with validator - - whether to include validator function in field description.
- * Warning! If set to true, the output is not serializable in JSON.
- * @returns {} resource type signature
- */
- this.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.
- var resource_type_specification = {};
- for (var field_name in this.fields){
- var field_specification = this.fields[field_name].get_specification(with_validators);
- resource_type_specification[field_name] = field_specification;
+ 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);
+ }
+ });
+};
+ResourceType.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);
}
-
- var specification = {
- name: this.name,
- human_readable_name: this.human_readable_name,
- summary: this.summary,
- fields: resource_type_specification
- };
- return specification;
}
-
- this.get_specification_with_validators = function(){
- return this.get_specification(true);
+ return Promise.props(promises);
+};
+ResourceType.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 resource_type_specification = {};
+ for (const field_name in this.fields){
+ const field_specification = this.fields[field_name].get_specification(with_validators);
+ resource_type_specification[field_name] = field_specification;
}
- this.set_access_strategy = function(strategy_declaration){
- var access_strategy_name;
-
- if (typeof strategy_declaration === "string"){
- access_strategy_name = strategy_declaration;
- this.access_strategy = {
- "default": Sealious.ChipManager.get_chip("access_strategy", access_strategy_name),
- }
- } else if (typeof strategy_declaration === "object"){
- for (var action_name in strategy_declaration){
- var access_strategy = Sealious.ChipManager.get_chip("access_strategy", strategy_declaration[action_name]);
- this.access_strategy[action_name] = access_strategy;
- }
+ const specification = {
+ name: this.name,
+ human_readable_name: this.human_readable_name,
+ summary: this.summary,
+ fields: resource_type_specification
+ };
+ return specification;
+};
+ResourceType.prototype.get_specification_with_validators = function(){
+ return this.get_specification(true);
+};
+ResourceType.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)
+ };
+ } 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);
}
}
-
- this.get_access_strategy = function(action){
- return this.access_strategy[action] || this.access_strategy["default"];
- }
-
- this.has_large_data_fields = function(){
- for (var i in this.fields){
- var field = this.fields[i];
- if (field.type.handles_large_data){
- return true;
- }
+};
+ResourceType.prototype.get_access_strategy = function(action_name){
+ return this.access_strategy[action_name] || this.access_strategy["default"];
+};
+ResourceType.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;
}
- return false;
}
-
- this.is_old_value_sensitive = function(method_name){
- for (var i in this.fields){
- if (this.fields[i].type.is_old_value_sensitive(method_name)) {
- return true;
- }
+ return false;
+};
+ResourceType.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;
}
- /**
- * Decodes multiple values, with proper decode value function
- * @param {Context} context
- * @param {Object} db_document - object representing encoded document from database
- * @returns {Promise} resolving with object represeting decoded resource
- */
- this.decode_values = function(context, values){
- var decoded_values = {};
- for (var key in this.fields) {
- var value = values[key];
- var field = this.fields[key];
- if (field === undefined){
- continue;
- }
- decoded_values[key] = field.decode_value(context, value);
+ return false;
+};
+ResourceType.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 Promise.props(decoded_values);
+ decoded_values[key] = field.decode(context, value);
}
- /**
- * Decodes an entry from datastorage
- * @param {Context} context
- * @param {Object} db_document - object representing encoded document from database
- * @returns {Promise} resolving with object represeting decoded resource
- */
- this.decode_db_entry = function(context, db_document){
- var id = db_document.sealious_id;
- var original_body = db_document.body;
+ return Promise.props(decoded_values);
+};
+ResourceType.prototype._format_decoded_values = function(context, decoded_values, format){
- return this.decode_values(context, original_body)
- .then(function(decoded_body){
- var ret = {
- id: id,
- type: db_document.type,
- body: decoded_body,
- created_context: db_document.created_context,
- last_modified_context: db_document.last_modified_context,
- }
- return Promise.resolve(ret);
+ 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(formatted_values);
+};
+ResourceType.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);
});
+ } else {
+ return decoded_values;
}
+};
+ResourceType.prototype.get_resource_representation = ResourceType.prototype.decode_db_entry = function(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.type_name = this.name;
+ representation.body = this._get_body(context, db_document, format);
+
+ return Promise.props(representation).then(function(res){
+ return res;
+ });
+};
+ResourceType.prototype.check_if_action_is_allowed = function(context, action_name, resource_representation){
+ const access_strategy = this.get_access_strategy(action_name);
-}
+ return access_strategy.check(context, resource_representation)
+ .then(function(results){
+ return results;
+ });
+};
-module.exports = ResourceType;
\ No newline at end of file
+module.exports = ResourceType;
diff --git a/lib/config/config-manager.js b/lib/config/config-manager.js
index d80ec0f2..f4421f4d 100644
--- a/lib/config/config-manager.js
+++ b/lib/config/config-manager.js
@@ -1,68 +1,60 @@
-var Sealious = require("../main.js");
-var fs = require("fs");
-var path = require("path");
-
-var merge = require("merge");
-
-var ConfigManager = new function(){
- var default_config = {};
- var config = {};
-
- function modify_config (is_default_config, key, value) {
- var key_elements = key.split('.');
- var new_values = {};
- var current_position = new_values;
- for (var i = 0; i < key_elements.length - 1; i++) {
- var current_key = key_elements[i];
- current_position[current_key] = {};
- current_position = current_position[current_key];
- }
- current_position[key_elements[key_elements.length - 1]] = value;
- if (is_default_config) {
- default_config = merge.recursive(true, default_config, new_values);
- } else {
- config = merge.recursive(true, config, new_values);
- }
+"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);
}
+}
- this.set_config = function(key, new_config){
- if (arguments.length === 1) {
- config = config;
+const ConfigManager = {
+ set_config: function(key, new_config){
+ if (arguments.length === 1){
+ // config = config;
} else {
modify_config(false, key, new_config);
}
- }
-
- this.set_default_config = function(key, value){
- if (arguments.length === 1) {
- default_config = default_config;
+ },
+ set_default_config: function(key, value){
+ if (arguments.length === 1){
+ // default_config = default_config;
} else {
modify_config(true, key, value);
}
- }
-
- this.get_configuration = function(key){
- var to_merge_left = default_config;
- var to_merge_right = config;
- var key_elements = key === undefined ? [] : key.split(".");
- while (key_elements.length) {
- var current_key = key_elements.splice(0, 1);
+ },
+ 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);
- }
-
- this.get_config = this.get_configuration;
-
- this.get_chip_config = function(longid){
+ },
+ get_chip_config: function(longid){
return config.chip_config && config.chip_config[longid];
- }
-
- this.get_dispatcher_config = function(){
+ },
+ get_dispatcher_config: function(){
return config.dispatcher_config || {};
}
+};
-}
+ConfigManager.get_config = ConfigManager.get_configuration;
-module.exports = ConfigManager;
\ No newline at end of file
+module.exports = ConfigManager;
diff --git a/lib/context.js b/lib/context.js
index cdb41cb6..50df556a 100644
--- a/lib/context.js
+++ b/lib/context.js
@@ -1,19 +1,76 @@
-var Immutable = require("immutable");
+"use strict";
+const locreq = require("locreq")(__dirname);
+const promisify = require("bluebird-events");
+const EventEmitter = require("events");
-function Context (timestamp, ip, user_id) {
- if (user_id === undefined) {
+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) {
- var d = new Date();
+
+ if (timestamp === undefined){
+ const d = new Date();
timestamp = d.getTime();
}
- var ret = Immutable.fromJS({
- timestamp: timestamp,
- ip: ip || null,
- user_id: user_id
- });
- return ret;
+
+ this.timestamp = timestamp;
+ this.ip = ip || null;
+ this.user_id = user_id;
}
-module.exports = Context;
\ No newline at end of file
+Context.prototype.get_user_data = function(){
+ 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")
+ .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
index 32d8ff64..93a2b32a 100644
--- a/lib/core-services/file-manager.js
+++ b/lib/core-services/file-manager.js
@@ -1,112 +1,110 @@
-var Promise = require("bluebird");
-var UUIDGenerator = require("uid");
-var path = require('path');
-var fse = require("fs-extra");
-var fs = require("fs");
-var ResourceRepresentation = require("../chip-types/resource-representation.js");
-var Sealious = require("../main.js");
+"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 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
*/
-var root_path = function(){
- var parent_tmp = module.parent;
- var parent = null;
- while (parent_tmp) {
+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;
-}
+};
-
-var FileManager = new function(upload_path){
- this.name = "files";
-
- if (!upload_path) {
+const FileManager = function(upload_path){
+ if (upload_path === undefined){
upload_path = "./uploaded_files/";
}
+ this.upload_path = upload_path;
+};
- var upload_path_abs = path.resolve(root_path(), "../" + upload_path);
-
- this.save_file = function(file, upload_path){
-
-
- if (!fs.existsSync(upload_path_abs)) {
- fse.mkdirs(upload_path_abs, function(err){});
- }
-
- var newID = UUIDGenerator(10);
-
-
- var upload_path_with_sealious_name = upload_path_abs + "/" + newID;
- fs.writeFile(upload_path_with_sealious_name, file.data, function(err, data){
- if (err) {
- throw (err);
- }
- });
-
- var file_database_entry = {
- original_name: file.filename,
- creation_context: file.context,
- id: newID,
- mime_type: file.mime,
- }
-
- return Sealious.Datastore.insert("files", file_database_entry, {})
- .then(function(){
- return Promise.resolve({
- id: newID,
- filename: file.filename
- });
- })
+FileManager.prototype.name = "files";
+FileManager.prototype.save_file = function(file){
- }
-
- this.diff = function(dispatcher, file){
+ // should be passed as an argument
+ const Datastore = ChipManager.get_datastore_chip();
- }
+ const upload_path_abs = path.resolve(root_path(), "../" + this.upload_path);
- this.get_list = function(dispatcher, owner){
- var query = {
- "body.owner": owner
- };
- Sealious.Logger.info("List for owner '" + owner + "' has been created");
- return this.find(dispatcher, query);
+ if (!fs.existsSync(upload_path_abs)){
+ fse.mkdirs(upload_path_abs, function(err){});
}
- this.find = function(context, query){
- return Sealious.Datastore.find("files", query)
- .then(function(documents){
- var parsed_documents = documents.map(function(document){
- var ret = Sealious.File.from_db_entry(document);
- ret.path_on_hdd = upload_path + ret.id;
- return ret;
- });
- return Promise.resolve(parsed_documents);
- })
- }
+ const newID = UUIDGenerator(10);
- this.change_name = function(dispatcher, sealious_name, new_name){
- return Sealious.Datastore.update("files", {
- sealious_id: sealious_name
- }, {
- $set: {
- "body.original_name": new_name
- }
+ const upload_path_with_sealious_name = upload_path_abs + "/" + newID;
+ fs.writeFile(upload_path_with_sealious_name, file.data, function(err, data){
+ if (err){
+ throw (err);
+ }
+ });
+
+ 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 Promise.resolve({
+ 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 = 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){
- }
-
- this.delete = function(dispatcher, query){
-
- }
-}
-
-
-//wersjonowanie, historia dostępu, przetrzymywanie poprzednich wersji
+};
+// wersjonowanie, historia dostępu, przetrzymywanie poprzednich wersji
-module.exports = FileManager;
\ No newline at end of file
+module.exports = new FileManager();
diff --git a/lib/core-services/resource-manager.js b/lib/core-services/resource-manager.js
deleted file mode 100644
index 94948540..00000000
--- a/lib/core-services/resource-manager.js
+++ /dev/null
@@ -1,288 +0,0 @@
-var Sealious = require("../main.js");
-var Promise = require("bluebird");
-var ResourceRepresentation = require("../chip-types/resource-representation.js");
-
-var assert = require("assert");
-
-var UUIDGenerator = require("uid");
-
-/**
- * Manages resources in the database
- * @class
- */
- var ResourceManager = new function(){
- this.name = "resources";
- var self = this;
-
- /**
- * Creates a resource of given type
- * @param {Context} context - context in which resource is being created
- * @param {String} type_name - name of created resource's type, defined in resource type declaration
- * @param {Object} body - data with which resource will be created wrapped in object, body.field_name should give us value of field "field_name"
- * @returns {Promise} which resolves with created object
- */
- this.create = function(context, type_name, body){
- return Promise.try(function(){
- var resource_type_object = Sealious.ChipManager.get_chip("resource_type", type_name);
- var access_strategy = resource_type_object.get_access_strategy("create");
-
- var old_values = {};
-
- if (resource_type_object.is_old_value_sensitive("is_proper_value")) {
- for (var i in resource_type_object.fields) {
- var field = resource_type_object.fields[i];
- old_values[field.name] = null;
- }
- }
-
- var encoded_body = {};
-
- var current_item;
- if (access_strategy.item_sensitive){
- current_item = null;
- } else {
- current_item = undefined;
- }
-
- return access_strategy.check(context, current_item)
- .then(function(){
- return resource_type_object.validate_field_values(context, true, body, old_values);
- }).then(function(){
- return resource_type_object.encode_field_values(context, body);
- }).then(function(response){
- encoded_body = response;
- var newID = UUIDGenerator(10);
- var resource_data = {
- sealious_id: newID,
- type: type_name,
- body: encoded_body,
- created_context: context.toObject(),
- };
- return Sealious.Datastore.insert("resources", resource_data, {});
- }).then(function(inserted_document){
- var database_entry = inserted_document;
- return resource_type_object.decode_db_entry(context, database_entry);
- })
- })
- }
- /**
- * Deletes resource of given id
- * @param {Context} context - context
- * @param {String} type_name - name of deleted resource's type, defined in resource type declaration
- * @param {String} id - id of particular resource, which you want to delete
- * @returns {Promise} witch resolves if resource had been successfully deleted
- */
- this.delete = function(context, type_name, id){
- return new Promise.try(function(){
- var resource_type_object = Sealious.ChipManager.get_chip("resource_type", type_name);
- var access_strategy = resource_type_object.get_access_strategy("delete");
- return access_strategy.check(context)
- .then(function(){
- return Sealious.Datastore.find("resources", {
- sealious_id: id
- }, {})
- .then(function(documents){
- if (documents[0] === undefined) {
- return Promise.reject(new Sealious.Errors.NotFound("resource of id " + id + " not found"));
- } else {
- return Sealious.Datastore.remove("resources", {sealious_id: id, type: type_name}, {});
- }
- })
- })
- .then(function(data){
- return Promise.resolve();
- });
- })
- }
- /**
- * Gets a resource of given id
- * @param {Context} context - context
- * @param {String} resource_id - id of particular resource
- * @returns {Promise} which resolves with object representing resource, or rejects if resource with given id is not find
- */
- this.get_by_id = function(context, resource_id){
- return Promise.try(function(){
- //var access_strategy = resource_type_object.get_access_strategy("get_by_id");
-
- return Sealious.Datastore.find("resources", {
- sealious_id: resource_id
- }, {})
- .then(function(documents){
- if (documents[0] === undefined) {
- return Promise.reject(new Sealious.Errors.NotFound("resource of id " + resource_id + " not found"));
- } else {
- var database_entry = documents[0];
- var resource_type_name = database_entry.type;
- var resource_type_object = Sealious.ChipManager.get_chip("resource_type", resource_type_name);
- var ret = [];
- ret[0] = resource_type_object;
- ret[1] = resource_type_object.decode_db_entry(context, database_entry);
- return Promise.all(ret);
- }
- })
- .then(function(response){
- var resource_type = response[0];
- var resource_data = response[1];
- var access_strategy = resource_type.get_access_strategy("retrieve");
- return access_strategy.check(context, resource_data);
- })
- })
- }
- /**
- * is used to filter in item sensitive access strategies. Returns a function that can be used with Promise.filter
- * @param {Context} context - context in which resource is being created
- * @param {} access_strategy -
- */
- function filter_resource_list (context, access_strategy) {
- return function(item){
- return new Promise(function(resolve, reject){
- access_strategy.check(context, item)
- .then(function(){
- resolve(true);
- }).catch(function(){
- resolve(false);
- })
- });
- }
- }
- /**
- * Returns list of resources of given type
- * @param {Context} context - context in which resource is being created
- * @param {String} type_name - name of resource type, defined in resource type declaration
- * @returns {Promise} which resolves with array of objects, representing resources of given type
- */
- this.list_by_type = function(context, type_name){
- return Promise.try(function(){
- var resource_type = Sealious.ChipManager.get_chip("resource_type", type_name);
- var access_strategy = resource_type.get_access_strategy("retrieve");
- var preliminary_access_strategy_check;
- if (access_strategy.item_sensitive){
- preliminary_access_strategy_check = Promise.resolve();
- } else {
- preliminary_access_strategy_check = access_strategy.check(context);
- }
-
- var get_items = preliminary_access_strategy_check.then(function(){
- return Sealious.Datastore.find("resources", {
- type: type_name
- }, {}, {});
- });
-
- var decoded_items = get_items.map(resource_type.decode_db_entry.bind(resource_type, context));
-
- var filtered_items;
- if (access_strategy.item_sensitive){
- filtered_items = decoded_items.then(function(items){
- return Promise.filter(items, filter_resource_list(context, access_strategy));
- });
- } else {
- filtered_items = decoded_items;
- }
- return filtered_items;
- })
- }
- /**
- * Returns list of resources, which match given restriction
- * @param {Context} context - context in which resource is being created
- * @param {Object} field_values - object representing our query ex. field_values.name = "cup" will find all resources, which field name has value "cup"
- * @param {String} type - name of resource type, defined in resource type declaration
- * @returns {Promise} which resolves with array of founded objects
- */
- this.find = function(context, field_values, type){
- var find_arguments = arguments;
- return Promise.try(function(){
- //throw new Error("ResourceManager.find not implemented.");
- if (find_arguments.length === 2) {
- type = null;
- }
- var query = {};
- if (type){
- query.type = type;
- }
- for (var field_name in field_values){
- query["body." + field_name] = field_values[field_name];
- }
- return Sealious.Datastore.find("resources", query)
- .then(function(documents){
- var parsed_documents = documents.map(function(document){
- return new ResourceRepresentation(document).getData()
- });
- return Promise.resolve(parsed_documents);
- });
- })
-
- }
- /**
- * Replaces just the provided values. Equivalent of PATCH request
- * @param {Context} context - context in which resource is being created
- * @param {String} type_name - name of resource type, defined in resource type declaration
- * @param {Object} field_values - object representing our query ex. field_values.name = "cup" will find all resources, which field name has value "cup"
- * @param consider_empty_values - if set to true, values from values_to_patch will be deleted. Defaults to false.
- *
- * @returns {Promise} which resolves with array of founded objects
- */
- this.patch_resource = function(context, type_name, resource_id, values_to_patch, consider_empty_values){
- return Promise.try(function(){
- var access_strategy;
- var get_item;
- if (consider_empty_values === undefined){
- consider_empty_values = false;
- }
- //replaces just the provided values. Equivalent of PATCH request
- var resource_type_object = Sealious.ChipManager.get_chip("resource_type", type_name);
- access_strategy = resource_type_object.get_access_strategy();
- if (access_strategy.item_sensitive || resource_type_object.is_old_value_sensitive()){
- get_item = self.get_by_id(context, resource_id);
- } else {
- get_item = Promise.resolve({
- body: {}
- });
- }
-
- return get_item.then(function(item){
- return access_strategy.check(context, item);
- }).then(function(current_resource){
- var old_values = current_resource.body;
- return resource_type_object.validate_field_values(context, consider_empty_values, values_to_patch, old_values)
- .then(function(){
- return Promise.resolve(old_values);
- })
- }).then(function(old_values){
- return resource_type_object.encode_field_values(context, values_to_patch, old_values && old_values.body);
- }).then(function(encoded_values){
- var query = {};
- query.last_modified_context = context.toObject();
- for (var field_name in encoded_values){
- query["body." + field_name] = encoded_values[field_name];
- }
- if (Object.keys(query).length === 0){
- return Promise.resolve();
- } else {
- return Sealious.Datastore.update("resources", {
- sealious_id: resource_id
- }, {
- $set: query
- })
- }
- }).then(function(){
- return self.get_by_id(context, resource_id);
- });
- })
- }
-
- this.update_resource = function(context, type_name, resource_id, body){
- return Promise.try(function(){
- var type = Sealious.ChipManager.get_chip("resource_type", type_name);
- for (var i in type.fields) {
- var field = type.fields[i];
- if (!body.hasOwnProperty(field.name)) {
- body[field.name] = undefined;
- }
- }
- return self.patch_resource(context, type_name, resource_id, body, true);
- })
- }
- }
-
-
- module.exports = ResourceManager;
diff --git a/lib/core-services/user_manager.js b/lib/core-services/user_manager.js
deleted file mode 100644
index eafda546..00000000
--- a/lib/core-services/user_manager.js
+++ /dev/null
@@ -1,99 +0,0 @@
-var Sealious = require("../main.js");
-var Promise = require("bluebird");
-
-module.exports = new function(){
- this.name = "users";
-
- this.create_user = function(context, username, password){
- var user_data;
- return Sealious.UserManager.user_exists(context, username)
- .then(function(user_exists){
- if (!user_exists) {
- Sealious.Logger.info("User " + username + " has been created");
- return Sealious.ResourceManager.create(context, "user", {
- username: username,
- password: password
- });
- } else {
- throw new Sealious.Errors.ValueExists("Username `" + username + "` is already taken.");
- }
- })
- }
-
- this.user_exists = function(context, username){
- return new Promise(function(resolve, reject){
- Sealious.ResourceManager.find(context, {
- username: username
- }, "user")
- .then(function(matched_documents){
- resolve(matched_documents.length === 1);
- });
- })
- }
-
- this.password_match = function(context, username, password){
- return new Promise(function(resolve, reject){
- var err;
- if (!username && !password) {
- err = new Sealious.Errors.InvalidCredentials("Missing username and password!");
- reject(err);
- } else if (!password) {
- err = new Sealious.Errors.InvalidCredentials("Missing password!");
- reject(err);
- } else if (!username) {
- err = new Sealious.Errors.InvalidCredentials("Missing username!");
- reject(err);
- } else {
- var query = {
- type: "user",
- body: {
- username: username,
- password: password
- }
- };
- Sealious.Datastore.find("resources", query)
- .then(function(result){
- if (result[0]) {
- resolve(result[0].sealious_id);
- } else {
- var err = new Sealious.Errors.InvalidCredentials("Wrong username or password!");
- reject(err);
- }
- })
- }
- })
- }
-
- this.get_all_users = function(context){
- return Sealious.Datastore.find("resources", {
- type: "user"
- });
- }
-
- this.get_user_data = function(context, user_resource_id){
- var ret;
- try {
- ret = Sealious.ResourceManager.get_by_id(context, user_resource_id);
- } catch (err) {
- throw err;
- }
- return ret;
- }
-
- this.update_user_data = function(context, user_id, new_user_data){
- return Sealious.ResourceManager.update_resource(user_id, new_user_data);
- }
-
- this.delete_user = function(context, user_id){
- return new Promise(function(resolve, reject){
- Sealious.Datastore.delete("resources", {
- sealious_id: user_id
- })
- .then(function(data){
- resolve(data);
- }).catch(function(e){
- reject(e);
- });
- });
- }
-}
\ No newline at end of file
diff --git a/lib/core.js b/lib/core.js
index 691b960e..f25ad240 100644
--- a/lib/core.js
+++ b/lib/core.js
@@ -1,49 +1,55 @@
-var Sealious = require("./main.js");
-var http = require("http");
+"use strict";
+const Sealious = require("./main.js");
+const http = require("http");
-var ConfigManager = require("./config/config-manager.js");
+const ConfigManager = require("./config/config-manager.js");
-var SealiousCore = new function(){
+const SealiousCore = new function(){
this.check_version = function(package_info){
- var pkg = require("../package.json")
- var pkg_split = pkg.version.split(".");
- var version = pkg_split[0] + "." + pkg_split[1];
- var url = "http://registry.npmjs.org/sealious/" + version;
-
- var check_request = http.get(url, function(res){
- res.setEncoding('utf8');
- var body = "";
- res.on('data', function(chunk){
+ 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();
});
- var sealious_npm;
- res.on('end', function(){
+ let sealious_npm;
+ res.on("end", function(){
try {
sealious_npm = JSON.parse(body);
- } catch (error) {
+ } 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 || !sealious_npm.version){
+ } else if (!sealious_npm.version || sealious_npm === undefined){
Sealious.Logger.warning("unknown npm registry error when requesting info for version " + version + ".");
} else {
- var sealious_npm_array = sealious_npm.version.split(".");
+ const sealious_npm_array = sealious_npm.version.split(".");
- if ((sealious_npm.version !== pkg.version) && (parseInt(sealious_npm_array[2]) > parseInt(pkg_split[2]))) {
+ 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){
+ 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;
\ No newline at end of file
+module.exports = SealiousCore;
diff --git a/lib/data-structures/field-type-description.js b/lib/data-structures/field-type-description.js
index e1a5f4c6..f0680a6f 100644
--- a/lib/data-structures/field-type-description.js
+++ b/lib/data-structures/field-type-description.js
@@ -1,7 +1,10 @@
-var FieldTypeDescription = function(summary, raw_params, extra_info){
+"use strict";
+"use strict";
+
+const FieldTypeDescription = function(summary, raw_params, extra_info){
this.summary = summary;
this.raw_params = raw_params;
this.extra_info = extra_info || {};
-}
+};
-module.exports = FieldTypeDescription;
\ No newline at end of file
+module.exports = FieldTypeDescription;
diff --git a/lib/data-structures/file.js b/lib/data-structures/file.js
index cfcafebc..39ffc66b 100644
--- a/lib/data-structures/file.js
+++ b/lib/data-structures/file.js
@@ -1,33 +1,34 @@
-var Sealious = require("../main.js");
-var Promise = require("bluebird");
+"use strict";
+const locreq = require("locreq")(__dirname);
-function File (creation_context, filename, data, id, mime) {
+const FileManager = locreq("lib/core-services/file-manager.js");
+const Promise = require("bluebird");
+
+function File (creation_context, filename, data, id, mime){
this.filename = filename;
this.data = data;
this.id = id || null;
this.mime = mime || false;
}
File.from_id = function(context, file_id){
- return Sealious.FileManager.find(context, {
- id: 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, upload_path){
+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 = new function(){
- this.data_structure = "file";
-}
+File.prototype.data_structure = "file";
File.Reference = function(id, filename){
this.id = id;
this.filename = filename;
-}
+};
-module.exports = File;
\ No newline at end of file
+module.exports = File;
diff --git a/lib/data-structures/subject-path.js b/lib/data-structures/subject-path.js
new file mode 100644
index 00000000..4dd18b1f
--- /dev/null
+++ b/lib/data-structures/subject-path.js
@@ -0,0 +1,47 @@
+"use strict";
+
+const clone = require("clone");
+
+const SubjectPath = function(subject_path){
+ if (SubjectPath instanceof SubjectPath){
+ return SubjectPath;
+ }
+
+ this.elements = [];
+ this.subject_type_instance = null;
+
+ this._init(subject_path);
+};
+SubjectPath.prototype._init = function(subject_path){
+ this._load_path_elements(subject_path);
+};
+SubjectPath.prototype._load_path_elements = function(subject_path){
+ if (subject_path instanceof SubjectPath){
+ this._from_path(subject_path);
+ } else if (typeof subject_path === "string"){
+ this._from_string(subject_path);
+ } else if (subject_path instanceof Array){
+ this._from_array(subject_path);
+ }
+};
+SubjectPath.prototype._from_string = function(description_string){
+ this.elements = description_string.split(".");
+};
+SubjectPath.prototype._from_array = function(description_array){
+ this.elements = clone(description_array);
+};
+SubjectPath.prototype._from_path = function(subject){
+ this.elements = clone(subject.elements);
+};
+SubjectPath.prototype.clone = function(){
+ const cloned_elements = clone(this.elements);
+ return new SubjectPath(cloned_elements);
+};
+SubjectPath.prototype.tail = function(){
+ return new SubjectPath(this.elements.slice(1));
+};
+SubjectPath.prototype.head = function(){
+ return this.elements[0];
+};
+
+module.exports = SubjectPath;
diff --git a/lib/data-structures/virtual-file.js b/lib/data-structures/virtual-file.js
new file mode 100644
index 00000000..c6696655
--- /dev/null
+++ b/lib/data-structures/virtual-file.js
@@ -0,0 +1,9 @@
+"use strict";
+"use strict";
+
+const VirtualFile = function(content, mime){
+ this.content = content;
+ this.mime = mime || "text/plain";
+};
+
+module.exports = VirtualFile;
diff --git a/lib/logger/logger.js b/lib/logger/logger.js
index 59bb919e..a3ff3bd3 100644
--- a/lib/logger/logger.js
+++ b/lib/logger/logger.js
@@ -1,149 +1,148 @@
-var Sealious = require("../main.js");
-var winston = require('winston');
-var ConfigManager = Sealious.ConfigManager;
+"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_level - specifies from which log level (displayed below) onward should be displayed,
@logger_color - specifies if the log should be colorized, values "true" or "false"
@logger_file - defines a filename to save the logs, if a falsy value is given the logs will not be saved,
@logger_dirname - defines a default path to save the logs,
@logger_to_json - specifies the format of the saved logs,
@logger_rotation - defines the log rotation format, set to daily by default
*/
ConfigManager.set_default_config(
"logger_config", {
logger_level: "info",
logger_color: true,
logger_file: null,
logger_dirname: ".",
logger_to_json: false,
- logger_rotation: '.yyyy-MM-Tdd'
+ logger_rotation: ".yyyy-MM-Tdd",
});
/*
This is the custom logger level and color configuration.
@levels - default logger levels, 0 being the lowest importance, 4 being the highest:
* lazyseal - an Easter, or should we say: Sealious egg. Used only for humorous reasons, the lowest level of importance, default color: white,
* info - used for stating the current status or general information such as starting the server, default color: green,
* debug - used for debugging, default color: blue,
* warning - used to display warnings, default color: yellow,
* error - used to display errors, default color: red
-
+
*/
-var custom = {
+const custom = {
levels: {
lazyseal: 0,
info: 1,
debug: 2,
warning: 3,
error: 4,
- no_output: 5
+ no_output: 5,
},
colors: {
lazyseal: "white",
info: "green",
- debug: 'blue',
- warning: 'yellow',
- error: 'red'
- }
+ 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"
+ Returns the current date and time, default format: "yyyy-mm-dd hh:mm:ss.mmm", ex. "2000-01-01 20:00:00.000"
*/
-function getDateTime (with_date) {
-
- var date = new Date();
+function getDateTime (with_date){
+ const date = new Date();
- var hour = date.getHours();
+ let hour = date.getHours();
hour = (hour < 10 ? "0" : "") + hour;
- var min = date.getMinutes();
+ let min = date.getMinutes();
min = (min < 10 ? "0" : "") + min;
- var sec = date.getSeconds();
+ let sec = date.getSeconds();
sec = (sec < 10 ? "0" : "") + sec;
- var milli = date.getMilliseconds();
+ let milli = date.getMilliseconds();
milli = (milli < 10 ? "00" : "") + milli;
milli = (milli < 100 && milli >= 10 ? "0" : "") + milli;
- var year = date.getFullYear();
+ const year = date.getFullYear();
- var month = date.getMonth() + 1;
+ let month = date.getMonth() + 1;
month = (month < 10 ? "0" : "") + month;
- var day = date.getDate();
+ let day = date.getDate();
day = (day < 10 ? "0" : "") + day;
- if (!with_date) {
+ if (!with_date){
return hour + ":" + min + ":" + sec + "." + milli;
} else {
return year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + sec + "." + milli;
}
-
}
-var transports_array = [];
+const transports_array = [];
-var logger_level = ConfigManager.get_config().logger_config.logger_level;
-var logger_color = ConfigManager.get_config().logger_config.logger_color;
-var logger_file = ConfigManager.get_config().logger_config.logger_file;
-var logger_dirname = ConfigManager.get_config().logger_config.logger_dirname;
-var logger_to_json = ConfigManager.get_config().logger_config.logger_to_json;
-var logger_rotation = ConfigManager.get_config().logger_config.logger_rotation;
+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;
-var winston_level = new(winston.transports.Console)({
+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) {
- var winston_save_to_file = new(winston.transports.File)({
+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
+ json: logger_to_json,
});
- var winston_daily_rotate = new(winston.transports.DailyRotateFile)({
+ const winston_daily_rotate = new(winston.transports.DailyRotateFile)({
filename: logger_file,
- datePattern: logger_rotation
+ datePattern: logger_rotation,
});
transports_array.push(winston_save_to_file);
transports_array.push(winston_daily_rotate);
}
-var logger = new winston.Logger({
+const logger = new winston.Logger({
levels: custom.levels,
colors: custom.colors,
- transports: transports_array
+ transports: transports_array,
});
logger.rewriters.push(function(level, msg, meta){
- if (Object.keys(meta).length) {
- var message = "\n";
- for (var prop in meta){
- message += " - " + prop + ": " + meta[prop] + "\n";
+ 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;
\ No newline at end of file
+module.exports = logger;
diff --git a/lib/main.js b/lib/main.js
index f2ec51d5..f72554b9 100644
--- a/lib/main.js
+++ b/lib/main.js
@@ -1,51 +1,61 @@
-var path = require("path");
-
-var Sealious = {};
+"use strict";
+const Sealious = {};
module.exports = Sealious;
-var Core = require("./core.js");
+const Core = require("./core.js");
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.Logger = require("./logger/logger.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.ResourceManager = require("./core-services/resource-manager.js");
-Sealious.UserManager = require("./core-services/user_manager.js");
Sealious.FileManager = require("./core-services/file-manager.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"),
- "ResourceType": require("./chip-types/resource-type.js"),
-}
+ "ResourceType": require("./chip-types/resource-type.js")
+};
// prefix Sealious.ChipTypes[chip_type_name] to Sealious[chip_type_name]
-for (var chip_type_name in Sealious.ChipTypes) {
- if (chip_type_name === 'Datastore'){
- chip_type_name += 'Creator';
+for (let chip_type_name in Sealious.ChipTypes){
+ if (chip_type_name === "Datastore"){
+ chip_type_name += "Creator";
}
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();
-}
+};
module.exports = Sealious;
diff --git a/lib/misc/me-synonyms.json b/lib/misc/me-synonyms.json
new file mode 100644
index 00000000..0428d9b0
--- /dev/null
+++ b/lib/misc/me-synonyms.json
@@ -0,0 +1 @@
+["me", "myself", "current"]
diff --git a/lib/plugins/plugin-manager.js b/lib/plugins/plugin-manager.js
index 0ec16f19..7108015b 100644
--- a/lib/plugins/plugin-manager.js
+++ b/lib/plugins/plugin-manager.js
@@ -1,63 +1,79 @@
-var Sealious = require("../main.js");
-var path = require("path");
-var fs = require("fs");
-var resolve = require("resolve");
-
-var PluginManager = new function(){
-
- function get_package_info_path (dir, package_name) {
- var package_path = resolve.sync(package_name, { basedir: dir });
- var package_info_path = null;
- while (package_info_path === null){
- var 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;
- }
+"use strict";
+const locreq = require("locreq")(__dirname);
+const path = require("path");
+const fs = require("fs");
+const resolve = require("resolve");
- function get_package_info (dir, package_name) {
- return require(get_package_info_path(dir, package_name));
+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 is_sealious_plugin (dir, module_name) {
- var plugin_package_info = get_package_info(dir, module_name);
- return plugin_package_info.keywords && plugin_package_info.keywords.indexOf("sealious-plugin") !== -1;
+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 load_plugins_from_dir (dir) {
- var root = path.resolve(dir);
- var pkgfile = path.join(root, 'package.json');
- var pkg = require(pkgfile);
-
- var dependencies = pkg.dependencies;
- var required_sealious_plugins = Object.keys(dependencies).filter(is_sealious_plugin.bind({}, root));
-
- if (required_sealious_plugins.length){
- Sealious.Logger.debug(`${pkg.name} (${pkgfile}) requires: ${required_sealious_plugins.join(", ")}`)
- for (var i in required_sealious_plugins){
- var plugin_name = required_sealious_plugins[i];
- var plugin_info_path = get_package_info_path(root, plugin_name);
- var plugin_dir = path.resolve(plugin_info_path, "../");
- load_plugins_from_dir(plugin_dir);
- require(resolve.sync(plugin_name, {basedir: root}));
- Sealious.Logger.info(`\t\u2713 ${plugin_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 = path.join(root, "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)`);
}
}
}
-
- this.load_plugins = function(){
- Sealious.Logger.info("Loading plugins...");
- var sealious_dir = path.resolve(module.filename, "../../../");
+}
+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 04bf6b14..fc206338 100644
--- a/lib/response/error.js
+++ b/lib/response/error.js
@@ -1,120 +1,81 @@
-var Response = require("./response.js");
+"use strict";
+const Response = require("./response.js");
-var SealiousErrors = {};
+const SealiousErrors = {};
SealiousErrors.Error = function(message, params, data){
- var ret = new Error(message);
params = params || {};
- ret.is_sealious_error = true;
- ret.status_message = message;
- ret.is_error = true;
- ret.is_user_fault = params.is_user_fault === undefined ? false : params.is_user_fault;
- ret.is_developer_fault = params.is_developer_fault === undefined ? false : params.is_developer_fault;
- ret.type = params.type === undefined ? "error" : params.type;
- ret.http_code = params.http_code === undefined ? 500 : params.http_code;
- ret.data = data || params.data || {};
+ 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 || {};
- return ret;
-}
-
-SealiousErrors.ValidationError = function(message, data){
- var err = new SealiousErrors.Error(message, {}, data);
- err.status_message = message;
- err.is_user_fault = true;
- err.type = "validation";
- err.http_code = 403;
- return err;
-}
-
-SealiousErrors.ValueExists = function(message, data){
- var err = new SealiousErrors.Error(message, {}, data);
- err.status_message = message;
- err.is_user_fault = true;
- err.type = "valueExists";
- err.http_code = 409;
- return err;
-}
-
-SealiousErrors.InvalidCredentials = function(message, data){
- var err = new SealiousErrors.Error(message, {}, data);
- err.status_message = message;
- err.is_user_fault = true;
- err.type = "authorization";
- err.http_code = 401;
- return err;
-}
+ Error.captureStackTrace(this, SealiousErrors.Error);
+};
-SealiousErrors.NotFound = function(message, data){
- var err = new SealiousErrors.Error(message, {}, data);
- err.status_message = message;
- err.is_user_fault = true;
- err.type = "not_found";
- err.http_code = 404;
- return err;
-}
-
-SealiousErrors.InternalConnectionError = function(message, data){
- var err = new SealiousErrors.Error(message, {}, data);
- err.status_message = message;
- err.is_user_fault = false;
- err.type = "internal_connection_error";
- err.http_code = 500;
- return err;
-}
+SealiousErrors.Error.prototype = Object.create(Error.prototype);
+SealiousErrors.Error.prototype.constructor = SealiousErrors.Error;
-SealiousErrors.DependencyError = function(message, data){
- var err = new SealiousErrors.Error(message, {}, data);
- err.status_message = message;
- err.is_user_fault = false;
- err.is_developer_fault = true;
- err.type = "dependency_error";
- err.http_code = 500;
- return err;
-}
+SealiousErrors.Error.prototype.to_object = function(){
+ return {
+ message: this.message,
+ type: this.type,
+ data: this.data,
+ };
+};
-SealiousErrors.UnauthorizedRequest = function(message, data){
- var err = new SealiousErrors.Error(message, {}, data);
- err.status_message = message;
- err.is_user_fault = true;
- err.type = "unauthorized_request";
- err.http_code = 401;
- return err;
-}
-
-SealiousErrors.DeveloperError = function(message, data){
- var err = new SealiousErrors.Error(message, {}, data);
- err.status_message = message;
- err.is_user_fault = false;
- err.is_developer_fault = true;
- err.type = "dev_error";
- return err;
-}
+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",
+ },
+};
-SealiousErrors.BadContext = function(message, data){
- var err = new SealiousErrors.Error(message, {}, data);
- err.status_message = message;
- err.is_user_fault = true;
- err.type = "permission";
- err.http_code = 401;
- return err;
+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];
}
-/*
-process.on('uncaughtException', function (exception) {
- switch(exception.code){
- case "EACCES":
- console.log("\nNo root access - closing!\n");
- process.exit();
- break;
- case "EADDRINUSE":
- console.log("\nPort 80 is already taken - closing!\n");
- process.exit();
- break;
- default:
- console.log(exception.stack);
- throw exception;
- break;
- }
-});
-*/
-module.exports = SealiousErrors;
\ No newline at end of file
+module.exports = SealiousErrors;
diff --git a/lib/response/response.js b/lib/response/response.js
index 69f7f10b..e886524f 100644
--- a/lib/response/response.js
+++ b/lib/response/response.js
@@ -1,17 +1,21 @@
-function Response (data, is_error, type, status_message) {
+"use strict";
+"use strict";
+
+function Response (data, is_error, type, status_message){
this.status = is_error ? "error" : "success";
this.type = type || "response";
this.status_message = status_message || "ok";
this.data = data || {};
}
Response.fromError = function(sealious_error){
return {
data: sealious_error.data || {},
is_error: true,
type: sealious_error.type,
- status_message: sealious_error.status_message,
+ status_message: sealious_error.message,
+ message: sealious_error.message,
};
-}
+};
-module.exports = Response;
\ No newline at end of file
+module.exports = Response;
diff --git a/lib/response/responses.js b/lib/response/responses.js
new file mode 100644
index 00000000..76fc69fb
--- /dev/null
+++ b/lib/response/responses.js
@@ -0,0 +1,13 @@
+"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 = {};
+};
+
+module.exports = SealiousResponses;
diff --git a/lib/subject/predefined-subjects/me-subject.js b/lib/subject/predefined-subjects/me-subject.js
new file mode 100644
index 00000000..a82059b2
--- /dev/null
+++ b/lib/subject/predefined-subjects/me-subject.js
@@ -0,0 +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(){
+ this.perform_action = function(context, action_name, params){
+ return context.run_action(["resources", "user", 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();
diff --git a/lib/subject/predefined-subjects/resources-subject.js b/lib/subject/predefined-subjects/resources-subject.js
new file mode 100644
index 00000000..e630a468
--- /dev/null
+++ b/lib/subject/predefined-subjects/resources-subject.js
@@ -0,0 +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 ResourceTypeCollection = require("../subject-types/resource-type-collection-subject.js");
+
+const ResourcesSubject = function(){
+
+ this.resource_collections = null;
+
+ this._initialize_resource_collections = function(){
+ this.resource_collections = {};
+ const resource_types = ChipManager.get_chips_by_type("resource_type");
+ for (const resource_type_name in resource_types){
+ const resource_type = resource_types[resource_type_name];
+ this.resource_collections[resource_type_name] = new ResourceTypeCollection(resource_type);
+ }
+ };
+
+ 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}'.`);
+ }
+ 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.");
+ };
+};
+
+ResourcesSubject.prototype = Object.create(Subject.prototype);
+
+module.exports = new ResourcesSubject();
diff --git a/lib/subject/predefined-subjects/root-subject.js b/lib/subject/predefined-subjects/root-subject.js
new file mode 100644
index 00000000..4fa24261
--- /dev/null
+++ b/lib/subject/predefined-subjects/root-subject.js
@@ -0,0 +1,34 @@
+"use strict";
+const locreq = require("locreq")(__dirname);
+
+const Errors = locreq("lib/response/error.js");
+const Subject = locreq("lib/subject/subject.js");
+
+const ResourcesSubject = require("./resources-subject.js");
+const UsersSubject = require("./users-subject.js");
+const SessionsSubject = require("./sessions-subject.js");
+const UploadedFilesSubject = require("./uploaded-files.js");
+
+const RootSubject = function(){
+
+ this.name = "Root";
+
+ this.get_child_subject = function(key){
+ switch (key){
+ case "resources":
+ return ResourcesSubject;
+ case "users":
+ return UsersSubject;
+ case "sessions":
+ return SessionsSubject;
+ case "uploaded-files":
+ return UploadedFilesSubject;
+ default:
+ throw new Errors.BadSubjectPath(`No child subject with key '${key}' in RootSubject`);
+ }
+ };
+};
+
+RootSubject.prototype = Object.create(Subject.prototype);
+
+module.exports = new RootSubject();
diff --git a/lib/subject/predefined-subjects/sessions-subject.js b/lib/subject/predefined-subjects/sessions-subject.js
new file mode 100644
index 00000000..0fba4cf2
--- /dev/null
+++ b/lib/subject/predefined-subjects/sessions-subject.js
@@ -0,0 +1,113 @@
+"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"],
+ "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){
+ let username, password;
+ 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)
+ .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);
+ });
+ });
+}
+
+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(){
+
+ 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);
+ 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);
+ default:
+ throw new Errors.BadSubjectPath(`No child subject with key '${key}' in SessionSubject`);
+ }
+ };
+
+};
+
+SessionsSubject.prototype = Object.create(Subject.prototype);
+
+module.exports = new SessionsSubject();
diff --git a/lib/subject/predefined-subjects/uploaded-files.js b/lib/subject/predefined-subjects/uploaded-files.js
new file mode 100644
index 00000000..e71cbb48
--- /dev/null
+++ b/lib/subject/predefined-subjects/uploaded-files.js
@@ -0,0 +1,24 @@
+"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(){
+
+ this.get_child_subject = function(key){
+ const file_id = key;
+ return Promise.resolve(new SingleFileSubject(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();
diff --git a/lib/subject/predefined-subjects/users-subject.js b/lib/subject/predefined-subjects/users-subject.js
new file mode 100644
index 00000000..973b6d2f
--- /dev/null
+++ b/lib/subject/predefined-subjects/users-subject.js
@@ -0,0 +1,46 @@
+"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(){
+ this.perform_action = function(context, action_name, params){
+ params = params || {};
+ switch (action_name){
+ case "create":
+ return context.run_action(["resources", "user"], "create", params);
+ case "show":
+ return context.run_action(["resources", "user"], "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;
+ } else {
+ const username = key;
+ return new SuperContext().run_action(["resources", "user"], "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]);
+ }
+ });
+ }
+ };
+};
+
+UsersSubject.prototype = Object.create(Subject.prototype);
+
+module.exports = new UsersSubject();
diff --git a/lib/subject/subject-types/current-session-subject.js b/lib/subject/subject-types/current-session-subject.js
new file mode 100644
index 00000000..c1e99bba
--- /dev/null
+++ b/lib/subject/subject-types/current-session-subject.js
@@ -0,0 +1,29 @@
+"use strict";
+const locreq = require("locreq")(__dirname);
+const Promise = require("bluebird");
+
+const Response = locreq("lib/response/response.js");
+const Errors = locreq("lib/response/error.js");
+const Subject = locreq("lib/subject/subject.js");
+
+const CurrentSession = function(all_sessions){
+ this.all_sessions = all_sessions;
+};
+
+CurrentSession.prototype = Object.create(Subject);
+
+CurrentSession.prototype.perform_action = function(context, action_name, args){
+ switch (action_name){
+ case "delete":
+ if (this.all_sessions[context.session_id]){
+ delete this.all_sessions[context.session_id];
+ return Promise.resolve(new Response({}, false, "logged_out", "You've been logged out"));
+ } else {
+ return Promise.reject(new Errors.BadContext("Invalid session id!"));
+ }
+ default:
+ throw new Errors.DeveloperError(`Unknown action ${action_name} for CurrentSession subject.`);
+ }
+};
+
+module.exports = CurrentSession;
diff --git a/lib/subject/subject-types/resource-type-collection-subject.js b/lib/subject/subject-types/resource-type-collection-subject.js
new file mode 100644
index 00000000..5e1b009a
--- /dev/null
+++ b/lib/subject/subject-types/resource-type-collection-subject.js
@@ -0,0 +1,190 @@
+"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 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 ResourceTypeCollection = function(resource_type){
+ this.resource_type = resource_type;
+ this.name = "ResourceTypeCollection";
+};
+
+ResourceTypeCollection.prototype = Object.create(Subject.prototype);
+
+ResourceTypeCollection.prototype.__create_resource = function(datastore, resource_type, context, body){
+ return resource_type.check_if_action_is_allowed(context, "create")
+ .then(function(){
+ return resource_type.validate_field_values(context, true, body);
+ }).then(function(){
+ return resource_type.encode_field_values(context, body);
+ }).then(function(encoded_body){
+ const newID = UUIDGenerator(10);
+ const resource_data = {
+ sealious_id: newID,
+ type: resource_type.name,
+ body: encoded_body,
+ created_context: context,
+ last_modified_context: context,
+ };
+ return datastore.insert("resources", resource_data, {});
+ }).then(function(database_entry){
+ return resource_type.get_resource_representation(context, database_entry);
+ });
+};
+
+ResourceTypeCollection.prototype.create_resource = function(context, body){
+ const self = this;
+ return ResourceTypeCollection.prototype.__create_resource(ChipManager.get_datastore_chip(), self.resource_type, context, body);
+};
+
+ResourceTypeCollection.prototype.__preprocess_resource_filter = function(resource_type, context, filter){
+ filter = clone(filter) || {};
+ const expanded_filter = expandHash(filter);
+ const processed_filter = {};
+ for (const field_name in expanded_filter){
+ if (resource_type.fields[field_name]){
+ const field = resource_type.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(resource_type, 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;
+};
+
+ResourceTypeCollection.prototype.__list_resources = function(datastore, resource_type, context, params){
+ if (params === undefined || params === null){
+ params = {};
+ }
+
+ const access_strategy = resource_type.get_access_strategy("retrieve");
+ let decoded_items;
+
+ const output_options = get_output_options(this.resource_type, params);
+
+ return resource_type.check_if_action_is_allowed(context, "retrieve")
+ .then(function(){
+ return ResourceTypeCollection.prototype.__preprocess_resource_filter(resource_type, context, params.filter);
+ }).then(function(body_filter){
+ const query = {
+ type: resource_type.name,
+ body: body_filter,
+ };
+
+ if (params.search){
+ query.$text = {
+ $search: params.search.toString(),
+ $caseSensitive: false,
+ $diacriticSensitive: false,
+ };
+ }
+
+ return datastore.find("resources", query, {}, output_options);
+ })
+ .map(function(db_document){
+ return resource_type.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;
+ }
+ });
+};
+
+ResourceTypeCollection.prototype.list_resources = function(context, params){
+ const datastore = ChipManager.get_datastore_chip();
+ const self = this;
+ return ResourceTypeCollection.prototype.__list_resources(datastore, self.resource_type, context, params);
+};
+
+ResourceTypeCollection.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.resource_type.name + "' collection: '" + action_name + "'");
+ }
+};
+
+ResourceTypeCollection.prototype.get_child_subject = function(key){
+ const resource_id = key;
+ const single_resource_subject = new SingleResource(this.resource_type, resource_id);
+ return Promise.resolve(single_resource_subject);
+};
+
+module.exports = ResourceTypeCollection;
diff --git a/lib/subject/subject-types/resource-type-field-subject.js b/lib/subject/subject-types/resource-type-field-subject.js
new file mode 100644
index 00000000..d3ed8d25
--- /dev/null
+++ b/lib/subject/subject-types/resource-type-field-subject.js
@@ -0,0 +1,41 @@
+"use strict";
+const locreq = require("locreq")(__dirname);
+const Promise = require("bluebird");
+const merge = require("merge");
+
+const Subject = locreq("lib/subject/subject.js");
+const Errors = locreq("lib/response/error.js");
+
+const ResourceFieldTypeSubject = function(resource_type, resource_id, field_name){
+ this.name = "ResourceFieldTypeSubject";
+
+ this.resource_type = resource_type;
+ this.resource_id = resource_id;
+ this.field_name = field_name;
+ this.field_type = resource_type[field_name].type;
+};
+
+ResourceFieldTypeSubject.prototype = Object.create(Subject.prototype);
+
+ResourceFieldTypeSubject.prototype.perform_action = function(context, action_name, params){
+ params = params || {};
+ merge(params, {
+ resource_id: this.resource_id,
+ field_name: this.field_name,
+ resource_type: this.resource_type,
+ });
+ if (this.field_type.actions[action_name]){
+ return Promise.resolve(this.field_type.actions[action_name](context, params));
+ } else {
+ throw new Errors.DeveloperError(`Unknown action: '${action_name}'`);
+ }
+};
+
+ResourceFieldTypeSubject.prototype.get_child_subject = function(key){
+ const self = this;
+ return Promise.try(function(){
+ return self.field_type.get_child_subject(key);
+ });
+};
+
+module.exports = ResourceFieldTypeSubject;
diff --git a/lib/subject/subject-types/single-file-subject.js b/lib/subject/subject-types/single-file-subject.js
new file mode 100644
index 00000000..18d3fa91
--- /dev/null
+++ b/lib/subject/subject-types/single-file-subject.js
@@ -0,0 +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){
+ 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})
+ .then(function(results){
+ return results[0];
+ });
+ default:
+ throw new Errors.DeveloperError(`Unknown action for '${this.resource_type.name}' resource: '${action_name}'`);
+ }
+};
+
+
+
+module.exports = FileHash;
diff --git a/lib/subject/subject-types/single-resource-subject.js b/lib/subject/subject-types/single-resource-subject.js
new file mode 100644
index 00000000..880ba413
--- /dev/null
+++ b/lib/subject/subject-types/single-resource-subject.js
@@ -0,0 +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 ResourceTypeFieldSubject = require("./resource-type-field-subject.js");
+
+const SingleResource = function(resource_type, resource_id){
+ this.resource_type = resource_type;
+ this.resource_id = resource_id;
+ this.name = "SingleResource";
+};
+
+SingleResource.prototype = Object.create(Subject.prototype);
+
+SingleResource.prototype.__get_resource = function(datastore, resource_type, resource_id, context, args){
+ args = args || {};
+
+
+ return datastore.find("resources", {sealious_id: resource_id}, {})
+ .then(function(db_entries){
+ if (db_entries[0] === undefined){
+ throw new Errors.NotFound("resource of id " + resource_id + " not found");
+ } else {
+ return resource_type.get_resource_representation(context, db_entries[0], args.format);
+ }
+ }).then(function(resource_representation){
+ return resource_type.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.resource_type, this.resource_id, context, args);
+};
+
+SingleResource.prototype.__edit_resource = function(datastore, resource_type, 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;
+ const self = this;
+
+
+ return SingleResource.prototype.__get_resource(datastore, resource_type, resource_id, context, {})
+ .then(function(resource_data){
+ resource_representation = resource_data;
+ return resource_type.check_if_action_is_allowed(context, "update", resource_representation);
+ }).then(function(){
+ return resource_type.validate_field_values(context, delete_empty_values, values_to_patch, resource_representation.body);
+ }).then(function(){
+ return resource_type.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];
+ }
+ return datastore.update("resources", {sealious_id: self.resource_id}, {$set: query});
+ }).then(function(){
+ return SingleResource.prototype.__get_resource(datastore, resource_type, resource_id, context, self.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.resource_type, self.resource_id, context, values_to_patch, delete_empty_values);
+};
+
+SingleResource.prototype.__delete_resource = function(datastore, resource_type, resource_id, context, args){
+
+ return SingleResource.prototype.__get_resource(datastore, resource_type, resource_id, context, {})
+ .then(function(resource_representation){
+ return resource_type.check_if_action_is_allowed(context, "delete", resource_representation);
+ }).then(function(){
+ return datastore.remove("resources", {
+ sealious_id: resource_id,
+ type: resource_type.name,
+ }, {});
+ })
+ .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.resource_type, 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.resource_type.name}' resource: '${action_name}'`);
+ }
+};
+
+SingleResource.prototype.get_child_subject = function(key){
+ if (this.resource_type.fields[key].type.is_subject){
+ return new ResourceTypeFieldSubject(this.resource_type, this.resource_id, key);
+ }
+};
+
+module.exports = SingleResource;
diff --git a/lib/subject/subject.js b/lib/subject/subject.js
new file mode 100644
index 00000000..1566791b
--- /dev/null
+++ b/lib/subject/subject.js
@@ -0,0 +1,22 @@
+"use strict";
+const locreq = require("locreq")(__dirname);
+const Promise = require("bluebird");
+const SubjectPath = locreq("lib/data-structures/subject-path.js");
+
+function Subject (){}
+
+Subject.prototype.get_subject = function(subject_path){
+ // This is a recursive function. It traverses the subject tree and returns
+ // the subject referenced by subject_path
+ subject_path = new SubjectPath(subject_path);
+ return Promise.resolve(this.get_child_subject(subject_path.head()))
+ .then(function(child_subject){
+ if (subject_path.elements.length === 1){
+ return child_subject;
+ } else {
+ return child_subject.get_subject(subject_path.tail());
+ }
+ });
+};
+
+module.exports = Subject;
diff --git a/lib/super-context.js b/lib/super-context.js
new file mode 100644
index 00000000..2abfa574
--- /dev/null
+++ b/lib/super-context.js
@@ -0,0 +1,18 @@
+"use strict";
+const locreq = require("locreq")(__dirname);
+const Context = locreq("lib/context.js");
+
+function SuperContext (regular_context){
+
+ if (regular_context === undefined){
+ regular_context = new Context();
+ }
+
+ const ret = Object.create(regular_context);
+
+ Object.defineProperty(ret, "is_super", {value: true});
+
+ return ret;
+}
+
+module.exports = SuperContext;
diff --git a/lib/utils/check-for-updates.js b/lib/utils/check-for-updates.js
new file mode 100644
index 00000000..1c8c8dc0
--- /dev/null
+++ b/lib/utils/check-for-updates.js
@@ -0,0 +1,44 @@
+"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){
+ 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;
+ 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!");
+ }
+}
+
+module.exports = check_for_updates;
diff --git a/lib/utils/run-action.js b/lib/utils/run-action.js
new file mode 100644
index 00000000..05b8a319
--- /dev/null
+++ b/lib/utils/run-action.js
@@ -0,0 +1,11 @@
+"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 fe2d9887..a174449e 100644
--- a/package.json
+++ b/package.json
@@ -1,63 +1,55 @@
{
"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": {
- "prepublish": "require-self",
- "test": "node ./tests/test.js",
- "test-coverage": "istanbul cover ./tests/test.js",
- "coveralls": "npm run test-coverage && cat coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js",
- "check-formatting": "jscs -c .jscsrc ./lib && echo \"\\n ✓ Code formatting O.K.!\\n\" || (echo \"\\nSome formatting errors found. Run 'npm run fix-formatting' to correct them.\\n\" && exit 1 )",
- "fix-formatting": "jscs -c .jscsrc ./lib --fix",
- "jshint": "jshint ./lib/*/*.js ./lib/*.js && echo \"\\n ✓ Code guidelines O.K.!\\n\" || (echo \"\\nSome JSHint errors found. Fix errors and run 'npm run check-hint' to correct them.\\n\" && exit 1)"
+ "test": "mocha --recursive tests",
+ "coverage-test": "istanbul cover --include-all-sources _mocha -- -R spec --recursive tests && (xdg-open ./coverage/lcov-report/index.html || exit 0)",
+ "coveralls": "npm run coverage-test && 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/Sealious/Sealious/"
+ "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": {
- "Set": "~0.4.1",
- "bluebird": "~2.9.9",
+ "bluebird": "^3.3.3",
+ "bluebird-events": "^2.0.0",
"clone": "^1.0.2",
"color": "latest",
- "fs-extra": "^0.18.2",
- "immutable": "^3.7.2",
+ "escape-html": "^1.0.3",
+ "expand-hash": "^0.2.2",
+ "fs-extra": "^0.30.0",
+ "locreq": "^1.0.3",
"merge": "^1.2.0",
- "require-dir": "^0.3.0",
+ "node-uuid": "^1.4.7",
+ "request-promise": "^4.0.2",
"resolve": "^1.1.7",
- "sanitize-html": "^1.6.1",
"sealious-datastore-tingo": "^0.1.5",
- "sha1": "^1.1.0",
- "uid": "0.0.2",
+ "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",
- "jscs": "^2.1.1",
- "jshint": "^2.9.1",
"mocha": "*",
"mocha-istanbul": "^0.2.0",
- "pre-commit": "^1.1.1",
- "require-self": "^0.1.0"
+ "pre-commit": "^1.1.3"
},
- "pre-commit": {
- "colors": true,
- "run": [
- "check-formatting",
- "jshint"
- ],
- "silent": false
- }
+ "pre-commit": [
+ "eslint"
+ ]
}
diff --git a/sealious.sublime-project b/sealious.sublime-project
deleted file mode 100644
index 37968020..00000000
--- a/sealious.sublime-project
+++ /dev/null
@@ -1,9 +0,0 @@
-{
- "folders":
- [
- {
- "path": ".",
- "folder_exclude_patterns": ["node_modules", "lib-cov"]
- }
- ]
-}
diff --git a/tests/test.js b/tests/test.js
deleted file mode 100644
index e53e4ab7..00000000
--- a/tests/test.js
+++ /dev/null
@@ -1,50 +0,0 @@
-var Sealious = require("sealious");
-var requireDir = require("require-dir");
-var Mocha = require('mocha');
-var fs = require('fs');
-var path = require('path');
-
-// Instantiate a Mocha instance.
-var mocha = new Mocha();
-mocha.delay();
-
-var testDir = path.resolve(module.filename, '../unit-tests')
-
-// Add each .js file to the mocha instance
-fs.readdirSync(testDir).filter(function(file){
- // Only keep the .js files
- return file.substr(-3) === '.js';
-
-}).forEach(function(file){
- mocha.addFile(
- path.join(testDir, file)
- );
-});
-
-try{
- fs.unlinkSync(path.resolve(module.filename, "../../db/resources"));
-}catch(e){
- console.log("Did not found `db/resources` file")
-}
-
-var tests = requireDir("./unit-tests");
-
-Sealious.init();
-
-for(var i in tests){
- tests[i].test_init && tests[i].test_init();
-}
-
-Sealious.start().then(function(){
- for(var i in tests){
- tests[i].test_start && tests[i].test_start();
- }
- run();
-})
-
-// Run the tests.
-mocha.run(function(failures){
- process.on('exit', function () {
- process.exit(failures);
- });
-});
\ No newline at end of file
diff --git a/tests/unit-tests/access-strategy.just_owner.test.js b/tests/unit-tests/access-strategy.just_owner.test.js
deleted file mode 100644
index efdf8245..00000000
--- a/tests/unit-tests/access-strategy.just_owner.test.js
+++ /dev/null
@@ -1,47 +0,0 @@
-var Sealious = require("sealious");
-
-module.exports = {
- test_init: function() {
-
- },
- test_start: function() {
- var just_owner = Sealious.ChipManager.get_chip("access_strategy", "just_owner")
- describe("AccessStrategy.JustOwner", function() {
- it("checks if the user is the owner and returns true", function(done) {
- var context = new Sealious.Context(undefined, "ip", "user_id");
- var item = {
- created_context: {
- user_id: "user_id"
- }
- }
- just_owner.checker_function(context, item)
- .then(function() {
- done();
- })
- .catch(function(error) {
- done(new Error(error))
- })
- })
- /*
- it("checks if the user is the owner and returns false (the test doesn't pass because it doesn't reject with an error but with a string)", function(done) {
- var context = new Sealious.Context(undefined, "ip", "user_id");
- var item = {
- created_context: {
- user_id: "user_id2"
- }
- }
- just_owner.checker_function(context, item)
- .then(function() {
- done(new Error("It lets the user pass"));
- })
- .catch(function(error) {
- if(error instanceof String)
- done(new Error("The error is an instance of String"))
- else
- done();
- })
- })
-*/
- })
- }
-}
\ No newline at end of file
diff --git a/tests/unit-tests/access-strategy.test.js b/tests/unit-tests/access-strategy.test.js
deleted file mode 100644
index 3927c95c..00000000
--- a/tests/unit-tests/access-strategy.test.js
+++ /dev/null
@@ -1,35 +0,0 @@
-var Sealious = require('sealious');
-
-module.exports = {
- test_init: function() {
- new Sealious.ChipTypes.AccessStrategy({
- name: "test_access_strategy",
- checker_function: function(context){
- return Promise.resolves();
- },
- item_sensitive: false,
- });
- },
- test_start: function() {
- describe("AccessStrategy", function() {
- it("throws an error because declaration.name isn't string", function(done) {
- try {
- new Sealious.ChipTypes.AccessStrategy({})
- }
- catch (e) {
- if (e.type === "dev_error")
- done();
- else
- done(new Error("It didn't throw a developer error"))
- }
- })
- it("finds tests_access_strategy", function(done) {
- var result = Sealious.ChipManager.get_chip("access_strategy", "test_access_strategy")
- if (result.name === "test_access_strategy")
- done();
- else
- done("The names don't match");
- })
- })
- }
-}
\ No newline at end of file
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
new file mode 100644
index 00000000..ea42ff2a
--- /dev/null
+++ b/tests/unit-tests/base-chips/access-strategy/logged-in.test.js
@@ -0,0 +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");
+
+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
new file mode 100644
index 00000000..4ca9d6e4
--- /dev/null
+++ b/tests/unit-tests/base-chips/access-strategy/noone.test.js
@@ -0,0 +1,23 @@
+"use strict";
+const locreq = require("locreq")(__dirname);
+const assert = require("assert");
+const noone = locreq("lib/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
new file mode 100644
index 00000000..ccff2d10
--- /dev/null
+++ b/tests/unit-tests/base-chips/access-strategy/owner.test.js
@@ -0,0 +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 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
new file mode 100644
index 00000000..3e0e8385
--- /dev/null
+++ b/tests/unit-tests/base-chips/access-strategy/public.test.js
@@ -0,0 +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");
+
+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
new file mode 100644
index 00000000..79a0270a
--- /dev/null
+++ b/tests/unit-tests/base-chips/field-types/boolean.test.js
@@ -0,0 +1,81 @@
+"use strict";
+const locreq = require("locreq")(__dirname);
+const field_type_boolean = locreq("lib/base-chips/field-types/boolean.js");
+const Context = locreq("lib/context.js");
+
+const acceptCorrectly = locreq("tests/util/accept-correctly.js");
+const rejectCorrectly = locreq("tests/util/reject-correctly.js");
+
+const assert = require("assert");
+
+
+describe("FieldType.Boolean", function(){
+ 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");
+ });
+ it("checks if is_proper_value works correctly (given boolean)", function(done){
+ const accept = acceptCorrectly(done).accept;
+ const reject = acceptCorrectly(done).reject;
+ field_type_boolean.is_proper_value(accept, reject, new Context(), {}, true);
+ });
+ it("checks if is_proper_value works correctly (given 1)", function(done){
+ const accept = acceptCorrectly(done).accept;
+ const reject = acceptCorrectly(done).reject;
+ field_type_boolean.is_proper_value(accept, reject, new Context(), {}, 1);
+ });
+ it("checks if is_proper_value works correctly (given \"true\")", function(done){
+ const accept = acceptCorrectly(done).accept;
+ const reject = acceptCorrectly(done).reject;
+ field_type_boolean.is_proper_value(accept, reject, new Context(), {}, "true");
+ });
+ it("checks if is_proper_value works correctly (given 2)", function(done){
+ const accept = rejectCorrectly(done).accept;
+ const reject = rejectCorrectly(done).reject;
+ field_type_boolean.is_proper_value(accept, reject, new Context(), {}, 2);
+ });
+ 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
new file mode 100644
index 00000000..037eb2be
--- /dev/null
+++ b/tests/unit-tests/base-chips/field-types/color.test.js
@@ -0,0 +1,58 @@
+"use strict";
+const locreq = require("locreq")(__dirname);
+const field_type_color = locreq("lib/base-chips/field-types/color.js");
+const Context = locreq("lib/context.js");
+const assert = require("assert");
+
+const acceptCorrectly = locreq("tests/util/accept-correctly.js");
+const rejectCorrectly = locreq("tests/util/reject-correctly.js");
+
+describe("FieldType.Color", function(){
+ it("returns the name of the field type", function(){
+ assert.strictEqual(field_type_color.name, "color");
+ });
+ it("checks if is_proper_value throws an error (wrong value)", function(done){
+ const accept = rejectCorrectly(done).accept;
+ const reject = rejectCorrectly(done).reject;
+ field_type_color.is_proper_value(accept, reject, new Context(), {}, "aaaa");
+ });
+ it("checks if is_proper_value works correctly (given \"rgb(255, 255, 255)\"", function(done){
+ const accept = acceptCorrectly(done).accept;
+ const reject = acceptCorrectly(done).reject;
+ field_type_color.is_proper_value(accept, reject, new Context(), {}, "rgb(255, 255, 255)");
+ });
+ it("checks if is_proper_value works correctly (given \"black\"", function(done){
+ const accept = acceptCorrectly(done).accept;
+ const reject = acceptCorrectly(done).reject;
+ field_type_color.is_proper_value(accept, reject, new Context(), {}, "black");
+ });
+ it("checks if is_proper_value works correctly (given \"BLACK\"", function(done){
+ const accept = acceptCorrectly(done).accept;
+ const reject = acceptCorrectly(done).reject;
+ field_type_color.is_proper_value(accept, reject, new Context(), {}, "BLACK");
+ });
+ it("checks if is_proper_value works correctly (given \"#000000\"", function(done){
+ const accept = acceptCorrectly(done).accept;
+ const reject = acceptCorrectly(done).reject;
+ field_type_color.is_proper_value(accept, reject, new Context(), {}, "#000000");
+ });
+ it("checks if is_proper_value works correctly (given \"{r: 255, g: 255, b: 255}\"", function(done){
+ const accept = acceptCorrectly(done).accept;
+ const reject = acceptCorrectly(done).reject;
+ field_type_color.is_proper_value(accept, reject, new Context(), {r: 255, g: 255, b: 255});
+ });
+ it("checks if is_proper_value works correctly (given \"hsla(262, 59%, 81%, 0.5)\"", function(done){
+ const accept = acceptCorrectly(done).accept;
+ const reject = acceptCorrectly(done).reject;
+ field_type_color.is_proper_value(accept, reject, new Context(), "hsla(262, 59%, 81%, 0.5)");
+ });
+ 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
new file mode 100644
index 00000000..e43245e3
--- /dev/null
+++ b/tests/unit-tests/base-chips/field-types/context.test.js
@@ -0,0 +1,25 @@
+"use strict";
+const locreq = require("locreq")(__dirname);
+const field_type_context = locreq("lib/base-chips/field-types/context.js");
+const Context = locreq("lib/context.js");
+
+const acceptCorrectly = locreq("tests/util/accept-correctly.js");
+const rejectCorrectly = locreq("tests/util/reject-correctly.js");
+
+const assert = require("assert");
+
+describe("FieldType.Context", function(){
+ it("returns the name of the field type", function(){
+ assert.strictEqual(field_type_context.name, "context");
+ });
+ it("accepts an instance of Sealious.Context", function(done){
+ const accept = acceptCorrectly(done).accept;
+ const reject = acceptCorrectly(done).reject;
+ field_type_context.is_proper_value(accept, reject, new Context(), {}, new Context());
+ });
+ it("rejects a non-instance of Sealious.Context", function(done){
+ const accept = rejectCorrectly(done).accept;
+ const reject = rejectCorrectly(done).reject;
+ field_type_context.is_proper_value(accept, reject, new 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
new file mode 100644
index 00000000..f6f56be0
--- /dev/null
+++ b/tests/unit-tests/base-chips/field-types/date.test.js
@@ -0,0 +1,27 @@
+"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 acceptCorrectly = locreq("tests/util/accept-correctly.js");
+const rejectCorrectly = locreq("tests/util/reject-correctly.js");
+
+const assert = require("assert");
+
+describe("FieldType.Date", function(){
+ 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");
+ });
+ it("checks if is_proper_value works correctly(given correct date format)", function(done){
+ const accept = acceptCorrectly(done).accept;
+ const reject = acceptCorrectly(done).reject;
+ field_type_date.is_proper_value(accept, reject, new Context(), {}, "2015-10-27");
+ });
+ it("checks if is_proper_value works correctly (given incorrect date format)", function(done){
+ const accept = rejectCorrectly(done).accept;
+ const reject = rejectCorrectly(done).reject;
+ field_type_date.is_proper_value(accept, reject, new Context(), {}, "2015/10/27");
+ });
+});
diff --git a/tests/unit-tests/base-chips/field-types/datetime.test.js b/tests/unit-tests/base-chips/field-types/datetime.test.js
new file mode 100644
index 00000000..242edf5e
--- /dev/null
+++ b/tests/unit-tests/base-chips/field-types/datetime.test.js
@@ -0,0 +1,30 @@
+"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 acceptCorrectly = locreq("tests/util/accept-correctly.js");
+const rejectCorrectly = locreq("tests/util/reject-correctly.js");
+
+const assert = require("assert");
+
+describe("FieldType.Datetime", function(){
+ 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 is_proper_value works correctly(given timestamp)", function(done){
+ const accept = acceptCorrectly(done).accept;
+ const reject = acceptCorrectly(done).reject;
+ field_type_datetime.is_proper_value(accept, reject, new Context(), {}, 1);
+ });
+ it("checks if is_proper_value works correctly(given string)", function(done){
+ const accept = rejectCorrectly(done).accept;
+ const reject = rejectCorrectly(done).reject;
+ field_type_datetime.is_proper_value(accept, reject, new Context(), {}, "test");
+ });
+ 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
new file mode 100644
index 00000000..9238dca6
--- /dev/null
+++ b/tests/unit-tests/base-chips/field-types/email.test.js
@@ -0,0 +1,27 @@
+"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 acceptCorrectly = locreq("tests/util/accept-correctly.js");
+const rejectCorrectly = locreq("tests/util/reject-correctly.js");
+
+const assert = require("assert");
+
+describe("FieldType.Email", function(){
+ 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");
+ });
+ it("checks if is_proper_value works correctly(given correct date format)", function(done){
+ const accept = acceptCorrectly(done).accept;
+ const reject = acceptCorrectly(done).reject;
+ field_type_email.is_proper_value(accept, reject, new Context(), {}, "test@mail.com");
+ });
+ it("checks if is_proper_value works correctly(given incorrect date format)", function(done){
+ const accept = rejectCorrectly(done).accept;
+ const reject = rejectCorrectly(done).reject;
+ field_type_email.is_proper_value(accept, reject, new Context(), {}, "test");
+ });
+});
diff --git a/tests/unit-tests/base-chips/field-types/file.test.js b/tests/unit-tests/base-chips/field-types/file.test.js
new file mode 100644
index 00000000..dfeab51b
--- /dev/null
+++ b/tests/unit-tests/base-chips/field-types/file.test.js
@@ -0,0 +1,49 @@
+"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 acceptCorrectly = locreq("tests/util/accept-correctly.js");
+const rejectCorrectly = locreq("tests/util/reject-correctly.js");
+
+const File = locreq("lib/data-structures/file.js");
+
+const assert = require("assert");
+
+describe("FieldType.File", function(){
+ it("returns undefined", function(){
+ assert.strictEqual(field_type_file.is_proper_value({}, {}, new Context(), {}, undefined), undefined);
+ });
+ it("accepts given value (which is an instance of Sealious.File)", function(done){
+ const accept = acceptCorrectly(done).accept;
+ const reject = acceptCorrectly(done).reject;
+ field_type_file.is_proper_value(accept, reject, new Context(), {}, new File());
+ });
+ it("accepts given value (which is an object with filename and data attributes)", function(done){
+ const value = {
+ filename: "test_filename",
+ data: new Buffer(1)
+ };
+ const accept = acceptCorrectly(done).accept;
+ const reject = acceptCorrectly(done).reject;
+ field_type_file.is_proper_value(accept, reject, new Context(), {}, value);
+ });
+ it("rejects given value (which is an empty object)", function(done){
+ const accept = rejectCorrectly(done).accept;
+ const reject = rejectCorrectly(done).reject;
+ field_type_file.is_proper_value(accept, reject, new Context(), {}, {});
+ });
+ it("rejects given value (which is an array)", function(done){
+ const accept = rejectCorrectly(done).accept;
+ const reject = rejectCorrectly(done).reject;
+ field_type_file.is_proper_value(accept, reject, new Context(), {}, []);
+ });
+ 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);
+ });
+ 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");
+ });
+});
diff --git a/tests/unit-tests/base-chips/field-types/float.test.js b/tests/unit-tests/base-chips/field-types/float.test.js
new file mode 100644
index 00000000..a584b946
--- /dev/null
+++ b/tests/unit-tests/base-chips/field-types/float.test.js
@@ -0,0 +1,30 @@
+"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 acceptCorrectly = locreq("tests/util/accept-correctly.js");
+const rejectCorrectly = locreq("tests/util/reject-correctly.js");
+
+const assert = require("assert");
+
+describe("FieldType.Float", function(){
+ 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 is_proper_value works correctly", function(done){
+ const accept = acceptCorrectly(done).accept;
+ const reject = acceptCorrectly(done).reject;
+ field_type_float.is_proper_value(accept, reject, new Context(), {}, 2.5);
+ });
+ it("returns error because new_value is not an integer", function(done){
+ const accept = rejectCorrectly(done).accept;
+ const reject = rejectCorrectly(done).reject;
+ field_type_float.is_proper_value(accept, reject, new Context(), {}, "janusz");
+ });
+ 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
new file mode 100644
index 00000000..b098aaf1
--- /dev/null
+++ b/tests/unit-tests/base-chips/field-types/hashed-text.test.js
@@ -0,0 +1,90 @@
+"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 acceptCorrectly = locreq("tests/util/accept-correctly.js");
+const rejectCorrectly = locreq("tests/util/reject-correctly.js");
+
+const assert = require("assert");
+const crypto = require("crypto");
+
+describe("FieldType.HashedText", function(){
+ 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("accepts given password ('pas1sw24rd1')", function(done){
+ const accept = acceptCorrectly(done).accept;
+ const reject = acceptCorrectly(done).reject;
+ field_type_hashed_text.is_proper_value(accept, reject, new Context(), {}, "pas1sw24rd1");
+ });
+ it("accepts given password ('pas1sw24rd1')", function(done){
+ const accept = acceptCorrectly(done).accept;
+ const reject = acceptCorrectly(done).reject;
+ field_type_hashed_text.is_proper_value(accept, reject, new Context(), {digits: 3}, "pas1sw24rd1");
+ });
+ it("accepts given password ('PAs1sW24rD1')", function(done){
+ const accept = acceptCorrectly(done).accept;
+ const reject = acceptCorrectly(done).reject;
+ field_type_hashed_text.is_proper_value(accept, reject, new Context(), {capitals: 3}, "PAs1sW24rD1");
+ });
+ it("accepts given password ('PaSw0rd23')", function(done){
+ const accept = acceptCorrectly(done).accept;
+ const reject = acceptCorrectly(done).reject;
+ field_type_hashed_text.is_proper_value(accept, reject, new Context(), {capitals: 2, digits: 3}, "PaSw0rd23");
+ });
+ it("rejects given password ('password')", function(done){
+ const accept = rejectCorrectly(done).accept;
+ const reject = rejectCorrectly(done).reject;
+ field_type_hashed_text.is_proper_value(accept, reject, new Context(), {capitals: 2, digits: 3}, "password");
+ });
+ it("accept the password", function(done){
+ const accept = acceptCorrectly(done).accept;
+ const reject = acceptCorrectly(done).reject;
+ field_type_hashed_text.is_proper_value(accept, reject, new Context(), "not on object", "password");
+ });
+ 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/int.test.js b/tests/unit-tests/base-chips/field-types/int.test.js
new file mode 100644
index 00000000..072d7427
--- /dev/null
+++ b/tests/unit-tests/base-chips/field-types/int.test.js
@@ -0,0 +1,30 @@
+"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 acceptCorrectly = locreq("tests/util/accept-correctly.js");
+const rejectCorrectly = locreq("tests/util/reject-correctly.js");
+
+const assert = require("assert");
+
+describe("FieldType.Int", function(){
+ 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 is_proper_value works correctly", function(done){
+ const accept = acceptCorrectly(done).accept;
+ const reject = acceptCorrectly(done).reject;
+ field_type_int.is_proper_value(accept, reject, new Context(), {}, 2);
+ });
+ it("should return error because new_value is not an integer", function(done){
+ const accept = rejectCorrectly(done).accept;
+ const reject = rejectCorrectly(done).reject;
+ field_type_int.is_proper_value(accept, reject, new Context(), {}, "janusz");
+ });
+ it("should check if encode works properly (given \"2\")", function(){
+ assert.strictEqual(field_type_int.encode(new Context(), {}, "2"), 2);
+ });
+});
diff --git a/tests/unit-tests/base-chips/field-types/text.test.js b/tests/unit-tests/base-chips/field-types/text.test.js
new file mode 100644
index 00000000..a4b82993
--- /dev/null
+++ b/tests/unit-tests/base-chips/field-types/text.test.js
@@ -0,0 +1,103 @@
+"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 acceptCorrectly = locreq("tests/util/accept-correctly.js");
+const rejectCorrectly = locreq("tests/util/reject-correctly.js");
+const assert_no_error = locreq("tests/util/assert-no-error.js");
+
+const assert = require("assert");
+
+describe("FieldType.Text", function(){
+ it("returns the name of the field type", function(){
+ assert.strictEqual(field_type_text.name, "text");
+ });
+ it("enables full text search", function(){
+ assert.strictEqual(field_type_text.full_text_search_enabled({include_in_search: true}), true);
+ });
+ it("enables full text search with max length of 200", function(){
+ assert.strictEqual(field_type_text.full_text_search_enabled({max_length: 201}), true);
+ });
+ it("disables full text search", function(){
+ assert.strictEqual(field_type_text.full_text_search_enabled({}), false);
+ });
+ 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 is_proper_value works correctly", function(done){
+ const accept = acceptCorrectly(done).accept;
+ const reject = acceptCorrectly(done).reject;
+ field_type_text.is_proper_value(accept, reject, new Context(), {}, 2);
+ });
+ it("checks if is_proper_value works correctly", function(done){
+ const accept = acceptCorrectly(done).accept;
+ const reject = acceptCorrectly(done).reject;
+ field_type_text.is_proper_value(accept, reject, new Context(), {max_length: 5}, "12345");
+ });
+ it("checks if is_proper_value works correctly", function(done){
+ const accept = rejectCorrectly(done).accept;
+ const reject = rejectCorrectly(done).reject;
+ field_type_text.is_proper_value(accept, reject, new Context(), {max_length: 5}, "asdfghjkl");
+ });
+ it("checks if is_proper_value accepts text with required min characters", function(done){
+ const accept = acceptCorrectly(done).accept;
+ const reject = acceptCorrectly(done).reject;
+ field_type_text.is_proper_value(accept, reject, new Context(), {min_length: 4}, "aaaa");
+ });
+ it("checks if is_proper_value rejects text with fewer characters than needed", function(done){
+ const accept = rejectCorrectly(done).accept;
+ const reject = rejectCorrectly(done).reject;
+ field_type_text.is_proper_value(accept, reject, new Context(), {min_length: 4}, "aa");
+ });
+ it("checks if is_proper_value accepts text with required min and max characters", function(done){
+ const accept = acceptCorrectly(done).accept;
+ const reject = acceptCorrectly(done).reject;
+ field_type_text.is_proper_value(accept, reject, new Context(), {min_length: 2, max_length: 3}, "aaa");
+ });
+ it("checks if is_proper_value reject text that doesn't meet the requirements", function(done){
+ const accept = rejectCorrectly(done).accept;
+ const reject = rejectCorrectly(done).reject;
+ field_type_text.is_proper_value(accept, reject, new Context(), {min_length: 2, max_length: 3}, "aaaaaa");
+ });
+ 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
new file mode 100644
index 00000000..14c88215
--- /dev/null
+++ b/tests/unit-tests/base-chips/field-types/username.test.js
@@ -0,0 +1,33 @@
+"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 acceptCorrectly = locreq("tests/util/accept-correctly.js");
+const rejectCorrectly = locreq("tests/util/reject-correctly.js");
+
+const assert = require("assert");
+
+describe("FieldType.Username", function(){
+ 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");
+ });
+ it("checks if is_proper_value works correctly (old value equals new value)", function(done){
+ const accept = acceptCorrectly(done).accept;
+ const reject = acceptCorrectly(done).reject;
+ field_type_username.is_proper_value(accept, reject, new Context(), {}, "troll", "troll");
+ });
+ it("checks if is_proper_value works correctly (new value is a reserved keyword)", function(done){
+ const accept = rejectCorrectly(done).accept;
+ const reject = rejectCorrectly(done).reject;
+ field_type_username.is_proper_value(accept, reject, new Context(), {}, "me");
+ });
+ // it("checks if is_proper_value works correctly", function(done){
+ // const accept = rejectCorrectly(done).accept;
+ // const reject = rejectCorrectly(done).reject;
+ // field_type_username.is_proper_value(accept, reject, new Context(), {}, "test", "lol");
+ // });
+});
diff --git a/tests/unit-tests/channel.test.js b/tests/unit-tests/channel.test.js
deleted file mode 100644
index a72d741a..00000000
--- a/tests/unit-tests/channel.test.js
+++ /dev/null
@@ -1,21 +0,0 @@
-//var Channel = require('../../lib/chip-types/chip.js');
-var Sealious = require('sealious');
-
-
-module.exports = {
- test_init: function() {
-
- },
- test_start: function() {
- describe("Channel", function() {
- it("adds new channel", function(done) {
- Sealious.ChipTypes.Channel("new_test_channel");
- var result = Sealious.ChipManager.get_chip("channel", "new_test_channel")
- if (result.name === "new_test_channel")
- done();
- else
- done(new Error("It didn't return the correct channel"))
- })
- })
- }
-}
diff --git a/tests/unit-tests/chip-manager.test.js b/tests/unit-tests/chip-manager.test.js
deleted file mode 100644
index 312833af..00000000
--- a/tests/unit-tests/chip-manager.test.js
+++ /dev/null
@@ -1,72 +0,0 @@
-var Sealious = require("sealious");
-
-module.exports = {
- test_init: function() {
- var always_fails_resource = new Sealious.ChipTypes.ResourceType({
- name: "chip_manager_tests_resource",
- });
- },
- test_start: function() {
- describe("ChipManager", function() {
- it("gets all resource types", function(done) {
- var names = Sealious.ChipManager.get_all_resource_types();
- if (names instanceof Array)
- if (names.indexOf("chip_manager_tests_resource") > -1)
- done();
- else
- done(new Error("It doesn't contains the created resource"))
- else
- done(new Error("It didn't return the array"))
- })
- it("gets chip by longid (longid exists)", function(done) {
- var chip = Sealious.ChipManager.get_chip_by_longid("resource_type.chip_manager_tests_resource");
- if (chip instanceof Object)
- if (chip.type === "resource_type")
- if (chip.name === "chip_manager_tests_resource")
- if (chip.longid === "resource_type.chip_manager_tests_resource")
- done();
- else
- done(new Error("It didn't return the correct longid"));
- else
- done(new Error("It didn't return the correct chip name"));
- else
- done(new Error("It didn't return the correct chip type"));
- else
- done(new Error("It didn't return an object"))
- });
- it("throws an error when get_chip_by_longid has non existent longid", function(done) {
- try {
- Sealious.ChipManager.get_chip_by_longid("doesn't exist");
- done(new Error("It didn't throw an error"));
- }
- catch (e) {
- if (e.type === "validation")
- done();
- else
- done(new Error(e))
- }
- });
- it("gets chip amount by type and returns 0 (non existent type)", function(done) {
- var amount = Sealious.ChipManager.get_chip_amount_by_type("non existent");
- if (amount === 0)
- done();
- else
- done(new Error("It returned something else than 0"))
- });
- it("gets chips by type (type exists)", function(done){
- var chips = Sealious.ChipManager.get_chips_by_type("resource_type");
- if (chips["chip_manager_tests_resource"] !== undefined)
- done();
- else
- done(new Error("It didn't get the chip_manager_tests_resource type"))
- });
- it("gets chips by type (type doesn't exist)", function(done){
- var chips = Sealious.ChipManager.get_chips_by_type("troll_type");
- if (chips === undefined)
- done();
- else
- done(new Error("The result is not undefined"))
- });
- })
- }
-}
\ No newline at end of file
diff --git a/tests/unit-tests/chip-types/access-strategy-type.test.js b/tests/unit-tests/chip-types/access-strategy-type.test.js
new file mode 100644
index 00000000..93892501
--- /dev/null
+++ b/tests/unit-tests/chip-types/access-strategy-type.test.js
@@ -0,0 +1,152 @@
+"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 ASTP = AccessStrategyType.prototype;
+
+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);
+ });
+
+ describe(".prototype.__is_item_sensitive", function(){
+ it("should work with a boolean 'item_sensitive' value: false", function(done){
+ ASTP.__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({
+ 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({
+ 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({
+ 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({
+ 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({
+ item_sensitive: () => Promise.resolve(true)
+ }).then(function(result){
+ assert.strictEqual(result, true);
+ done();
+ });
+ });
+ });
+
+ describe(".prototype.__check", function(){
+ it("should resolve if given an instance of SuperContext", function(done){
+ const sc = new SuperContext();
+ const result = ASTP.__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(), {})
+ .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(), {});
+ 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(), {});
+ 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(), {});
+ assert_error(result, done);
+ });
+
+ it("should pass item as argument if the strategy is item_sensitive", function(done){
+ const item = {};
+ ASTP.__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
new file mode 100644
index 00000000..08b2d3e5
--- /dev/null
+++ b/tests/unit-tests/chip-types/chip-manager.test.js
@@ -0,0 +1,54 @@
+"use strict";
+const locreq = require("locreq")(__dirname);
+const ChipManager = locreq("lib/chip-types/chip-manager.js");
+const assert = require("assert");
+
+describe("ChipManager", function(){
+
+ const chips = {
+ resource_type: {
+ test: {},
+ test2: {}
+ }
+ };
+
+ it("gets all resource types", function(){
+ const names = ChipManager.__get_all_resource_types(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, "resource_type.test");
+ assert.strictEqual(chip, chips.resource_type.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");
+ assert.strictEqual(amount, 0);
+ });
+
+ it("gets chips by type (type exists)", function(){
+ const received_chips = ChipManager.__get_chips_by_type(chips, "resource_type");
+ assert.strictEqual(received_chips.test, chips.resource_type.test);
+ });
+
+ it("gets chips by type (type doesn't exist)", function(){
+ const chips = ChipManager.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
new file mode 100644
index 00000000..16387978
--- /dev/null
+++ b/tests/unit-tests/chip-types/field-structures/single.test.js
@@ -0,0 +1,25 @@
+"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-default-methods.test.js b/tests/unit-tests/chip-types/field-type-default-methods.test.js
new file mode 100644
index 00000000..dba54c20
--- /dev/null
+++ b/tests/unit-tests/chip-types/field-type-default-methods.test.js
@@ -0,0 +1,64 @@
+"use strict";
+const locreq = require("locreq")(__dirname);
+const assert = require("assert");
+const FieldTypeDefaultMethods = locreq("lib/chip-types/field-type-default-methods.js");
+
+describe("Sealious.FieldTypeDefaultMethods", function() {
+ it("resolves the .is_proper_value()", function(done) {
+ FieldTypeDefaultMethods.is_proper_value()
+ .then(function() {
+ done();
+ }).catch(done);
+ });
+ it("resolves the .format() with decoded value \"test\"", function(done) {
+ FieldTypeDefaultMethods.format(null, null, "test")
+ .then(function(decoded_value) {
+ assert.strictEqual(decoded_value, "test");
+ done();
+ }).catch(done);
+ });
+ it("resolves the .format() with decoded value null", function(done) {
+ FieldTypeDefaultMethods.format(null, null, null)
+ .then(function(decoded_value) {
+ assert.strictEqual(decoded_value, null);
+ done();
+ }).catch(done);
+ });
+ it("resolves the .encode() with value \"test\"", function(done) {
+ FieldTypeDefaultMethods.encode(null, null, "test")
+ .then(function(encoded_value) {
+ assert.strictEqual(encoded_value, "test");
+ done();
+ }).catch(done);
+ });
+ it("resolves the .encode() with value null", function(done) {
+ FieldTypeDefaultMethods.encode(null, null, null)
+ .then(function(encoded_value) {
+ assert.strictEqual(encoded_value, null);
+ done();
+ }).catch(done);
+ });
+ it("returns the .decode() with value \"test\"", function() {
+ assert.strictEqual(FieldTypeDefaultMethods.decode(null, null, "test"), "test");
+ });
+ it("returns the .decode() with value null", function() {
+ assert.strictEqual(FieldTypeDefaultMethods.decode(null, null, null), null);
+ });
+ it("resolves the .filter_to_query() with value \"test\"", function(done) {
+ FieldTypeDefaultMethods.filter_to_query(null, null, "test")
+ .then(function(encoded) {
+ assert.deepEqual(encoded, {$eq: "test"});
+ done();
+ }).catch(done);
+ });
+ it("returns false when full_text_search_enabled called", function() {
+ assert.strictEqual(FieldTypeDefaultMethods.full_text_search_enabled(), false);
+ });
+ it("returns the field type description", function() {
+ FieldTypeDefaultMethods.name = "test_name";
+ const field_type = FieldTypeDefaultMethods.get_description();
+ assert.strictEqual(field_type.summary, "test_name");
+ assert.strictEqual(field_type.raw_params, undefined);
+ assert.deepEqual(field_type.extra_info, {});
+ });
+});
diff --git a/tests/unit-tests/chip-types/field-type.test.js b/tests/unit-tests/chip-types/field-type.test.js
new file mode 100644
index 00000000..b210f9f6
--- /dev/null
+++ b/tests/unit-tests/chip-types/field-type.test.js
@@ -0,0 +1,182 @@
+"use strict";
+const locreq = require("locreq")(__dirname);
+const FieldType = locreq("lib/chip-types/field-type.js");
+const ChipManager = locreq("lib/chip-types/chip-manager.js");
+const Context = locreq("lib/context.js");
+const assert_no_error = require("../../util/assert-no-error.js");
+const assert = require("assert");
+
+new FieldType({
+ name: "test_field_type"
+});
+
+new FieldType({
+ name: "rejecting_father",
+ is_proper_value: function(accept, reject){
+ reject("Rejected by the father");
+ },
+ encode: function(){
+ return "from_father";
+ },
+ decode: function(){
+ return "from_father";
+ },
+ get_description: function(){
+ return "from_father";
+ }
+});
+
+new FieldType({
+ name: "accepting_son",
+ extends: "rejecting_father",
+ is_proper_value: function(accept){
+ accept();
+ },
+ encode: function(){
+ return "from_son";
+ },
+ decode: function(){
+ return "from_son";
+ },
+ get_description: function(){
+ return "from_son"
+ }
+});
+
+new FieldType({
+ name: "hesitant_daughter",
+ extends: "rejecting_father"
+});
+
+describe("FieldType", function(){
+ const test_field_type = ChipManager.get_chip("field_type", "test_field_type");
+ const but_it_didnt = new Error("But it didn't");
+
+ describe("default methods", function(){
+ describe("when not overwritten", function(){
+ it("should use default .is_proper_value", function(done){
+ const result = test_field_type.is_proper_value("any_value");
+ assert_no_error(result, done);
+ });
+ // it("should use default .is_proper_declaration", function(){
+ // var return_value = test_field_type.is_proper_declaration({});
+ // assert.strictEqual(typeof return_value, "boolean");
+ // assert.strictEqual(return_value, true);
+ // });
+ it("should use default .encode", function(done){
+ test_field_type.encode(new Context(), {}, "dogfood")
+ .then(function(encoded){
+ assert.strictEqual(encoded, "dogfood");
+ done();
+ }).catch(done);
+ });
+ it("should use default .decode", function(){
+ const decoded = test_field_type.decode(new Context(), {}, "dogfood")
+ assert.strictEqual(decoded, "dogfood");
+ });
+ it("should use default .get_description", function(){
+ const description = test_field_type.get_description()
+ assert.strictEqual(description.summary, "test_field_type");
+ });
+ });
+ describe("when overwritten", function(){
+ const rejecting_father = ChipManager.get_chip("field_type", "rejecting_father");
+
+ it("should use the custom .is_proper_value method", function(done){
+ rejecting_father.is_proper_value("any_value")
+ .then(function(){
+ done(new Error("But it didn't (should have been rejected in this case, but wasn't)"));
+ }).catch(function(error){
+ done();
+ });
+ });
+ it("should use the custom .encode method", function(done){
+ rejecting_father.encode(new Context(), {}, "anything")
+ .then(function(encoded_value){
+ assert.strictEqual(encoded_value, "from_father");
+ done();
+ }).catch(done);
+ });
+ it("should use the custom .decode method", function(done){
+ rejecting_father.decode("anything")
+ .then(function(decoded_value){
+ assert.strictEqual(decoded_value, "from_father");
+ done();
+ }).catch(done);
+ });
+ it("should use the custom .get_description method", function(done){
+ rejecting_father.get_description()
+ .then(function(description){
+ assert.strictEqual(description, "from_father");
+ done();
+ }).catch(done);
+ });
+ });
+ });
+
+ describe("inheritance", function(){
+ const accepting_son = ChipManager.get_chip("field_type", "accepting_son");
+ const hesitant_daughter = ChipManager.get_chip("field_type", "hesitant_daughter");
+
+ // it("should inherit is_proper_value", function(done){
+ // accepting_son.is_proper_value(new Context(), {}, "any")
+ // .then(function(){
+ // done(new Error("accepting_son accepted the value, which should have been rejected by his rejecting_father"));
+ // }).catch(function(error){
+ // assert.strictEqual(error.message, "Rejected by the father");
+ // done();
+ // })
+ // });
+ it("should use parent's is_proper_value when not having its own", function(done){
+ hesitant_daughter.is_proper_value(new Context(), {}, "any")
+ .then(function(){
+ done(new Error("But it accepted value, which should have been rejected by rejecting_father"));
+ }).catch(function(error){
+ assert.strictEqual(error.message, "Rejected by the father");
+ done();
+ });
+ });
+ it("should use child's .encode method when a child has it's own encode method", function(done){
+ accepting_son.encode(new Context(), {}, "anything")
+ .then(function(encoded_value){
+ assert.strictEqual(encoded_value, "from_son");
+ done();
+ }).catch(done);
+ });
+ it("should use parent's .encode method when a child does not have it's own", function(done){
+ hesitant_daughter.encode(new Context(), {}, "anything")
+ .then(function(encoded_value){
+ assert.strictEqual(encoded_value, "from_father");
+ done();
+ }).catch(done);
+ });
+ it("should use child's .decode method when a child has it's own decode method", function(done){
+ accepting_son.decode("anything")
+ .then(function(decoded_value){
+ assert.strictEqual(decoded_value, "from_son");
+ done();
+ }).catch(done);
+ });
+ it("should use parent's .decode method when a child does not have it's own", function(done){
+ hesitant_daughter.decode("anything")
+ .then(function(decoded_value){
+ assert.strictEqual(decoded_value, "from_father");
+ done();
+ }).catch(done);
+ });
+ it("should use child's .get_description method when a child has it's own .get_description method", function(done){
+ accepting_son.get_description()
+ .then(function(description){
+ assert.strictEqual(description, "from_son");
+ done();
+ }).catch(done);
+ });
+ it("should use parent's .get_description method when a child does not have it's own", function(done){
+ hesitant_daughter.get_description()
+ .then(function(description){
+ assert.strictEqual(description, "from_father");
+ done();
+ }).catch(done);
+ });
+ });
+});
diff --git a/tests/unit-tests/chip.test.js b/tests/unit-tests/chip.test.js
deleted file mode 100644
index 50530710..00000000
--- a/tests/unit-tests/chip.test.js
+++ /dev/null
@@ -1,26 +0,0 @@
-var Chip = require('../../lib/chip-types/chip.js');
-var Sealious = require('sealious')
-
-module.exports = {
- test_init: function() {
- },
- test_start: function() {
- describe("Chip", function() {
- /*
- it("configures chip", function(done) {
- Chip(true, "test_type_chip", "test_name_chip");
- var chip = Sealious.ChipManager.get_chip("test_type_chip", "test_name_chip")
- console.log(chip)
- chip.prototype.configure({field: "value"});
- if (chip.configuration.field === "value")
- done();
- else
- done(new Error("It didn't return the configuration"))
-
- //test_chip.configure({field: "test_value"});
-
- })
-*/
- })
- }
-}
\ No newline at end of file
diff --git a/tests/unit-tests/config-manager-test.js b/tests/unit-tests/config-manager-test.js
deleted file mode 100644
index 002bbb4b..00000000
--- a/tests/unit-tests/config-manager-test.js
+++ /dev/null
@@ -1,62 +0,0 @@
-var Sealious = require("sealious");
-
-module.exports = {
- test_init: function() {
-
- },
- test_start: function() {
- describe("ConfigManager", function() {
- it("sets config with arguments.length === 1", function(done) {
- try {
- Sealious.ConfigManager.set_config("some_key");
- done();
- }
- catch (e) {
- done(new Error(e));
- }
- })
- it("sets config with arguments.length === 2 and uses modify_config private function", function(done) {
- try {
- Sealious.ConfigManager.set_config("this.key", "config");
- done();
- }
- catch (e) {
- done(new Error(e));
- }
- })
- it("sets default config with arguments.length === 1", function(done) {
- try {
- Sealious.ConfigManager.set_default_config("some_key");
- done();
- }
- catch (e) {
- done(new Error(e));
- }
- })
- it("gets configuration", function(done) {
- var config = Sealious.ConfigManager.get_configuration("this.key");
- if (config instanceof Object)
- done();
- else
- done(new Error("It didn't return an object"))
- })
- it("gets dispatcher config", function(done) {
- var dispatcher_config = Sealious.ConfigManager.get_dispatcher_config();
- if (dispatcher_config instanceof Object)
- if (Object.getOwnPropertyNames(dispatcher_config).length === 0)
- done();
- else
- done(new Error("It didn't return an empty object"))
- else
- done(new Error("It didn't return an object"))
- })
- it("gets non existent chip config and returns undefined", function(done) {
- var dispatcher_config = Sealious.ConfigManager.get_chip_config("some_non_existent_longid");
- if (dispatcher_config === undefined)
- done();
- else
- done(new Error("It didn't return undefined"))
- })
- })
- }
-}
\ No newline at end of file
diff --git a/tests/unit-tests/config/config-manager.test.js b/tests/unit-tests/config/config-manager.test.js
new file mode 100644
index 00000000..b3d1a23e
--- /dev/null
+++ b/tests/unit-tests/config/config-manager.test.js
@@ -0,0 +1,80 @@
+"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/context.test.js b/tests/unit-tests/context.test.js
new file mode 100644
index 00000000..75eaa3a4
--- /dev/null
+++ b/tests/unit-tests/context.test.js
@@ -0,0 +1,34 @@
+"use strict";
+const Context = require.main.require("lib/context.js");
+const assert = require("assert");
+
+describe("Sealious.Context", function() {
+ it("returns an Context instance properly (no arguments provided)", function() {
+ const context = new Context();
+ assert.strictEqual(context.ip, null);
+ assert.strictEqual(context.user_id, null);
+ assert(new Date().getTime() - context.timestamp <= 1);
+ assert.strictEqual(context._cached_user_data, false);
+ assert.strictEqual(context.loading_user_data, false);
+ });
+ it("returns an Context instance proreply (with arguments)", function() {
+ const context = new Context(1, "ip", "user_id", "session_id");
+ assert.strictEqual(context.timestamp, 1);
+ assert.strictEqual(context.ip, "ip");
+ assert.strictEqual(context.user_id, "user_id");
+ assert.strictEqual(context.session_id, "session_id");
+ });
+ it("checks if session_id is non-writable", function() {
+ const context = new Context(1, "ip", "user_id", "session_id");
+ assert.throws(
+ function(){
+ context.session_id = 2;
+ },
+ TypeError
+ );
+ });
+ it("checks if _cached_user_data and loading_user_data are not enumerable", function() {
+ const context = new Context();
+ assert.strictEqual(Object.keys(context).length, 3);
+ });
+});
diff --git a/tests/unit-tests/data-structures/field-type-description.test.js b/tests/unit-tests/data-structures/field-type-description.test.js
new file mode 100644
index 00000000..0fffd449
--- /dev/null
+++ b/tests/unit-tests/data-structures/field-type-description.test.js
@@ -0,0 +1,16 @@
+"use strict";
+const locreq = require("locreq")(__dirname);
+const assert = require("assert");
+const FieldTypeDescription = locreq("lib/data-structures/field-type-description.js");
+
+describe("Sealious.FieldTypeDescription", function() {
+ it("returns a FieldTypeDescription object", function() {
+ const ftd = new FieldTypeDescription("a", "b", "c");
+ assert.strictEqual(ftd.summary, "a");
+ assert.strictEqual(ftd.raw_params, "b");
+ assert.strictEqual(ftd.extra_info, "c");
+
+ const ftd2 = new FieldTypeDescription("a", "b");
+ assert.deepEqual(ftd2.extra_info, {});
+ });
+});
diff --git a/tests/unit-tests/data-structures/file.test.js b/tests/unit-tests/data-structures/file.test.js
new file mode 100644
index 00000000..4729e5dd
--- /dev/null
+++ b/tests/unit-tests/data-structures/file.test.js
@@ -0,0 +1,42 @@
+"use strict";
+const locreq = require("locreq")(__dirname);
+const File = locreq("lib/data-structures/file.js");
+const Context = locreq("lib/context.js");
+
+const assert = require("assert");
+
+describe("Sealious.File", function(){
+ it("references a file", function(){
+ assert.doesNotThrow(function() {
+ File.Reference("id", "filename")
+ });
+ });
+ // it("finds a file from id", function(){
+ // // doesn't work
+ // // File.from_id(new Context(), "my_test_file")
+ // // .then(function(result){
+ // // if (result === undefined)
+ // // done();
+ // // else
+ // // done(new Error("Result isn't undefined"))
+ // // })
+ // // .catch(function(error){
+ // // done(new Error(error));
+ // // })
+ // })
+ it("return a new file from db entry", function(){
+ const db_document = {
+ creation_context: new Context(),
+ original_name: "original_name",
+ data: "data",
+ id: "id",
+ mime_type: "mime_type"
+ }
+
+ const result = File.from_db_entry(db_document, "path");
+ assert.strictEqual(result.filename, db_document.original_name);
+ assert.strictEqual(result.data, db_document.data);
+ assert.strictEqual(result.id, db_document.id);
+ assert.strictEqual(result.mime, db_document.mime_type)
+ });
+});
diff --git a/tests/unit-tests/data-structures/subject-path.test.js b/tests/unit-tests/data-structures/subject-path.test.js
new file mode 100644
index 00000000..05a6440b
--- /dev/null
+++ b/tests/unit-tests/data-structures/subject-path.test.js
@@ -0,0 +1,31 @@
+"use strict";
+const locreq = require("locreq")(__dirname);
+const SubjectPath = locreq("lib/data-structures/subject-path.js");
+const assert = require("assert");
+
+describe("SubjectPath", function(){
+
+ it("can be constructed from string", function(){
+ const d = new SubjectPath("foo.bar.baz");
+ assert.strictEqual(d.elements[0], "foo");
+ assert.strictEqual(d.elements[1], "bar");
+ assert.strictEqual(d.elements[2], "baz");
+ });
+
+ it("can be contructed from array", function(){
+ const elements = ["foo", "bar", "baz"];
+ const d = new SubjectPath(elements);
+ assert.strictEqual(d.elements[0], "foo");
+ assert.strictEqual(d.elements[1], "bar");
+ assert.strictEqual(d.elements[2], "baz");
+ });
+
+ it("can be constructed from an instance of itself", function(){
+ const elements = ["foo", "bar", "baz"];
+ const d = new SubjectPath(elements);
+ const d2 = new SubjectPath(d);
+ assert.strictEqual(d2.elements[0], "foo");
+ assert.strictEqual(d2.elements[1], "bar");
+ assert.strictEqual(d2.elements[2], "baz");
+ });
+})
diff --git a/tests/unit-tests/data-structures/virtual-file.test.js b/tests/unit-tests/data-structures/virtual-file.test.js
new file mode 100644
index 00000000..33f90c80
--- /dev/null
+++ b/tests/unit-tests/data-structures/virtual-file.test.js
@@ -0,0 +1,16 @@
+"use strict";
+const locreq = require("locreq")(__dirname);
+
+const assert = require("assert");
+const VirtualFile = locreq("lib/data-structures/virtual-file.js");
+
+describe("Sealious.VirtualFile", function() {
+ it("returns a VirtualFile object", function() {
+ const virtualFile1 = new VirtualFile("a", "b");
+ assert.strictEqual(virtualFile1.content, "a");
+ assert.strictEqual(virtualFile1.mime, "b");
+
+ const virtualFile2 = new VirtualFile("a");
+ assert.strictEqual(virtualFile2.mime, "text/plain");
+ });
+});
diff --git a/tests/unit-tests/datastore.test.js b/tests/unit-tests/datastore.test.js
deleted file mode 100644
index 4dae845c..00000000
--- a/tests/unit-tests/datastore.test.js
+++ /dev/null
@@ -1,21 +0,0 @@
-var Sealious = require("sealious");
-
-module.exports = {
- test_start: function() {
- describe("Sealious.Datastore", function() {
- it("returns a developer error \"not implemented\"", function(done) {
- var func = Sealious.Datastore.return_not_implemented("not implemented");
- try {
- func();
- done("It didn't throw an error at all")
- }
- catch (e) {
- if (e.type === "dev_error")
- done();
- else
- done("It didn't throw a proper error");
- }
- })
- })
- }
-}
\ No newline at end of file
diff --git a/tests/unit-tests/error.test.js b/tests/unit-tests/error.test.js
deleted file mode 100644
index b719c885..00000000
--- a/tests/unit-tests/error.test.js
+++ /dev/null
@@ -1,121 +0,0 @@
-var Sealious = require("sealious");
-
-module.exports = {
- test_init: function() {
-
- },
- test_start: function() {
- describe("Sealious.Errors", function(){
- it("throws a Sealious.Errors.Error", function(done) {
- try{
- throw new Sealious.Errors.Error("This is just an error", {type: "test_error"});
- }
- catch (e) {
- if (e.type === "test_error")
- done();
- else
- done(new Error("It didn't throw a Sealious Error"))
- }
- })
- it("throws a Sealious.Errors.ValidationError", function(done) {
- try{
- throw new Sealious.Errors.ValidationError("This is just an error");
- }
- catch (e) {
- if (e.type === "validation")
- done();
- else
- done(new Error("It didn't throw a Sealious ValidationError"))
- }
- })
- it("throws a Sealious.Errors.ValueExists", function(done) {
- try{
- throw new Sealious.Errors.ValueExists("This is just an error");
- }
- catch (e) {
- if (e.type === "valueExists")
- done();
- else
- done(new Error("It didn't throw a Sealious ValueExists Error"))
- }
- })
- it("throws a Sealious.Errors.InvalidCredentials", function(done) {
- try{
- throw new Sealious.Errors.InvalidCredentials("This is just an error");
- }
- catch (e) {
- if (e.type === "authorization")
- done();
- else
- done(new Error("It didn't throw a Sealious InvalidCredentials Error"))
- }
- })
- it("throws a Sealious.Errors.NotFound", function(done) {
- try{
- throw new Sealious.Errors.NotFound("This is just an error");
- }
- catch (e) {
- if (e.type === "not_found")
- done();
- else
- done(new Error("It didn't throw a Sealious NotFound Error"))
- }
- })
- it("throws a Sealious.Errors.InternalConnectionError", function(done) {
- try{
- throw new Sealious.Errors.InternalConnectionError("This is just an error");
- }
- catch (e) {
- if (e.type === "internal_connection_error")
- done();
- else
- done(new Error("It didn't throw a Sealious InternalConnectionError Error"))
- }
- })
- it("throws a Sealious.Errors.DependencyError", function(done) {
- try{
- throw new Sealious.Errors.DependencyError("This is just an error");
- }
- catch (e) {
- if (e.type === "dependency_error")
- done();
- else
- done(new Error("It didn't throw a Sealious DependencyError Error"))
- }
- })
- it("throws a Sealious.Errors.UnauthorizedRequest", function(done) {
- try{
- throw new Sealious.Errors.UnauthorizedRequest("This is just an error");
- }
- catch (e) {
- if (e.type === "unauthorized_request")
- done();
- else
- done(new Error("It didn't throw a Sealious UnauthorizedRequest Error"))
- }
- })
- it("throws a Sealious.Errors.DeveloperError", function(done) {
- try{
- throw new Sealious.Errors.DeveloperError("This is just an error");
- }
- catch (e) {
- if (e.type === "dev_error")
- done();
- else
- done(new Error("It didn't throw a Sealious DeveloperError"))
- }
- })
- it("throws a Sealious.Errors.BadContext", function(done) {
- try{
- throw new Sealious.Errors.BadContext("This is just an error");
- }
- catch (e) {
- if (e.type === "permission")
- done();
- else
- done(new Error("It didn't throw a Sealious BadContext Error"))
- }
- })
- })
- }
-}
\ No newline at end of file
diff --git a/tests/unit-tests/field-type.boolean.test.js b/tests/unit-tests/field-type.boolean.test.js
deleted file mode 100644
index b371f768..00000000
--- a/tests/unit-tests/field-type.boolean.test.js
+++ /dev/null
@@ -1,86 +0,0 @@
-var Sealious = require("sealious");
-
-module.exports = {
- test_init: function() {},
-
- test_start: function() {
- var field_type_boolean = Sealious.ChipManager.get_chip("field_type", "boolean");
- describe("FieldType.Boolean", function() {
- it("should return the description of the field type", function(done) {
- if (typeof field_type_boolean.declaration.get_description() === "string")
- done();
- else
- done(new Error("But it didn't"));
- });
- it("should check if is_proper_value works correctly (given boolean)", function(done) {
- field_type_boolean.is_proper_value(new Sealious.Context(), {}, true)
- .then(function() {
- done();
- })
- .catch(function(error) {
- done(new Error(error));
- })
- });
- it("should check if is_proper_value works correctly (given 1)", function(done) {
- field_type_boolean.is_proper_value(new Sealious.Context(), {}, 1)
- .then(function() {
- done();
- })
- .catch(function(error) {
- done(new Error(error));
- })
- });
- it("should check if is_proper_value works correctly (given \"true\")", function(done) {
- field_type_boolean.is_proper_value(new Sealious.Context(), {}, "true")
- .then(function() {
- done();
- })
- .catch(function(error) {
- done(new Error(error));
- })
- });
- it("should check if is_proper_value works correctly (given 2)", function(done) {
- field_type_boolean.is_proper_value(new Sealious.Context(), {}, 2)
- .then(function() {
- done(new Error("It didn't throw an error"));
- })
- .catch(function(error) {
- if (error.type === "validation")
- done();
- else
- done(new Error(error));
- })
- });
- it("should encode the value corretly (given boolean)", function(done) {
- if (field_type_boolean.declaration.encode(new Sealious.Context(), {}, true) === true)
- done();
- else
- done(new Error("It didn't parse the value correctly"))
- });
- it("should encode the value corretly (given 1)", function(done) {
- if (field_type_boolean.declaration.encode(new Sealious.Context(), {}, 1) === true)
- done();
- else
- done(new Error("It didn't parse the value correctly"))
- });
- it("should encode the value corretly (given 0)", function(done) {
- if (field_type_boolean.declaration.encode(new Sealious.Context(), {}, 0) === false)
- done();
- else
- done(new Error("It didn't parse the value correctly"))
- });
- it("should encode the value corretly (given \"false\")", function(done) {
- if (field_type_boolean.declaration.encode(new Sealious.Context(), {}, "false") === false)
- done();
- else
- done(new Error("It didn't parse the value correctly"))
- });
- it("should encode the value corretly (given \"true\")", function(done) {
- if (field_type_boolean.declaration.encode(new Sealious.Context(), {}, "true") === true)
- done();
- else
- done(new Error("It didn't parse the value correctly"))
- });
- });
- }
-};
\ No newline at end of file
diff --git a/tests/unit-tests/field-type.color.test.js b/tests/unit-tests/field-type.color.test.js
deleted file mode 100644
index 1b1dafba..00000000
--- a/tests/unit-tests/field-type.color.test.js
+++ /dev/null
@@ -1,92 +0,0 @@
-var Sealious = require("sealious");
-
-module.exports = {
- test_init: function() {},
-
- test_start: function() {
- var field_type_color = Sealious.ChipManager.get_chip("field_type", "color");
- describe("FieldType.Color", function() {
- it("checks if is_proper_value throws an error (wrong value)", function(done) {
- field_type_color.is_proper_value(new Sealious.Context(), {}, "aaaa")
- .then(function() {
- done(new Error("It didn't throw an error"));
- })
- .catch(function(error){
- done();
- })
- })
- it("checks if is_proper_value works correctly (given \"rgb(255, 255, 255)\"", function(done) {
- field_type_color.is_proper_value(new Sealious.Context(), {}, "rgb(255, 255, 255)")
- .then(function() {
- done();
- })
- .catch(function(error){
- done(new Error(error));
- })
- })
- it("checks if is_proper_value works correctly (given \"black\"", function(done) {
- field_type_color.is_proper_value(new Sealious.Context(), {}, "black")
- .then(function() {
- done();
- })
- .catch(function(error){
- done(new Error(error));
- })
- })
- it("checks if is_proper_value works correctly (given \"BLACK\"", function(done) {
- field_type_color.is_proper_value(new Sealious.Context(), {}, "BLACK")
- .then(function() {
- done();
- })
- .catch(function(error){
- done(new Error(error));
- })
- })
- it("checks if is_proper_value works correctly (given \"#000000\"", function(done) {
- field_type_color.is_proper_value(new Sealious.Context(), {}, "#000000")
- .then(function() {
- done();
- })
- .catch(function(error){
- done(new Error(error));
- })
- })
- it("checks if is_proper_value works correctly (given \"{r: 255, g: 255, b: 255}\"", function(done) {
- field_type_color.is_proper_value(new Sealious.Context(), {}, {r: 255, g: 255, b: 255})
- .then(function() {
- done();
- })
- .catch(function(error){
- done(new Error(error));
- })
- })
- it("checks if is_proper_value works correctly (given \"hsla(262, 59%, 81%, 0.5)\"", function(done) {
- field_type_color.is_proper_value(new Sealious.Context(), {}, "hsla(262, 59%, 81%, 0.5)")
- .then(function() {
- done();
- })
- .catch(function(error){
- done(new Error(error));
- })
- })
- it("checks if encode works correctly", function(done){
- if(field_type_color.declaration.encode(new Sealious.Context(), {}, {r: 0, g: 0, b: 0}) === "#000000")
- done();
- else
- done("It didnt work correctly");
- })
- it("checks if encode works correctly", function(done){
- if(field_type_color.declaration.encode(new Sealious.Context(), {}, "black") === "#000000")
- done();
- else
- done("It didnt work correctly");
- })
- it("checks if encode works correctly", function(done){
- if(field_type_color.declaration.encode(new Sealious.Context(), {}, "hsl(0,0%,0%)") === "#000000")
- done();
- else
- done("It didnt work correctly");
- })
- })
- }
-}
\ No newline at end of file
diff --git a/tests/unit-tests/field-type.date.test.js b/tests/unit-tests/field-type.date.test.js
deleted file mode 100644
index a7194c2a..00000000
--- a/tests/unit-tests/field-type.date.test.js
+++ /dev/null
@@ -1,38 +0,0 @@
-var Sealious = require("sealious");
-
-module.exports = {
- test_init: function() {},
-
- test_start: function() {
- var field_type_date = Sealious.ChipManager.get_chip("field_type", "date");
- describe("FieldType.Date", function() {
- it("should return the description of the field type", function(done) {
- if (typeof field_type_date.declaration.get_description() === "string")
- done();
- else
- done(new Error("But it didn't"));
- });
- it("should check if is_proper_value works correctly(given correct date format)", function(done) {
- field_type_date.is_proper_value(new Sealious.Context(), {}, "2015-10-27")
- .then(function() {
- done();
- })
- .catch(function(error) {
- done(new Error(error));
- })
- });
- it("should check if is_proper_value works correctly(given incorrect date format)", function(done) {
- field_type_date.is_proper_value(new Sealious.Context(), {}, "2015/10/27")
- .then(function() {
- done(new Error("It worked correctly"));
- })
- .catch(function(error) {
- if (error.type === "validation")
- done();
- else
- done(new Error(error));
- })
- });
- });
- }
-};
\ No newline at end of file
diff --git a/tests/unit-tests/field-type.datetime.test.js b/tests/unit-tests/field-type.datetime.test.js
deleted file mode 100644
index d07dad7a..00000000
--- a/tests/unit-tests/field-type.datetime.test.js
+++ /dev/null
@@ -1,44 +0,0 @@
-var Sealious = require("sealious");
-
-module.exports = {
- test_init: function() {},
-
- test_start: function() {
- var field_type_datetime = Sealious.ChipManager.get_chip("field_type", "datetime");
- describe("FieldType.Datetime", function() {
- it("should return the description of the field type", function(done) {
- if (typeof field_type_datetime.declaration.get_description() === "string")
- done();
- else
- done(new Error("But it didn't"));
- });
- it("should check if is_proper_value works correctly(given timestamp)", function(done) {
- field_type_datetime.is_proper_value(new Sealious.Context(), {}, 1)
- .then(function() {
- done();
- })
- .catch(function(error) {
- done(new Error(error));
- })
- });
- it("should check if is_proper_value works correctly(given string)", function(done) {
- field_type_datetime.is_proper_value(new Sealious.Context(), {}, "test")
- .then(function() {
- done(new Error("It worked correctly"));
- })
- .catch(function(error) {
- if (error.type === "validation")
- done()
- else
- done(new Error(error));
- })
- });
- it("should check if encode works properly (given \"1\")", function(done) {
- if (field_type_datetime.declaration.encode(new Sealious.Context(), {}, "1") === 1)
- done();
- else
- done(new Error("It didn't parse the value correctly"))
- });
- });
- }
-};
\ No newline at end of file
diff --git a/tests/unit-tests/field-type.email.test.js b/tests/unit-tests/field-type.email.test.js
deleted file mode 100644
index d7b6c1a2..00000000
--- a/tests/unit-tests/field-type.email.test.js
+++ /dev/null
@@ -1,38 +0,0 @@
-var Sealious = require("sealious");
-
-module.exports = {
- test_init: function() {},
-
- test_start: function() {
- var field_type_email = Sealious.ChipManager.get_chip("field_type", "email");
- describe("FieldType.Email", function() {
- it("should return the description of the field type", function(done) {
- if (typeof field_type_email.declaration.get_description() === "string")
- done();
- else
- done(new Error("But it didn't"));
- });
- it("should check if is_proper_value works correctly(given correct date format)", function(done) {
- field_type_email.is_proper_value(new Sealious.Context(), {}, "test@mail.com")
- .then(function() {
- done();
- })
- .catch(function(error) {
- done(new Error(error));
- })
- });
- it("should check if is_proper_value works correctly(given incorrect date format)", function(done) {
- field_type_email.is_proper_value(new Sealious.Context(), {}, "test")
- .then(function() {
- done(new Error("It worked correctly"));
- })
- .catch(function(error) {
- if (error.type === "validation")
- done();
- else
- done(new Error(error));
- })
- });
- });
- }
-};
\ No newline at end of file
diff --git a/tests/unit-tests/field-type.file.test.js b/tests/unit-tests/field-type.file.test.js
deleted file mode 100644
index f5339bc2..00000000
--- a/tests/unit-tests/field-type.file.test.js
+++ /dev/null
@@ -1,77 +0,0 @@
-var Sealious = require("sealious");
-
-module.exports = {
- test_init: function() {
-
- },
- test_start: function() {
- var field_type_file = Sealious.ChipManager.get_chip("field_type", "file");
- describe("FieldType.File", function() {
- it("returns undefined", function(done) {
- if (field_type_file.declaration.is_proper_value(new Sealious.Context(), {}, undefined) === undefined)
- done();
- else
- done(new Error("It didn't return undefined"));
- })
- it("accepts given value (which is an instance of Sealious.File)", function(done) {
- field_type_file.is_proper_value(new Sealious.Context(), {}, new Sealious.File())
- .then(function(){
- done();
- })
- })
- it("accepts given value (which is an object with filename and data attributes)", function(done) {
- var value = {
- filename: "test_filename",
- data: new Buffer(1)
- }
- field_type_file.is_proper_value(new Sealious.Context(), {}, value)
- .then(function(){
- done();
- })
- })
- it("rejects given value (which is an empty object)", function(done) {
- field_type_file.is_proper_value(new Sealious.Context(), {}, {})
- .then(function() {
- done(new Error("It didn't reject the value"));
- })
- .catch(function(error) {
- done();
- })
- })
- it("rejects given value (which is an array)", function(done) {
- field_type_file.is_proper_value(new Sealious.Context(), {}, [])
- .then(function() {
- done(new Error("It didn't reject the value"));
- })
- .catch(function(error) {
- done();
- })
- })
- /*
- it("checks if encode works correctly", function(done) {
- // to add
- //console.log(field_type_file.declaration.encode(new Sealious.Context(), {}, "test"))
-
- })
-*/
- it("checks if encode works correctly (value_in_code is false)", function(done) {
- if (field_type_file.declaration.encode(new Sealious.Context(), {}, false) === null)
- done();
- else
- done(new Error("It didn't return null"));
- })
- it("checks if decode works correctly (value_in_database is false, params.no_file_value is not given)", function(done) {
- if (field_type_file.declaration.decode(new Sealious.Context(), {}, false) === undefined)
- done();
- else
- done(new Error("It didn't return null"));
- })
- it("checks if decode works correctly (value_in_database is false, params.no_file_value is given)", function(done) {
- if (field_type_file.declaration.decode(new Sealious.Context(), {no_file_value: "test"}, false) === "test")
- done();
- else
- done(new Error("It didn't return null"));
- })
- })
- }
-}
\ No newline at end of file
diff --git a/tests/unit-tests/field-type.float.test.js b/tests/unit-tests/field-type.float.test.js
deleted file mode 100644
index cc86276a..00000000
--- a/tests/unit-tests/field-type.float.test.js
+++ /dev/null
@@ -1,44 +0,0 @@
-var Sealious = require("sealious");
-
-module.exports = {
- test_init: function() {},
-
- test_start: function() {
- var field_type_float = Sealious.ChipManager.get_chip("field_type", "float");
- describe("FieldType.Float", function() {
- it("should return the description of the field type", function(done) {
- if (typeof field_type_float.declaration.get_description() === "string")
- done();
- else
- done(new Error("But it didn't"));
- });
- it("should check if is_proper_value works correctly", function(done) {
- field_type_float.is_proper_value(new Sealious.Context(), {}, 2.5)
- .then(function() {
- done();
- })
- .catch(function(error) {
- done(new Error(error));
- })
- });
- it("should return error because new_value is not an integer", function(done) {
- field_type_float.is_proper_value(new Sealious.Context(), {}, "janusz")
- .then(function() {
- done("But it didn't");
- })
- .catch(function(error){
- if (error.type === "validation")
- done();
- else
- done(new Error(error));
- })
- });
- it("should check if encode works properly (given \"2\")", function(done) {
- if (field_type_float.declaration.encode(new Sealious.Context(), {}, "2.5") === 2.5)
- done();
- else
- done(new Error("It didn't parse the value correctly"));
- });
- });
- }
-};
\ No newline at end of file
diff --git a/tests/unit-tests/field-type.hashed-text.test.js b/tests/unit-tests/field-type.hashed-text.test.js
deleted file mode 100644
index 44afe092..00000000
--- a/tests/unit-tests/field-type.hashed-text.test.js
+++ /dev/null
@@ -1,65 +0,0 @@
-var Sealious = require("sealious");
-var crypto = require('crypto');
-
-module.exports = {
- test_start: function() {
- var field_type_hashed_text = Sealious.ChipManager.get_chip("field_type", "hashed-text");
- describe("FieldType.HashedText", function() {
- it("should return the description of the field type", function(done) {
- if (typeof field_type_hashed_text.declaration.get_description() === "string")
- done();
- else
- done(new Error("But it didn't"));
- });
- it("accepts given password ('pas1sw24rd1')", function(done) {
- field_type_hashed_text.is_proper_value(new Sealious.Context(), {}, "pas1sw24rd1")
- .then(function() {
- done();
- })
- .catch(function(error) {
- done(new Error(error));
- })
- });
- it("accepts given password ('pas1sw24rd1')", function(done) {
- field_type_hashed_text.is_proper_value(new Sealious.Context(), {digits: 3}, "pas1sw24rd1")
- .then(function() {
- done();
- })
- .catch(function(error) {
- done(new Error(error));
- })
- });
- it("accepts given password ('PAs1sW24rD1')", function(done) {
- field_type_hashed_text.is_proper_value(new Sealious.Context(), {capitals: 3}, "PAs1sW24rD1")
- .then(function() {
- done();
- })
- .catch(function(error) {
- done(new Error(error));
- })
- });
- it("accepts given password ('PaSw0rd23')", function(done) {
- field_type_hashed_text.is_proper_value(new Sealious.Context(), {capitals: 2, digits: 3}, "PaSw0rd23")
- .then(function() {
- done();
- })
- .catch(function(error) {
- done(new Error(error));
- })
- });
- it("resolved with a hash (algorithm: 'md5', salt: '')", function(done) {
- field_type_hashed_text.encode(new Sealious.Context(), {}, "test")
- .then(function(result){
- crypto.pbkdf2("test", "", 4096, 64, "md5", function(err, key){
- if (err) done(new Error(err));
-
- key.toString('hex') === result ? done() : done(new Error("Wrong hash"))
- });
- })
- .catch(function(error){
- done(new Error(error))
- })
- })
- })
- }
-}
\ No newline at end of file
diff --git a/tests/unit-tests/field-type.int.test.js b/tests/unit-tests/field-type.int.test.js
deleted file mode 100644
index 3126c92b..00000000
--- a/tests/unit-tests/field-type.int.test.js
+++ /dev/null
@@ -1,44 +0,0 @@
-var Sealious = require("sealious");
-
-module.exports = {
- test_init: function() {},
-
- test_start: function() {
- var field_type_int = Sealious.ChipManager.get_chip("field_type", "int");
- describe("FieldType.Int", function() {
- it("should return the description of the field type", function(done) {
- if (typeof field_type_int.declaration.get_description() === "string")
- done();
- else
- done(new Error("But it didn't"));
- });
- it("should check if is_proper_value works correctly", function(done) {
- field_type_int.is_proper_value(new Sealious.Context(), {}, 2)
- .then(function() {
- done();
- })
- .catch(function(error) {
- done(new Error(error));
- })
- });
- it("should return error because new_value is not an integer", function(done) {
- field_type_int.is_proper_value(new Sealious.Context(), {}, "janusz")
- .then(function() {
- done("But it didn't");
- })
- .catch(function(error){
- if (error.type === "validation")
- done();
- else
- done(new Error(error));
- })
- });
- it("should check if encode works properly (given \"2\")", function(done) {
- if (field_type_int.declaration.encode(new Sealious.Context(), {}, "2") === 2)
- done();
- else
- done(new Error("It didn't parse the value correctly"));
- });
- });
- }
-};
\ No newline at end of file
diff --git a/tests/unit-tests/field-type.reference.test.js b/tests/unit-tests/field-type.reference.test.js
deleted file mode 100644
index dfdcbde2..00000000
--- a/tests/unit-tests/field-type.reference.test.js
+++ /dev/null
@@ -1,146 +0,0 @@
-var Sealious = require("sealious");
-
-module.exports = {
- test_init: function() {
- var listable = new Sealious.ChipTypes.ResourceType({
- name: "testable",
- })
-
- },
-
- test_start: function() {
- var field_type_reference = Sealious.ChipManager.get_chip("field_type", "reference");
- describe("FieldType.Reference", function() {
- it("checks if is_proper_declaration works correctly", function(done) {
- var declar = {
- "name": "string",
- "allowed_types": ["testable"]
- }
- try {
- field_type_reference.declaration.is_proper_declaration(declar)
- done();
- }
- catch (e) {
- done(new Error(e));
- }
- })
- it("checks if is_proper_declaration throws an error (non existing type)", function(done) {
- var declar = {
- "name": "string",
- "allowed_types": ["wrong_type"]
- }
- try {
- field_type_reference.declaration.is_proper_declaration(declar)
- done("It didn't throw an error");
- }
- catch (e) {
- if (e.type === "dev_error")
- done();
- else
- done(new Error(e));
-
- }
- })
- it("checks if is_proper_declaration throws an error (wrong attribute)", function(done) {
- var declar = {
- "nam": "string",
- "allowed_types": ["testable"]
- }
- try {
- field_type_reference.declaration.is_proper_declaration(declar)
- done("It didn't throw an error");
- }
- catch (e) {
- if (e.type === "dev_error")
- done();
- else
- done(new Error(e));
-
- }
- })
- it("checks if is_proper_value throws an error (no type in value argument)", function(done) {
- field_type_reference.is_proper_value(new Sealious.Context(), { allowed_types: ["testable"] }, {})
- .then(function() {
- done(new Error("It didn't throw an error"));
- })
- .catch(function(error){
- if(error.type === "validation")
- done();
- else
- done(new Error(error));
- })
- })
- it("checks if is_proper_value throws an error (wrong type given in value argument)", function(done) {
- field_type_reference.is_proper_value(new Sealious.Context(), { allowed_types: ["testable"] }, {type: "testabl"})
- .then(function() {
- done(new Error("It didn't throw an error"));
- })
- .catch(function(error){
- if(error.type === "validation")
- done();
- else
- done(new Error(error));
- })
- })
- /* TO DO
- it("checks if is_proper_value throws an error (wrong type given in value argument)", function(done) {
- field_type_reference.is_proper_value(new Sealious.Context(), { allowed_types: ["testable"] }, {type: "testable", data: 1})
- .then(function() {
- done();
- })
- .catch(function(error){
- if(error.type === "validation")
- done();
- else
- done(new Error(error));
- })
- })
- */
- it("checks if is_proper_value works corectly (value is not an object, not found given type)", function(done) {
- field_type_reference.is_proper_value(new Sealious.Context(), { allowed_types: ["testable"] }, "testable")
- .then(function(result) {
- done();
- })
- .catch(function(error){
- if(error.type === "validation")
- done();
- else
- done(new Error(error));
- })
- })
- //for some reason these tests don't cover the reference field type :/
- it("checks if encode works correctly (resolves a promise with value_in_code which is NOT and instance of Object", function(done){
- field_type_reference.encode(new Sealious.Context(), {}, "test")
- .then(function(result){
- if (result === "test")
- done();
- else
- done(new Error("It didn't resolved correctly"));
- })
- })
- it("checks if decode works correctly (resolves a promise with value_in_db not defined)", function(done){
- field_type_reference.encode(new Sealious.Context(), {}, undefined)
- .then(function(result){
- if (result === undefined)
- done();
- else
- done(new Error("It didn't resolved correctly"));
- })
- })
- it("checks if decode works correctly (resolves a promise with value_in_db not defined)", function(done){
- Sealious.ResourceManager.create(new Sealious.Context(), "never_fails_resource", {
- "#success": "specific_value"
- })
- .then(function(created_resource) {
- field_type_reference.encode(new Sealious.Context(), {}, created_resource.id)
- .then(function(result){
- if (created_resource.id === result)
- done();
- else
- done(new Error("It didn't return the correct value"))
- })
- })
- })
- })
- }
-}
\ No newline at end of file
diff --git a/tests/unit-tests/field-type.test.js b/tests/unit-tests/field-type.test.js
index 1ed384ee..e840149e 100644
--- a/tests/unit-tests/field-type.test.js
+++ b/tests/unit-tests/field-type.test.js
@@ -1,272 +1,263 @@
-var Sealious = require("sealious");
-
+"use strict";
+var assert_no_error = require("../util/assert-no-error.js");
module.exports = {
- test_init: function() {
+ test_init: function(){
new Sealious.ChipTypes.FieldType({
name: "test_field_type"
});
new Sealious.ChipTypes.FieldType({
name: "rejecting_father",
- is_proper_value: function(accept, reject) {
+ is_proper_value: function(accept, reject){
reject("Rejected by the father");
},
- encode: function() {
- return "from_father"
+ encode: function(){
+ return "from_father";
},
- decode: function() {
- return "from_father"
+ decode: function(){
+ return "from_father";
},
- get_description: function() {
- return "from_father"
+ get_description: function(){
+ return "from_father";
}
- })
+ });
new Sealious.ChipTypes.FieldType({
name: "accepting_son",
extends: "rejecting_father",
- is_proper_value: function(accept) {
+ is_proper_value: function(accept){
accept();
},
- encode: function() {
+ encode: function(){
return "from_son";
},
- decode: function() {
+ decode: function(){
return "from_son";
},
- get_description: function() {
- return "from_son"
+ get_description: function(){
+ return "from_son";
}
- })
+ });
new Sealious.ChipTypes.FieldType({
name: "hesitant_daughter",
extends: "rejecting_father"
- })
+ });
},
- test_start: function() {
- describe("FieldType", function() {
+ test_start: function(){
+ describe("FieldType", function(){
var test_field_type = Sealious.ChipManager.get_chip("field_type", "test_field_type");
var but_it_didnt = new Error("But it didn't");
- describe("default methods", function() {
- describe("when not overwritten", function() {
- it("should use default .is_proper_value", function(done) {
- var return_value = test_field_type.is_proper_value("any_value")
- .then(function() {
- done();
- }).catch(function(error) {
- done(new Error("But it rejected."));
- })
- })
+ describe("default methods", function(){
+ describe("when not overwritten", function(){
+
+ it("should use default .is_proper_value", function(done){
+ var result = test_field_type.is_proper_value("any_value");
+ assert_no_error(result, done);
+ });
- it("should use default .is_proper_declaration", function(done) {
+ it("should use default .is_proper_declaration", function(done){
var return_value = test_field_type.is_proper_declaration({});
if (typeof return_value != "boolean" || return_value != true) {
done(but_it_didnt);
} else {
done();
}
});
- it("should use default .encode", function(done) {
+ it("should use default .encode", function(done){
var what_its_been_fed = "dogfood";
test_field_type.encode(new Sealious.Context(), {}, what_its_been_fed)
- .then(function(encoded) {
- if (encoded == what_its_been_fed) {
- done();
- } else {
- done(new Error("But it returnet something else"));
- }
- }).catch(function(error) {
- console.error(error);
- done(new Error("but it threw an error"));
- })
+ .then(function(encoded){
+ if (encoded == what_its_been_fed) {
+ done();
+ } else {
+ done(new Error("But it returned something else"));
+ }
+ }).catch(done);
});
- it("should use default .decode", function(done) {
+ it("should use default .decode", function(done){
var what_its_been_fed = "dogfood";
test_field_type.decode(new Sealious.Context(), {}, what_its_been_fed)
- .then(function(decoded) {
- if (decoded == what_its_been_fed) {
- done();
- } else {
- done(new Error("But it returnett something else"));
- }
- }).catch(function(error) {
- console.error(error);
- done(new Error("but it threw an error"));
- })
+ .then(function(decoded){
+ if (decoded == what_its_been_fed) {
+ done();
+ } else {
+ done(new Error("But it returned something else"));
+ }
+ }).catch(done);
});
- it("should use default .get_description", function(done) {
+ it("should use default .get_description", function(done){
test_field_type.get_description()
- .then(function(description) {
- if (description.summary == "test_field_type") {
- done();
- } else {
- done(new Error("But it didn't"));
- }
- });
- })
- })
+ .then(function(description){
+ if (description.summary == "test_field_type") {
+ done();
+ } else {
+ done(new Error("But it didn't"));
+ }
+ });
+ });
+ });
- describe("when overwritten", function() {
+ describe("when overwritten", function(){
var rejecting_father = Sealious.ChipManager.get_chip("field_type", "rejecting_father");
- it("should use the custom .is_proper_value method", function(done) {
+ it("should use the custom .is_proper_value method", function(done){
rejecting_father.is_proper_value("any_value")
- .then(function() {
- done(new Error("But it didn't (should have been rejected in this case, but wasn't)"));
- }).catch(function() {
- done();
- });
+ .then(function(){
+ done(new Error("But it didn't (should have been rejected in this case, but wasn't)"));
+ }).catch(function(error){
+ done();
+ });
});
- it("should use the custom .encode method", function(done) {
+ it("should use the custom .encode method", function(done){
rejecting_father.encode(new Sealious.Context(), {}, "anything")
- .then(function(encoded_value) {
- if (encoded_value == "from_father") {
- done();
- } else {
- done(new Error("But it didn't"));
- }
- })
+ .then(function(encoded_value){
+ if (encoded_value == "from_father") {
+ done();
+ } else {
+ done(new Error("But it didn't"));
+ }
+ });
});
- it("should use the custom .decode method", function(done) {
+ it("should use the custom .decode method", function(done){
rejecting_father.decode("anything")
- .then(function(decoded_value) {
- if (decoded_value == "from_father") {
- done();
- } else {
- done(new Error("But it didn't"));
- }
- })
+ .then(function(decoded_value){
+ if (decoded_value == "from_father") {
+ done();
+ } else {
+ done(new Error("But it didn't"));
+ }
+ });
});
- it("should use the custom .get_description method", function(done) {
+ it("should use the custom .get_description method", function(done){
rejecting_father.get_description()
- .then(function(description) {
- if (description.summary == "from_father") {
- done();
- } else {
- done(new Error("But it didn't"));
- }
- });
+ .then(function(description){
+ if (description.summary == "from_father") {
+ done();
+ } else {
+ done(new Error("But it didn't"));
+ }
+ });
});
- })
- })
+ });
+ });
- describe("inheritance", function() {
+ describe("inheritance", function(){
var accepting_son = Sealious.ChipManager.get_chip("field_type", "accepting_son");
var hesitant_daughter = Sealious.ChipManager.get_chip("field_type", "hesitant_daughter");
- it("should inherit is_proper_value", function(done) {
+ it("should inherit is_proper_value", function(done){
accepting_son.is_proper_value(new Sealious.Context(), {}, "any")
- .then(function() {
- done(new Error("accepting_son accepted the value, which should have been rejected by his rejecting_father"));
- }).catch(function(error) {
- if (error.message == "Rejected by the father") {
- done();
- } else {
- done(new Error("But it didn't - it returned `" + error + "but should have returned \"Rejected by the father\""));
- }
- })
+ .then(function(){
+ done(new Error("accepting_son accepted the value, which should have been rejected by his rejecting_father"));
+ }).catch(function(error){
+ if (error.message == "Rejected by the father") {
+ done();
+ } else {
+ done(new Error("But it didn't - it returned '" + error + "' but should have returned \"Rejected by the father\""));
+ }
+ });
});
- it("should use parent's is_proper_value when not having its own", function(done) {
+ it("should use parent's is_proper_value when not having its own", function(done){
hesitant_daughter.is_proper_value(new Sealious.Context(), {}, "any")
- .then(function() {
- done(new Error("But it accepted value, which should have been rejected by rejecting_father"));
- }).catch(function(error) {
- if (error.message == "Rejected by the father") {
- done();
- } else {
- done(new Error("But it didn't"));
- }
- });
+ .then(function(){
+ done(new Error("But it accepted value, which should have been rejected by rejecting_father"));
+ }).catch(function(error){
+ if (error.message == "Rejected by the father") {
+ done();
+ } else {
+ done(new Error("But it didn't"));
+ }
+ });
});
- it("should use child's .encode method when a child has it's own encode method", function(done) {
+ it("should use child's .encode method when a child has it's own encode method", function(done){
accepting_son.encode(new Sealious.Context(), {}, "anything")
- .then(function(encoded_value) {
- if (encoded_value == "from_son") {
- done();
- } else {
- done(new Error("But it didn't"));
- }
- });
+ .then(function(encoded_value){
+ if (encoded_value == "from_son") {
+ done();
+ } else {
+ done(new Error("But it didn't"));
+ }
+ });
});
- it("should use parent's .encode method when a child does not have it's own", function(done) {
+ it("should use parent's .encode method when a child does not have it's own", function(done){
hesitant_daughter.encode(new Sealious.Context(), {}, "anything")
- .then(function(encoded_value) {
- if (encoded_value == "from_father") {
- done();
- } else {
- done(new Error("But it didn't"));
- }
- })
+ .then(function(encoded_value){
+ if (encoded_value == "from_father") {
+ done();
+ } else {
+ done(new Error("But it didn't"));
+ }
+ });
});
- it("should use child's .decode method when a child has it's own decode method", function(done) {
+ it("should use child's .decode method when a child has it's own decode method", function(done){
accepting_son.decode("anything")
- .then(function(decoded_value) {
- if (decoded_value == "from_son") {
- done();
- } else {
- done(new Error("But it didn't"));
- }
- });
+ .then(function(decoded_value){
+ if (decoded_value == "from_son") {
+ done();
+ } else {
+ done(new Error("But it didn't"));
+ }
+ });
});
- it("should use parent's .decode method when a child does not have it's own", function(done) {
+ it("should use parent's .decode method when a child does not have it's own", function(done){
hesitant_daughter.decode("anything")
- .then(function(decoded_value) {
- if (decoded_value == "from_father") {
- done();
- } else {
- done(new Error("But it didn't"));
- }
- })
+ .then(function(decoded_value){
+ if (decoded_value == "from_father") {
+ done();
+ } else {
+ done(new Error("But it didn't"));
+ }
+ });
});
- it("should use child's .get_description method when a child has it's own .get_description method", function(done) {
+ it("should use child's .get_description method when a child has it's own .get_description method", function(done){
accepting_son.get_description()
- .then(function(description) {
- if (description.summary == "from_son") {
- done();
- } else {
- done(new Error("But it didn't"));
- }
- });
+ .then(function(description){
+ if (description.summary == "from_son") {
+ done();
+ } else {
+ done(new Error("But it didn't"));
+ }
+ });
});
- it("should use parent's .get_description method when a child does not have it's own", function(done) {
+ it("should use parent's .get_description method when a child does not have it's own", function(done){
hesitant_daughter.get_description()
- .then(function(description) {
- if (description.summary == "from_father") {
- done();
- } else {
- done(new Error("But it didn't"));
- }
- })
+ .then(function(description){
+ if (description.summary == "from_father") {
+ done();
+ } else {
+ done(new Error("But it didn't"));
+ }
+ });
});
});
-
+
});
}
-}
+};
diff --git a/tests/unit-tests/field-type.text.test.js b/tests/unit-tests/field-type.text.test.js
deleted file mode 100644
index 9cf10e38..00000000
--- a/tests/unit-tests/field-type.text.test.js
+++ /dev/null
@@ -1,80 +0,0 @@
-var Sealious = require("sealious");
-
-module.exports = {
- test_init: function() {},
-
- test_start: function() {
- var field_type_text = Sealious.ChipManager.get_chip("field_type", "text");
- describe("FieldType.Text", function() {
- it("returns the description of the field type", function(done) {
- if (typeof field_type_text.declaration.get_description(new Sealious.Context(), {max_length: 10}) === "string")
- done();
- else
- done(new Error("But it didn't"));
- });
- it("checks if is_proper_value works correctly", function(done) {
- field_type_text.is_proper_value(new Sealious.Context(), {}, 2)
- .then(function() {
- done();
- })
- .catch(function(error) {
- done(new Error(error));
- })
- });
- it("checks if is_proper_value works correctly", function(done) {
- field_type_text.is_proper_value(new Sealious.Context(), {max_length: 5}, "123")
- .then(function() {
- done();
- })
- .catch(function(error) {
- done(new Error(error));
- })
- });
- it("checks if is_proper_value works correctly", function(done) {
- field_type_text.is_proper_value(new Sealious.Context(), {max_length: 5}, "asdfghjkl")
- .then(function() {
- done(new Error("It worked correctly"));
- })
- .catch(function(error) {
- if (error.type === "validation")
- done();
- else
- done(new Error(error));
- })
- });
- it("checks if encode works properly (sanitizes html)", function(done) {
- field_type_text.declaration.encode(new Sealious.Context(), {strip_html: true}, "outside<script>alert(\"a\")</script>")
- .then(function(result) {
- if (result === "outside")
- done();
- else
- done("It didn't sanitize the string")
- })
- .catch(function(error) {
- done(new Error(error));
- })
- });
- it("resolved with null when value_in_code is null", function(done) {
- field_type_text.declaration.encode(new Sealious.Context(), {}, null)
- .then(function(result) {
- if (result === null)
- done();
- else
- done(new Error("It didn't resolve with null"))
- })
- .catch(function(error) {
- done(new Error(error));
- })
- })
- it("checks if encode works properly", function(done) {
- field_type_text.declaration.encode(new Sealious.Context(), {}, {})
- .then(function(result) {
- done();
- })
- .catch(function(error) {
- done(new Error(error));
- })
- });
- });
- }
-};
\ No newline at end of file
diff --git a/tests/unit-tests/file.test.js b/tests/unit-tests/file.test.js
deleted file mode 100644
index 255c6bf1..00000000
--- a/tests/unit-tests/file.test.js
+++ /dev/null
@@ -1,57 +0,0 @@
-var Sealious = require("sealious");
-
-module.exports = {
- test_init: function() {
- Sealious.File(new Sealious.Context(), "filename", "just_data", "my_test_file", false)
- },
- test_start: function() {
- describe("Sealious.File", function() {
- it("references a file", function(done) {
- try {
- Sealious.File.Reference("id", "filename")
- done();
- }
- catch (e) {
- done(new Error(e));
- }
- });
- it("finds a file from id", function(done) {
- console.log("do sprawdzenia")
- Sealious.File.from_id(new Sealious.Context(), "my_test_file")
- .then(function(result) {
- if (result === undefined)
- done();
- else
- done(new Error("Result isn't undefined"))
- })
- .catch(function(error) {
- done(new Error(error));
- })
- })
- it("return a new file from db entry", function(done) {
- var db_document = {
- creation_context: new Sealious.Context(),
- original_name: "original_name",
- data: "data",
- id: "id",
- mime_type: "mime_type"
- }
-
- var result = Sealious.File.from_db_entry(db_document, "path");
- if (result.filename === db_document.original_name)
- if (result.data === db_document.data)
- if (result.id === db_document.id)
- if (result.mime === db_document.mime_type)
- done();
- else
- done(new Error("Wrong mime type"))
- else
- done(new Error("Wrong id"))
- else
- done(new Error("Wrong data"))
- else
- done(new Error("Wrong filename"))
- })
- })
- }
-}
\ No newline at end of file
diff --git a/tests/unit-tests/logger/logger.test.js b/tests/unit-tests/logger/logger.test.js
new file mode 100644
index 00000000..d524d0db
--- /dev/null
+++ b/tests/unit-tests/logger/logger.test.js
@@ -0,0 +1,26 @@
+"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/resource-manager.test.js b/tests/unit-tests/resource-manager.test.js
deleted file mode 100644
index e688ff5d..00000000
--- a/tests/unit-tests/resource-manager.test.js
+++ /dev/null
@@ -1,760 +0,0 @@
-var Sealious = require("sealious");
-var ResourceManager = Sealious.ResourceManager;
-var assert = require("assert");
-var deepEqual = require("deep-equal");
-
-module.exports = {
- test_init: function() {
- // Creating resource always fails
-
- var listable = new Sealious.ResourceType({
- name: "listable"
- })
-
- var always_fails = new Sealious.ChipTypes.FieldType({
- name: "always_fails",
- is_proper_value: function(accept, reject, context, value_in_code) {
- reject();
- }
- })
-
- var one_field_always_fails = new Sealious.ResourceType({
- name: "one_field_always_fails",
- fields: [{
- name: "#fail",
- type: "always_fails"
- }]
- });
-
- //Creating resource never fails
- var never_fails = new Sealious.FieldType({
- name: "never_fails",
- is_proper_value: function(accept, reject, context, value_in_code) {
- accept();
- }
- })
-
- var never_fails_resource = new Sealious.ResourceType({
- name: "never_fails_resource",
- fields: [{
- name: "#success",
- type: "never_fails"
- }, ]
- });
-
- var requires_old_value = new Sealious.FieldType({
- name: "requires_old_value",
- is_proper_value: function(accept, reject, context, params, new_value, old_value) {
- if (old_value === undefined) {
- reject("No old value provided!");
- } else {
- accept();
- }
- },
- old_value_sensitive_methods: {
- is_proper_value: true
- }
- })
-
- var rejects_with_old_value = new Sealious.FieldType({
- name: "rejects_with_old_value",
- is_proper_value: function(accept, reject, context, params, new_value, old_value) {
- if (old_value === undefined) {
- accept();
- } else {
- reject("Old value provided");
- }
- },
- old_value_sensitive_methods: {
- is_proper_value: false
- }
- })
-
- var always_the_same = new Sealious.FieldType({
- name: "always_the_same",
- is_proper_value: function(accept, reject, context, params, new_value, old_value) {
- if (old_value === null) {
- accept();
- } else if (new_value == old_value) {
- accept();
- } else {
- reject();
- }
- },
- old_value_sensitive_methods: {
- is_proper_value: true
- }
- })
-
- var old_value_sensitive_resource = new Sealious.ResourceType({
- name: "old_value_sensitive",
- fields: [{
- name: "value",
- type: "requires_old_value"
- }, ]
- })
-
- var old_value_insensitive_resource = new Sealious.ResourceType({
- name: "old_value_insensitive",
- fields: [{
- name: "value",
- type: "rejects_with_old_value"
- }, ]
- })
-
- var always_the_same_resource = new Sealious.ResourceType({
- name: "always_the_same",
- fields: [{
- name: "value",
- type: "always_the_same"
- }, ]
- })
-
- var multifield_resource = new Sealious.ResourceType({
- name: "multifield",
- fields: [{
- name: "value1",
- type: "text"
- }, {
- name: "value2",
- type: "text"
- }]
- });
-
- var nobody_can_create_me_resource = new Sealious.ResourceType({
- name: "nobody_can_create_me",
- access_strategy: "noone"
- });
-
- var nobody_can_update_me_resource = new Sealious.ResourceType({
- name: "nobody_can_update_me",
- fields: [{
- name: "value",
- type: "text"
- }],
- access_strategy: {
- update: "noone"
- }
- });
-
- var nobody_can_delete_me_resource = new Sealious.ResourceType({
- name: "nobody_can_delete_me",
- fields: [{
- name: "value",
- type: "text"
- }],
- access_strategy: {
- delete: "noone"
- }
- });
- var nobody_can_list_me_resource = new Sealious.ResourceType({
- name: "nobody_can_list_me",
- fields: [{
- name: "value",
- type: "text"
- }],
- access_strategy: {
- retrieve: "noone"
- }
- });
- var item_sensitive_access_strategy = new Sealious.AccessStrategy({
- name: "item_sensitive",
- checker_function: function(context, item) {
- if (item !== undefined) {
- return Promise.resolve();
- } else {
- return Promise.reject(new Sealious.Errors.BadContext("No item provided"));
- }
- },
- item_sensitive: true
- })
-
- var item_sensitive_access_strategy_second = new Sealious.AccessStrategy({
- name: "item_sensitive_second",
- checker_function: function(context, item) {
- return Promise.reject(new Sealious.Errors.BadContext("No item provided"));
-
- },
- item_sensitive: true
- })
-
- var item_sensitive_resource = new Sealious.ResourceType({
- name: "item_sensitive",
- fields: [{
- name: "value",
- type: "text"
- }],
- access_strategy: "item_sensitive"
-
- })
-
- var item_sensitive_resource_second = new Sealious.ResourceType({
- name: "item_sensitive_second",
- fields: [{
- name: "value",
- type: "text"
- }],
- access_strategy: "item_sensitive_second"
-
- })
-
- var has_required_field = new Sealious.ResourceType({
- name: "has_required_field",
- fields: [
- {name: "required", type: "int", required: true}
- ]
- })
-
- },
-
- test_start: function() {
-
- describe("ResourceManager", function() {
- var context = new Sealious.Context();
-
- it('should store creation and modification context', function(done) {
- var creation_context = new Sealious.Context();
-
- ResourceManager.create(creation_context, "never_fails_resource", { "#success": "yes" })
- .then(function(created_resource) {
- assert.deepEqual(created_resource.created_context, creation_context.toObject(), "Context info stored in resource's `created_context` attribute should reflect the actual context of creating this resource");
- return Promise.resolve(created_resource.id);
- })
- .then(function(created_resource_id) {
- var modification_context = new Sealious.Context();
- return ResourceManager.patch_resource(modification_context, "never_fails_resource", created_resource_id, { "#success": "yiss" })
- .then(function(patched_resource) {
- assert.deepEqual(patched_resource.last_modified_context, modification_context.toObject(), "Context info stored in resource's `last_modified` attribute should reflect the actual context of last modification to this resource after performing `patch` on it.")
- return Promise.resolve(created_resource_id);
- });
- })
- .then(function(created_resource_id) {
- var update_context = new Sealious.Context();
- ResourceManager.update_resource(update_context, "never_fails_resource", created_resource_id, { "#success": "yiss plis" })
- .then(function(patched_resource) {
- assert.deepEqual(patched_resource.last_modified_context, update_context.toObject(), "Context info stored in resource's `last_modified` attribute should reflect the actual context of last modification to this resource after performing `update` on it.")
- });
- done();
- })
- });
-
- it('throws an error due to field name duplication', function(done) {
- try {
- new Sealious.ChipTypes.ResourceType({
- name: "testing_name_duplication",
- fields: [{
- name: "duplicate_name",
- type: "text"
- },
- {
- name: "duplicate_name",
- type: "text"
- }],
- access_strategy: "item_sensitive"
- })
- }
- catch (e) {
- if (e.type === "dev_error")
- done();
- else(
- done(new Error(e)))
- }
- })
-
- describe(".create", function() {
- it("should create resource", function(done) {
- var context = new Sealious.Context();
- ResourceManager.create(context, "never_fails_resource", {
- "#success": "specific_value"
- })
- .then(function(created_resource) {
- return ResourceManager.get_by_id(new Sealious.Context(), created_resource.id)
- })
- .then(function(gotten_resource) {
- if (gotten_resource.body["#success"] == "specific_value" && deepEqual(context.toObject(), gotten_resource.created_context)) {
- done();
- } else {
- done(new Error("Created resource differs from what was intended to create."))
- }
- }).catch(function(error) {
- done(error)
- })
- })
- it("should resolve with created resource", function(done) {
- var context = new Sealious.Context();
- ResourceManager.create(context, "never_fails_resource", {
- "#success": "specific_value"
- })
- .then(function(created_resource) {
- if (created_resource.body["#success"] == "specific_value" && deepEqual(context.toObject(), created_resource.created_context)) {
- done();
- } else {
- done(new Error(".create resolves with something else than created resource."))
- }
- }).catch(function(error) {
- done(error)
- })
- })
- it("should throw proper error, if given resouce-type name is non-existent", function(done) {
- ResourceManager.create(new Sealious.Context(), "non_existent_resource_type", {})
- .then(function() {
- done(new Error("But it succedded instad of failing"));
- }).catch(function(error) {
- if (error.data.short_message = "chip_not_found") {
- done();
- } else {
- done(new Error("But threw an error that is not an instance of ValidationError"));
- }
- })
- })
- it("should provide resource_type.validate_field_values method with the previous field values, if it is needed", function(done) {
- ResourceManager.create(new Sealious.Context(), "old_value_sensitive", {
- value: "any"
- })
- .then(function(created_resource) {
- done();
- }).catch(function() {
- done(new Error("But it didn't"));
- })
- });
- it("should NOT provide resource_type.validate_field_values method with the previous field value if it's not needed", function(done) {
- ResourceManager.create(new Sealious.Context(), "old_value_insensitive", {
- value: "any"
- })
- .then(function() {
- done();
- }).catch(function() {
- done(new Error("But it didn't"));
- })
- });
- it("doesn't create resource, when access_strategy doesn't allow it", function(done) {
- ResourceManager.create(new Sealious.Context(), "nobody_can_create_me", {})
- .then(function() {
- done(new Error("It succedded instead of failing"))
- }).catch(function(error) {
- if (error.type == "permission") {
- done()
- } else {
- done(new Error("It didn't throw proper error."))
- }
- })
- })
- it("should provide access_strategy.check with null if the access_strategy is item_sensitive", function(done) {
- ResourceManager.create(new Sealious.Context(), "item_sensitive", { value: "any" })
- .then(function(created_resource) {
- done();
- }).catch(function(error) {
- if (error.type == "permission") {
- done(new Error("But it didn't"));
- } else {
- done(error);
- }
- })
- });
-
- it('should not create a new resource', function(done) {
- ResourceManager.create(new Sealious.Context(), "one_field_always_fails", { "#fail": "tak" })
- .then(function() {
- done(new Error("It didn't throw an error!"));
- }).catch(function(error) {
- if (error.type == "validation"){
- done();
- } else {
- done(new Error("It did throw an error, but not THE error"));
- }
- });
- });
- });
-
- describe(".delete", function() {
- it("should throw proper error, if given resouce-type name is non-existent", function(done) {
- ResourceManager.delete(new Sealious.Context(), "non_existent_resource_type", "id", {})
- .then(function() {
- done(new Error("But it succedded instad of failing"));
- }).catch(function(error) {
- if (error.type == "validation") {
- done();
- } else {
- done(new Error("But threw an error that is not an instance of ValidationError"));
- }
- });
- });
- it('should delete the resource', function(done) {
- var created_resource_id;
- ResourceManager.create(context, "never_fails_resource", {
- "#success": "tak"
- })
- .then(function(created_resource) {
- created_resource_id = created_resource.id;
- return ResourceManager.delete(context, "never_fails_resource", created_resource_id);
- })
- .then(function() {
- return ResourceManager.get_by_id(new Sealious.Context, created_resource_id);
- })
- .then(function(result) {
- done(new Error("But it didn't"));
- })
- .catch(function(error) {
- if (error.type == "not_found") {
- done();
- } else {
- done(error);
- }
- })
- });
- });
-
- describe(".get_by_id", function() {
- it("should find resource of given id", function(done) {
- ResourceManager.create(new Sealious.Context(), "never_fails_resource", {
- "#success": "specific_value"
- })
- .then(function(created_resource) {
- return ResourceManager.get_by_id(new Sealious.Context(), created_resource.id)
- })
- .then(function(gotten_resource) {
- if (gotten_resource.body["#success"] == "specific_value") {
- done();
- } else {
- done(new Error("It didn't get proper resource."))
- }
- }).catch(function(error) {
- done(error)
- })
- })
- it("should return proper error, if provided id is incorrect", function(done) {
- ResourceManager.get_by_id(new Sealious.Context(), "incorrect_resource_id*!@#R%^&*()")
- .then(function() {
- done(new Error("But it succeded instead of failing"))
- }).catch(function(error) {
- if (error.type = "not_found") {
- done();
- } else {
- done(new Error("But threw an error that is not an instance of NotFoundError"));
- }
- })
- });
- it("doesn't get resource, when access_strategy doesn't allow it", function(done) {
- ResourceManager.create(new Sealious.Context(), "nobody_can_list_me", {})
- .then(function(created_resource) {
- return ResourceManager.get_by_id(new Sealious.Context(), created_resource.id)
- })
- .then(function() {
- done(new Error("It succedded instead of failing"))
- }).catch(function(error) {
- if (error.type == "permission") {
- done()
- } else {
- done(new Error("It didn't throw proper error."))
- }
- })
- })
- });
-
- describe(".list_by_type", function() {
- it("uses a resource with item_sensitive access strategy", function(done) {
- ResourceManager.list_by_type(new Sealious.Context(),"item_sensitive")
- .then(function(){
- done();
- })
- .catch(function(error) {
- done(error);
- });
- });
- it("uses a resource with item_sensitive access strategy and should throw an error", function(done) {
- ResourceManager.create(new Sealious.Context(), "item_sensitive_second", { value: "any" })
- .then(function(created_resource) {
- }).catch(function(error) {
-
- })
-
-
- ResourceManager.list_by_type(new Sealious.Context(),"item_sensitive_second")
- .then(function(ok){
- done();
- })
- .catch(function(error) {
- done(error);
- });
- });
-
- it("throws proper error, if given resouce-type name is non-existent", function(done) {
- ResourceManager.list_by_type(new Sealious.Context(), "non_existent_resource_type")
- .then(function() {
- done(new Error("It succedded instead of failing"));
- })
- .catch(function(error) {
- if (error.type = "validation") {
- done();
- } else {
- done(new Error("It threw an error that is not an instance of ValidationError"));
- }
- });
- })
- it("lists resources of given type", function(done) {
- var promises = [];
- var resource_ids;
- for (var i = 1; i <= 3; i++) {
- var promise = ResourceManager.create(new Sealious.Context(), "listable", {});
- promises.push(promise);
- }
- Promise.all(promises)
- .then(function(created_resources) {
- resource_ids = created_resources.map(function(resource) {
- return resource.id;
- })
- return ResourceManager.list_by_type(new Sealious.Context(), "listable")
- })
- .then(function(listed_resources) {
- var listed_resources_ids = listed_resources.map(function(resource) {
- return resource.id;
- })
- listed_resources_ids.sort();
- resource_ids.sort();
- if (deepEqual(listed_resources_ids, resource_ids)) {
- done()
- } else if (listed_resources_ids.length != resource_ids.length) {
- done(new Error("It listed wrong amount of resources"))
- } else {
- done(new Error("It didn't return proper resources"))
- }
- })
-
- })
- });
-
- describe(".find", function() {
- it('should find all resources', function(done){
- ResourceManager.find(context)
- .then(function(found_resource){
- if (found_resource[0] !== undefined){
- done();
- } else {
- done(new Error ("It didn't find any resources"));
- }
- })
- .catch(function(error){
- done(error);
- })
- });
- it('should create a new resource and find it', function(done){
- ResourceManager.create(context, "never_fails_resource", { "#success": "absolutely" })
- .then(function(created_resource){
- ResourceManager.find(context, {"#success": created_resource.body["#success"]}, "never_fails_resource")
- .then(function(found_resource){
- if (found_resource[0]["#success"] == "absolutely"){
- done();
- } else if (found_resource[1] !== undefined) {
- done(new Error("Found more resources than should have"))
- } else {
- done(new Error("It didn't find the resource"));
- }
- })
- .catch(function(error){
- done(error);
- })
- })
- });
- it('should create a new resource and find it with without specifing the type', function(done){
- ResourceManager.create(context, "never_fails_resource", { "#success": "absolutely" })
- .then(function(created_resource){
- ResourceManager.find(context, {"#success": created_resource.body["#success"]})
- .then(function(found_resource){
- if (found_resource[0]["#success"] == "absolutely"){
- done();
- } else if (found_resource[1] !== undefined) {
- done(new Error("Found more resourced than should have"))
- } else {
- done(new Error("It didn't find the resource"));
- }
- })
- .catch(function(error){
- done(error);
- })
- })
- });
- it('should not find a resource', function(done){
- ResourceManager.find(context, {"#troll_field": "troll_value"}, "troll_resource_type")
- .then(function(found_resource){
- if (found_resource[0] === undefined){
- done();
- } else {
- done(new Error("It found a resource"));
- }
- })
- .catch(function(error){
- done(error);
- })
- });
- it('should create a new resource it, find it, then delete it and not find it', function(done){
- ResourceManager.create(context, "never_fails_resource", { "#success": "yep" })
- .then(function(created_resource){
- ResourceManager.find(context, {"#success": created_resource.body["#success"]}, "never_fails_resource")
- .then(function(found_resource){
- if (found_resource[0]["#success"] == "yep"){
- ResourceManager.delete(context, "never_fails_resource", found_resource[0]["id"])
- .then(function(success){
- ResourceManager.find(context, {"#success": "yep"}, "never_fails_resource")
- .then(function(found_resource){
- if (found_resource[0] === undefined){
- done();
- } else {
- done(new Error("It found the resource which should be deleted"));
- }
- })
- .catch(function(error){
- done(error);
- })
- })
- .catch(function(error){book.com/
- done(error);
- })
- } else {
- done(new Error("It didn't find the resource after creating it"))
- }
- })
- .catch(function(error){
- done(error);
- })
- })
- });
- });
-
- describe(".patch_resource", function() {
- it("should throw proper error, if given resource-type name is non-existent", function(done) {
- ResourceManager.patch_resource(new Sealious.Context(), "non_existent_resource_type", "id", {})
- .then(function() {
- done(new Error("But it succedded instead of failing"));
- }).catch(function(error) {
- if (error.type = "validation") {
- done();
- } else {
- done(new Error("But threw an error that is not an instance of ValidationError"));
- }
- })
- })
- it("should provide resource_type.validate_field_values method with the previous field value if it is needed", function(done) {
- ResourceManager.create(new Sealious.Context(), "old_value_sensitive", { value: "any" })
- .then(function(created_resource) {
- return ResourceManager.patch_resource(new Sealious.Context(), "old_value_sensitive", created_resource.id, { value: "any2" })
- }).then(function() {
- done();
- }).catch(function() {
- done(new Error("But it didn't."));
- })
- });
- describe("should provide real old value, if old_value is needed", function() {
- it("always_the_same_resource can be patched with the same value it was created", function(done) {
- ResourceManager.create(new Sealious.Context(), "always_the_same", {
- value: 33
- })
- .then(function(created_resource) {
- return ResourceManager.patch_resource(new Sealious.Context(), "always_the_same", created_resource.id, {
- value: 33
- })
- }).then(function() {
- done();
- }).catch(function() {
- done(new Error("But it didn't."));
- })
- });
- it("always_the_same_resource can't be patched with other value than the one it was created with", function(done) {
- ResourceManager.create(new Sealious.Context(), "always_the_same", { value: 33 })
- .then(function(created_resource) {
- return ResourceManager.patch_resource(new Sealious.Context(), "always_the_same", created_resource.id, { value: 42 })
- }).then(function() {
- done(new Error("But it was."));
- }).catch(function() {
- done();
- })
- });
- })
- it("should NOT provide resource_type.validate_field_values method with the previous field value if it's not needed", function(done) {
- ResourceManager.create(new Sealious.Context(), "has_required_field", {required: 1})
- .then(function(created_resource){
- return ResourceManager.patch_resource(new Sealious.Context(), "has_required_field", created_resource.id, {})
- }).then(function(){
- done();
- }).catch(function(error){
- done(error)
- })
- });
- });
-
- describe(".update_resource", function() {
- it('should update the resource', function(done) {
- ResourceManager.create(context, "never_fails_resource", {
- "#success": "tak"
- })
- .then(function(result) {
- ResourceManager.update_resource(context, "never_fails_resource", result.id, {
- "#success": "tak2"
- })
- .then(function(updated_resource) {
- return ResourceManager.get_by_id(context, updated_resource.id);
- })
- .then(function(gotten_resource) {
- if (gotten_resource.body["#success"] == "tak2" && deepEqual(context.toObject(), gotten_resource.created_context)) {
- done();
- } else {
- done(new Error("Updated resource differs from what was intended to update."))
- }
- })
- .catch(function(error) {
- done(new Error(error));
- })
- }).catch(function(error) {
- done(error);
- });
- });
- it("should throw proper error, if given resouce-type name is non-existent", function(done) {
- ResourceManager.update_resource(new Sealious.Context(), "non_existent_resource_type", "id", {})
- .then(function() {
- done(new Error("But it succedded instead of failing"));
- }).catch(function(error) {
- if (error.type === "validation") {
- done();
- } else {
- done(new Error("But threw an error that is not an instance of ValidationError"));
- }
- })
- })
- /*
- it("should remove a value if it's not provided", function(done) {
- ResourceManager.create(new Sealious.Context(), "multifield", {
- value1: "1",
- value2: "2"
- }).then(function(created_resource) {
- return ResourceManager.update_resource(new Sealious.Context(), "multifield", created_resource.id, {
- value1: "3"
- })
- }).then(function(updated_resource) {
- if (updated_resource.body.value2 === null) {
- done();
- } else {
- done(new Error("But it didn't"));
- }
- })
- });
-*/
- it("should not result in calling 'is_proper_value' for fields with no value (issue #235)", function(done){
- ResourceManager.create(new Sealious.Context(), "one_field_always_fails", {})
- .then(function(created_resource){
- return ResourceManager.update_resource(new Sealious.Context(), "one_field_always_fails", created_resource.id, {})
- }).then(function(){
- //if the field's 'is_proper_value' method wasn't called, it shouldn't throw an error
- done();
- }).catch(function(error){
- done(error);
- })
- })
- });
-
-
-
- })
-
- //should test if ResourceManager properly asks AccessStrategy.
-
- }
-}
\ No newline at end of file
diff --git a/tests/unit-tests/resource-type-collection-subject.test.js b/tests/unit-tests/resource-type-collection-subject.test.js
new file mode 100644
index 00000000..c2cc502c
--- /dev/null
+++ b/tests/unit-tests/resource-type-collection-subject.test.js
@@ -0,0 +1,458 @@
+"use strict";
+
+var UUIDGenerator = require("shortid");
+var equal = require("deep-equal");
+var Promise = require("bluebird");
+
+var assert_no_error = require("../util/assert-no-error.js");
+var assert_error_type = require("../util/assert-error-type.js");
+
+var ResourceTypeCollectionSubject = require("../../lib/subject/subject-types/resource-type-collection-subject.js");
+var SingleResource = require("../../lib/subject/subject-types/single-resource-subject.js");
+
+module.exports = {
+ test_start: function(){
+ describe("Subject type: resource-type-collection", function(){
+
+ describe(".create_resource", function(){
+ describe("should check access privilages, so it", function(){
+ var rt_user1_only = new Sealious.ResourceType({
+ name: "impossible_to_manipulate",
+ fields: [],
+ access_strategy: new Sealious.AccessStrategyType({
+ checker_function: function(context){
+ if (context.user_id == 1){
+ return Promise.resolve();
+ } else {
+ return Promise.reject("You are not user1!!");
+ }
+ }
+ })
+ });
+
+ var rt_user1_only_subject = new ResourceTypeCollectionSubject(rt_user1_only);
+ it("should not allow creating a resource when the access strategy forbids it", function(done){
+ var result = rt_user1_only_subject.perform_action(new Sealious.Context(0, null, 2), "create", {});
+ assert_error_type(result, "permission", done);
+ });
+
+ it("should allow creating a resource when the access strategy does not forbid it", function(done){
+ var rt_user1_only_subject = new ResourceTypeCollectionSubject(rt_user1_only);
+
+ var result = rt_user1_only_subject.perform_action(new Sealious.Context(0, null, 1), "create", {});
+ assert_no_error(result, done);
+ });
+
+ });
+
+ describe("should check if provided values are valid, so it", function(){
+ var rt_with_picky_field = new Sealious.ResourceType({
+ fields: [{
+ name: "value",
+ type: new Sealious.FieldType({
+ is_proper_value: function(accept, reject, context, params, value){
+ if (value === "correct"){
+ accept();
+ } else {
+ reject("The value isn't correct");
+ }
+ }
+ })
+ }]
+ });
+
+ var rt_with_picky_field_subject = new ResourceTypeCollectionSubject(rt_with_picky_field);
+
+ it("should throw an error if they aren't", function(done){
+ var result = rt_with_picky_field_subject.perform_action(new Sealious.Context(), "create", {value: "incorrect"});
+ assert_error_type(result, "validation", done);
+ });
+
+ it("should not throw an error if they are", function(done){
+ var result = rt_with_picky_field_subject.perform_action(new Sealious.Context(), "create", {value: "correct"});
+ assert_no_error(result, done);
+ });
+
+ });
+
+ it("should store the resource body", function(done){
+ var simple_rt_subject = new ResourceTypeCollectionSubject(new Sealious.ResourceType({
+ fields: [
+ {name: "value1", type: "text"},
+ {name: "value2", type: "int"}
+ ]
+ }));
+
+ var text = "text";
+ var int = 3;
+
+ simple_rt_subject.perform_action(new Sealious.Context(), "create", {value1: text, value2: int})
+ .then(function(created_resource){
+ if (created_resource.body.value1 == text && created_resource.body.value2 == int){
+ done();
+ } else {
+ done(new Error("The saved values don't match"));
+ }
+ });
+ });
+
+ it("should encode fields before sending them to datastore", function(done){
+ var rt_with_fancy_field = new Sealious.ResourceType({
+ fields: [{
+ name: "value",
+ type: new Sealious.FieldType({
+ encode: function(context, params, value_in_code){
+ return value_in_code + "_encoded";
+ }
+ })
+ }]
+ });
+
+ rt_with_fancy_field_subject = new ResourceTypeCollectionSubject(rt_with_fancy_field);
+
+ rt_with_fancy_field_subject.perform_action(new Sealious.Context(), "create", {value: "i_am"})
+ .then(function(resource_representation){
+ if (resource_representation.body.value === "i_am_encoded"){
+ done();
+ } else {
+ done(new Error("But apparently it did not."));
+ }
+ });
+ });
+
+ it("should create metadata for every newly created resource", function(done){
+
+ var context = new Sealious.Context();
+ var resource_type_name = "should create metadata for every newly created resource";
+
+ var simple_rt_subject = new ResourceTypeCollectionSubject(new Sealious.ResourceType({name: resource_type_name}))
+ .perform_action(context, "create", {})
+ .then(function(created_resource){
+ if (created_resource.id === undefined || created_resource.id === null){
+ done(new Error("It didn't create the 'sealious_id' attribute"));
+ } else if (created_resource.type_name !== resource_type_name){
+ done(new Error("It didn't properly set the 'type' attribute in db document"));
+ } else if (created_resource.created_context.timestamp !== context.timestamp){
+ done(new Error("It didn't properly set the 'created_context' attribute"));
+ } else if (created_resource.last_modified_context.timestamp !== created_resource.created_context.timestamp){
+ done(new Error("It didn't set the last_modified_context to the same value as created_context."));
+ } else {
+ done();
+ }
+ });
+ });
+
+
+ });
+
+ describe("._preprocess_resource_filter", function(){
+
+ it("should turn all filter values into {$eq: ...} query statements", function(done){
+
+ var rt = new Sealious.ResourceType({
+ fields: [
+ {name: "a", "type": "text"},
+ {name: "b", "type": "text"},
+ {name: "c", "type": "text"}
+ ]
+ });
+
+ var filter = {
+ "a": "d",
+ "b": "e",
+ "c": "f"
+ };
+
+ var expected_result = {
+ "a": {$eq: "d"},
+ "b": {$eq: "e"},
+ "c": {$eq: "f"}
+ };
+
+ var subject = new ResourceTypeCollectionSubject(rt);
+ subject._preprocess_resource_filter(new Sealious.Context(), filter)
+ .then(function(result){
+ if (equal(result, expected_result, {strict: true})){
+ done();
+ } else {
+ done(new Error("But it returned something else!"));
+ }
+ });
+ });
+
+ it("should skip values that do not correspond to the field names of the resource type and properly encode the others", function(done){
+ var rt = new Sealious.ResourceType({
+ fields: [
+ {name: "value", type: new Sealious.FieldType({
+ encode: function(context, params, value){
+ return value + "_encoded";
+ }
+ })}
+ ]
+ });
+
+ var filter = {
+ "value": "foo",
+ "non_existing": "bar"
+ };
+
+ var expected_result = {
+ "value": {$eq: "foo_encoded"}
+ };
+
+ var subject = new ResourceTypeCollectionSubject(rt);
+ subject._preprocess_resource_filter(new Sealious.Context(), filter)
+ .then(function(result){
+ if (equal(result, expected_result, {strict: true})){
+ done();
+ } else {
+ done(new Error("But it returned something else!"));
+ }
+ });
+ });
+
+ });
+
+ describe(".list_resources", function(){
+ it("should throw a proper error when trying to list instances of resource type with a shallow access_strategy that disallows the context", function(done){
+ var rt = new Sealious.ResourceType({
+ fields: [{name: "value", type: "text"}],
+ access_strategy: new Sealious.AccessStrategyType({
+ checker_function: function(context){
+ if (context.user_id == 1){
+ return Promise.reject("User 1 cannot access this resource");
+ }
+ }
+ })
+ });
+
+ var subject = new ResourceTypeCollectionSubject(rt);
+
+ var context = new Sealious.Context(0, null, 1);
+
+ var result = subject.perform_action(context, "show");
+ assert_error_type(result, "permission", done);
+ });
+
+ it("should only show resources that are allowed by the resource-type's deep item-sensitive access strategy", function(done){
+
+ var resource_type_name = UUIDGenerator(10);
+
+ var rt = new Sealious.ResourceType({
+ name: resource_type_name,
+ fields: [{name: "who_can_access", type: "text"}],
+ access_strategy: {
+ create: "public",
+ default: new Sealious.AccessStrategyType({
+ name: "hydra",
+ item_sensitive: true,
+ checker_function: function(context, params, item){
+ if (item.body.who_can_access.toString() === context.user_id.toString()){
+ return Promise.resolve();
+ } else {
+ return Promise.reject(`Only user #${item.body.who_can_access} can access this item.`);
+ }
+ }
+ })
+ }
+ });
+
+
+ var subject = new ResourceTypeCollectionSubject(rt);
+
+ var accessible_amount = 4;
+ var total_amount = 10;
+ var promises = [];
+ var p;
+
+ for (var i = 1; i <= accessible_amount; i++){
+ p = subject.perform_action(new Sealious.Context(), "create", {who_can_access: "1"});
+ promises.push(p);
+ }
+
+ for (var i = accessible_amount + 1; i <= total_amount; i++){
+ p = subject.perform_action(new Sealious.Context(), "create", {who_can_access: i});
+ promises.push(p);
+ }
+
+ var context = new Sealious.Context(0, null, 1);
+
+ Promise.all(promises).then(function(){
+ subject.perform_action(context, "show")
+ .then(function(accessible_resources){
+ if (accessible_resources.length === accessible_amount){
+ done();
+ } else {
+ done(new Error("It returned too many/didn't return enough resources"));
+ }
+ }).catch(done);
+ }).catch(done);
+ });
+
+ it("should only return resources of a given resource-type", function(done){
+ var resource_type_name1 = UUIDGenerator(10);
+
+ var rt1 = new Sealious.ResourceType({
+ name: resource_type_name1,
+ fields: [{name: "value", type: "text"}]
+ });
+
+ var subject1 = new ResourceTypeCollectionSubject(rt1);
+
+ var resource_type_name2 = UUIDGenerator(10);
+
+ var rt2 = new Sealious.ResourceType({
+ name: resource_type_name2,
+ fields: [{name: "value", type: "text"}]
+ });
+
+ var subject2 = new ResourceTypeCollectionSubject(rt2);
+
+ var accessible_amount = 4;
+ var total_amount = 10;
+ var promises = [];
+ var p;
+
+ for (var i = 1; i <= accessible_amount; i++){
+ p = subject1.perform_action(new Sealious.Context(), "create", {value: i});
+ promises.push(p);
+ }
+
+ for (var i = accessible_amount + 1; i <= total_amount; i++){
+ p = subject2.perform_action(new Sealious.Context(), "create", {value: i});
+ promises.push(p);
+ }
+
+ Promise.all(promises)
+ .then(function(){
+ subject1.perform_action(new Sealious.Context(), "show")
+ .then(function(visible_resources){
+ if (visible_resources.length === accessible_amount){
+ done();
+ } else {
+ done(new Error("Mismatch between expected visible resource amount and the actual amount"));
+ }
+ });
+ }).catch(done);
+
+ });
+
+ it("should throw an error when non-permission error is caught during filtering", function(done){
+ var rt = new Sealious.ResourceType({
+ name: UUIDGenerator(10),
+ access_strategy: {
+ default: "public",
+ retrieve: new Sealious.AccessStrategyType({
+ item_sensitive: true,
+ checker_function: function(){
+ throw new Error("Heil hydra");
+ }
+ })
+ }
+ });
+
+ var subject = new ResourceTypeCollectionSubject(rt);
+
+ subject.perform_action(new Sealious.Context(), "create", {})
+ .then(function(){
+ subject.perform_action(new Sealious.Context(), "show")
+ .then(function(){
+ done(new Error("It didn't throw any error, though..."));
+ }).catch(function(err){
+ if (err.type !== "validation"){
+ done();
+ } else {
+ done(new Error("But id did in fact return a validation error"));
+ }
+ });
+ });
+
+ });
+
+ it("should filter the results according to the 'filter' parameter", function(done){
+ var rt = new Sealious.ResourceType({
+ name: UUIDGenerator(10),
+ fields: [{name: "value", type: "text"}]
+ });
+
+ var accessible_amount = Math.ceil(Math.random() * 5);
+ var total_amount = accessible_amount + Math.ceil(Math.random() * 5);
+
+ var promises = [];
+ var p;
+
+ var subject = new ResourceTypeCollectionSubject(rt);
+
+ for (var i = 1; i <= accessible_amount; i++){
+ p = subject.perform_action(new Sealious.Context(), "create", {value: "1"});
+ promises.push(p);
+ }
+
+ for (var i = accessible_amount + 1; i <= total_amount; i++){
+ p = subject.perform_action(new Sealious.Context(), "create", {value: "2"});
+ promises.push(p);
+ }
+
+ Promise.all(promises)
+ .then(function(){
+ return subject.perform_action(new Sealious.Context(), "show", {filter: {value: "1"}});
+ }).then(function(filtered_resources){
+ if (filtered_resources.length === accessible_amount){
+ done();
+ } else {
+ done(new Error("But it seems it did not."));
+ }
+ });
+
+
+ });
+ });
+
+ describe(".perform_action", function(){
+ it("should throw an error when asked for non-existing action", function(done){
+ var rt = new Sealious.ResourceType({
+ name: UUIDGenerator(10)
+ });
+
+ var subject = new ResourceTypeCollectionSubject(rt);
+
+ try {
+ subject.perform_action(new Sealious.Context(), "i_dont_exist");
+ done(new Error("But it didn't throw any error at all"));
+ } catch (err){
+ if (err.type === "dev_error"){
+ done();
+ } else {
+ done(new Error("But it threw a different type of error"));
+ }
+ }
+ });
+ });
+
+ describe(".get_child_subject", function(){
+ it("should return a SingleResource subject tied to a specific resource type and id", function(done){
+ var rt = new Sealious.ResourceType({});
+
+ var subject = new ResourceTypeCollectionSubject(rt);
+
+ var resource_id = "resource_id";
+
+ subject.get_child_subject(resource_id)
+ .then(function(child_subject){
+ if (!(child_subject instanceof SingleResource)){
+ done(new Error("the child context was of wrong type"));
+ } else if (child_subject.resource_type !== rt){
+ done(new Error("the child context was tied to a different resource type"));
+ } else if (child_subject.resource_id !== resource_id){
+ done(new Error("the child context was tied to a different resource_id"));
+ } else {
+ done();
+ }
+ });
+
+ });
+ });
+ });
+
+ }
+};
diff --git a/tests/unit-tests/response.test.js b/tests/unit-tests/response.test.js
deleted file mode 100644
index 14110020..00000000
--- a/tests/unit-tests/response.test.js
+++ /dev/null
@@ -1,25 +0,0 @@
-var Sealious = require("sealious");
-
-module.exports = {
- test_init: function() {
- Sealious.Response({"field": "value"}, true, "type", "message")
- },
- test_start: function() {
- describe("Sealious.Response", function() {
- it("returns a Sealious.Response object", function(done) {
- var error = new Sealious.Errors.BadContext("This is an error", "test_data");
- var response = Sealious.Response.fromError(error);
- if (response.data === "test_data")
- if (response.type === "permission")
- if (response.status_message === "This is an error")
- done();
- else
- done("Wrong status_message")
- else
- done("Wrong type")
- else
- done("Wrong data")
- })
- })
- }
-};
\ No newline at end of file
diff --git a/tests/unit-tests/response/error.test.js b/tests/unit-tests/response/error.test.js
new file mode 100644
index 00000000..f58795e1
--- /dev/null
+++ b/tests/unit-tests/response/error.test.js
@@ -0,0 +1,91 @@
+"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, {});
+ });
+ 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;
+ }
+ }
+ 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;
+ }
+ }
+ 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;
+ }
+ }
+ 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;
+ }
+ }
+ 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;
+ }
+ }
+ 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;
+ }
+ }
+ 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
new file mode 100644
index 00000000..9c9def9d
--- /dev/null
+++ b/tests/unit-tests/response/response.test.js
@@ -0,0 +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");
+ });
+});
diff --git a/tests/unit-tests/response/responses.test.js b/tests/unit-tests/response/responses.test.js
new file mode 100644
index 00000000..59537301
--- /dev/null
+++ b/tests/unit-tests/response/responses.test.js
@@ -0,0 +1,13 @@
+"use strict";
+const locreq = require("locreq")(__dirname);
+const Responses = locreq("lib/response/responses.js");
+const assert = require("assert");
+
+describe("Sealious.Responses", function() {
+ it("returns a new Responses.NewSession object", function() {
+ const newSession = new Responses.NewSession("my_id");
+ assert.strictEqual(newSession.status, "success");
+ assert.strictEqual(newSession.message, "Logged in!");
+ assert.deepEqual(newSession.data, {});
+ });
+});
diff --git a/tests/unit-tests/single-resource-subject.test.js b/tests/unit-tests/single-resource-subject.test.js
new file mode 100644
index 00000000..7bcebbee
--- /dev/null
+++ b/tests/unit-tests/single-resource-subject.test.js
@@ -0,0 +1,126 @@
+"use strict";
+var Promise = require("bluebird");
+var UUIDGenerator = require("shortid");
+
+var assert_error_type = require("../util/assert-error-type.js");
+var assert_no_error = require("../util/assert-no-error.js");
+
+var SingleResourceSubject = require("../../lib/subject/subject-types/single-resource-subject.js");
+
+module.exports = {
+ test_start: function(){
+ describe("Subject type: single-resource", function(){
+ describe(".get_resource", function(){
+ var rt_name = UUIDGenerator(10);
+
+ var field_value = UUIDGenerator(10);
+
+ var rt = new Sealious.ResourceType({
+ name: rt_name,
+ fields: [{name: "value", type: "text"}]
+ });
+
+
+ it("should find an existing resource", function(done){
+ var create_action = new Sealious.Action(["resources", rt_name], "create");
+ create_action.run(new Sealious.Context(), {value: field_value})
+ .then(function(created_resource){
+ var subject = new SingleResourceSubject(rt, created_resource.id);
+ return subject.perform_action(new Sealious.Context(), "show")
+ .then(function(retrieved_resource){
+ if (retrieved_resource.id == created_resource.id && retrieved_resource.body.value == field_value){
+ done();
+ } else {
+ done(new Error("Retrieved id or field value were incorrect"));
+ }
+ });
+ });
+ });
+
+ it("should throw a 'not_found' error if the provided resource id does not exist", function(done){
+ var subject = new SingleResourceSubject(rt, "made-up-id");
+ var promise = subject.perform_action(new Sealious.Context(), "show");
+ assert_error_type(promise, "not_found", done);
+ });
+
+ it("should throw an error when asked to show a resource when access strategy rejects the context", function(done){
+ var rt = new Sealious.ResourceType({
+ name: UUIDGenerator(10),
+ fields: [{name: "value", type: "text"}],
+ access_strategy: new Sealious.AccessStrategyType({
+ checker_function: function(context){
+ if (context.user_id === 1){
+ return Promise.resolve();
+ } else {
+ return Promise.reject("Only user #1 can perform any operations on this resource");
+ }
+ }
+ })
+ });
+
+ var create_action = new Sealious.Action(["resources", rt.name], "create");
+ create_action.run(new Sealious.Context(0, null, 1), {value: UUIDGenerator(10)})
+ .then(function(created_resource){
+ var subject = new SingleResourceSubject(rt, created_resource.id);
+ var promise = subject.perform_action(new Sealious.Context(0, null, 2), "show");
+ assert_error_type(promise, "permission", done);
+ });
+ });
+
+ it("should throw an error when an item-sensitive access strategy rejects the 'show' method", function(done){
+ var rt = new Sealious.ResourceType({
+ name: UUIDGenerator(10),
+ fields: [{name: "value", type: "text"}],
+ access_strategy: {
+ create: "public",
+ retrieve: new Sealious.AccessStrategyType({
+ checker_function: function(context, params, item){
+ if (item.body.value === "allow"){
+ return Promise.resolve();
+ } else {
+ return Promise.reject("You cannot see this item.");
+ }
+ }
+ })
+ }
+ });
+
+ var create_action = new Sealious.Action(["resources", rt.name], "create");
+ create_action.run(new Sealious.Context(), {value: "disallow"})
+ .then(function(created_resource){
+ var subject = new SingleResourceSubject(rt, created_resource.id);
+ var promise = subject.perform_action(new Sealious.Context(), "show");
+ assert_error_type(promise, "permission", done);
+ });
+ });
+
+ it("should not throw an error when an item-sensitive access strategy allows the 'show' method", function(done){
+ var rt = new Sealious.ResourceType({
+ name: UUIDGenerator(10),
+ fields: [{name: "value", type: "text"}],
+ access_strategy: {
+ create: "public",
+ show: new Sealious.AccessStrategyType({
+ checker_function: function(context, params, item){
+ if (item.body.value === "allow"){
+ return Promise.resolve();
+ } else {
+ return Promise.reject("You cannot see this item.");
+ }
+ }
+ })
+ }
+ });
+
+ var create_action = new Sealious.Action(["resources", rt.name], "create");
+ create_action.run(new Sealious.Context(), {value: "allow"})
+ .then(function(created_resource){
+ var subject = new SingleResourceSubject(rt, created_resource.id);
+ var result = subject.perform_action(new Sealious.Context(), "show");
+ assert_no_error(result, done);
+ });
+ });
+ });
+ });
+ }
+};
diff --git a/tests/unit-tests/subject/prefedined-subjects/me-subject.test.js b/tests/unit-tests/subject/prefedined-subjects/me-subject.test.js
new file mode 100644
index 00000000..62c257c5
--- /dev/null
+++ b/tests/unit-tests/subject/prefedined-subjects/me-subject.test.js
@@ -0,0 +1,10 @@
+"use strict";
+// const locreq = require("locreq")(__dirname);
+// const MeSubject = locreq("lib/subject/predefined-subjects/me-subject.js");
+// const assert = require("assert");
+//
+// describe("Sealious.MeSubject", function() {
+// it("checks the MeSubject prototype", function() {
+// console.log(MeSubject);
+// });
+// });
diff --git a/tests/unit-tests/subject/subject-types/resource-type-collection-subject.test.js b/tests/unit-tests/subject/subject-types/resource-type-collection-subject.test.js
new file mode 100644
index 00000000..ec510446
--- /dev/null
+++ b/tests/unit-tests/subject/subject-types/resource-type-collection-subject.test.js
@@ -0,0 +1,455 @@
+"use strict";
+// const locreq = require("locreq")(__dirname);
+// const UUIDGenerator = require("shortid");
+// const equal = require("deep-equal");
+// const Promise = require("bluebird");
+//
+// const assert_no_error = locreq("tests/util/assert-no-error.js");
+// const assert_error_type = locreq("tests/util/assert-error-type.js");
+//
+// const Context = locreq("lib/context.js");
+// const FieldType = locreq("lib/chip-types/field-type.js");
+// const ResourceType = locreq("lib/chip-types/resource-type.js");
+// const AccessStrategyType = locreq("lib/chip-types/access-strategy-type.js");
+// const ResourceTypeCollectionSubject = locreq("lib/subject/subject-types/resource-type-collection-subject.js");
+// const SingleResource = locreq("lib/subject/subject-types/single-resource-subject.js");
+//
+// describe("Subject type: resource-type-collection", function(){
+// describe(".create_resource", function(){
+// describe("should check access privilages, so it", function(){
+// var rt_user1_only = new ResourceType({
+// name: "impossible_to_manipulate",
+// fields: [],
+// access_strategy: new AccessStrategyType({
+// checker_function: function(context){
+// if (context.user_id == 1){
+// return Promise.resolve();
+// } else {
+// return Promise.reject("You are not user1!!");
+// }
+// }
+// })
+// });
+//
+// var rt_user1_only_subject = new ResourceTypeCollectionSubject(rt_user1_only);
+// it("should not allow creating a resource when the access strategy forbids it", function(done){
+// var result = rt_user1_only_subject.perform_action(new Context(0, null, 2), "create", {});
+// assert_error_type(result, "permission", done);
+// })
+//
+// it("should allow creating a resource when the access strategy does not forbid it", function(done){
+// var rt_user1_only_subject = new ResourceTypeCollectionSubject(rt_user1_only);
+//
+// var result = rt_user1_only_subject.perform_action(new Context(0, null, 1), "create", {});
+// assert_no_error(result, done);
+// })
+//
+// })
+//
+// describe("should check if provided values are valid, so it", function(){
+// var rt_with_picky_field = new ResourceType({
+// fields: [{
+// name: 'value',
+// type: new FieldType({
+// is_proper_value: function(accept, reject, context, params, value){
+// if (value === "correct"){
+// accept();
+// } else {
+// reject("The value isn't correct");
+// }
+// }
+// })
+// }]
+// })
+//
+// var rt_with_picky_field_subject = new ResourceTypeCollectionSubject(rt_with_picky_field);
+//
+// it("should throw an error if they aren't", function(done){
+// var result = rt_with_picky_field_subject.perform_action(new Context(), "create", {value: "incorrect"});
+// assert_error_type(result, "validation", done);
+// })
+//
+// it("should not throw an error if they are", function(done){
+// var result = rt_with_picky_field_subject.perform_action(new Context(), "create", {value: "correct"});
+// assert_no_error(result, done)
+// })
+//
+// })
+//
+// it("should store the resource body", function(done){
+// var simple_rt_subject = new ResourceTypeCollectionSubject(new ResourceType({
+// fields: [
+// {name: "value1", type: "text"},
+// {name: "value2", type: "int"}
+// ]
+// }))
+//
+// var text = "text";
+// var int = 3;
+//
+// simple_rt_subject.perform_action(new Context(), "create", {value1: text, value2: int})
+// .then(function(created_resource){
+// if (created_resource.body.value1 == text && created_resource.body.value2 == int){
+// done();
+// } else {
+// done(new Error("The saved values don't match"));
+// }
+// })
+// })
+//
+// it("should encode fields before sending them to datastore", function(done){
+// var rt_with_fancy_field = new ResourceType({
+// fields: [{
+// name: "value",
+// type: new FieldType({
+// encode: function(context, params, value_in_code){
+// return value_in_code + "_encoded";
+// }
+// })
+// }]
+// })
+//
+// rt_with_fancy_field_subject = new ResourceTypeCollectionSubject(rt_with_fancy_field);
+//
+// rt_with_fancy_field_subject.perform_action(new Context(), "create", {value: "i_am"})
+// .then(function(resource_representation){
+// if (resource_representation.body.value === "i_am_encoded"){
+// done();
+// } else {
+// done(new Error("But apparently it did not."));
+// }
+// });
+// })
+//
+// it("should create metadata for every newly created resource", function(done){
+//
+// var context = new Context();
+// var resource_type_name = "should create metadata for every newly created resource";
+//
+// var simple_rt_subject = new ResourceTypeCollectionSubject(new ResourceType({name: resource_type_name}))
+// .perform_action(context, "create", {})
+// .then(function(created_resource){
+// if (created_resource.id === undefined || created_resource.id === null){
+// done(new Error("It didn't create the 'sealious_id' attribute"));
+// } else if (created_resource.type_name !== resource_type_name){
+// done(new Error("It didn't properly set the 'type' attribute in db document"));
+// } else if (created_resource.created_context.timestamp !== context.timestamp){
+// done(new Error("It didn't properly set the 'created_context' attribute"));
+// } else if (created_resource.last_modified_context.timestamp !== created_resource.created_context.timestamp){
+// done(new Error("It didn't set the last_modified_context to the same value as created_context."));
+// } else {
+// done();
+// }
+// })
+// })
+//
+//
+// })
+//
+// describe("._preprocess_resource_filter", function(){
+//
+// it("should turn all filter values into {$eq: ...} query statements", function(done){
+//
+// var rt = new ResourceType({
+// fields: [
+// {name: "a", "type": "text"},
+// {name: "b", "type": "text"},
+// {name: "c", "type": "text"}
+// ]
+// })
+//
+// var filter = {
+// "a": "d",
+// "b": "e",
+// "c": "f"
+// }
+//
+// var expected_result = {
+// "a": {$eq: "d"},
+// "b": {$eq: "e"},
+// "c": {$eq: "f"}
+// }
+//
+// var subject = new ResourceTypeCollectionSubject(rt);
+// subject._preprocess_resource_filter(new Context(), filter)
+// .then(function(result){
+// if (equal(result, expected_result, {strict: true})){
+// done();
+// } else {
+// done(new Error("But it returned something else!"));
+// }
+// })
+// });
+//
+// it("should skip values that do not correspond to the field names of the resource type and properly encode the others", function(done){
+// var rt = new ResourceType({
+// fields: [
+// {name: "value", type: new FieldType({
+// encode: function(context, params, value){
+// return value + "_encoded";
+// }
+// })}
+// ]
+// })
+//
+// var filter = {
+// "value": "foo",
+// "non_existing": "bar"
+// }
+//
+// var expected_result = {
+// "value": {$eq: "foo_encoded"}
+// }
+//
+// var subject = new ResourceTypeCollectionSubject(rt);
+// subject._preprocess_resource_filter(new Context(), filter)
+// .then(function(result){
+// if (equal(result, expected_result, {strict: true})){
+// done();
+// } else {
+// done(new Error("But it returned something else!"));
+// }
+// })
+// })
+//
+// })
+//
+// describe(".list_resources", function(){
+// it("should throw a proper error when trying to list instances of resource type with a shallow access_strategy that disallows the context", function(done){
+// var rt = new ResourceType({
+// fields: [{name: "value", type: "text"}],
+// access_strategy: new AccessStrategyType({
+// checker_function: function(context){
+// if (context.user_id == 1){
+// return Promise.reject("User 1 cannot access this resource");
+// }
+// }
+// })
+// })
+//
+// var subject = new ResourceTypeCollectionSubject(rt);
+//
+// var context = new Context(0, null, 1);
+//
+// var result = subject.perform_action(context, "show");
+// assert_error_type(result, "permission", done);
+// })
+//
+// it("should only show resources that are allowed by the resource-type's deep item-sensitive access strategy", function(done){
+//
+// var resource_type_name = UUIDGenerator(10);
+//
+// var rt = new ResourceType({
+// name: resource_type_name,
+// fields: [{name: "who_can_access", type: "text"}],
+// access_strategy: {
+// create: "public",
+// default: new AccessStrategyType({
+// name: "hydra",
+// item_sensitive: true,
+// checker_function: function(context, params, item){
+// if (item.body.who_can_access.toString() === context.user_id.toString()){
+// return Promise.resolve();
+// } else {
+// return Promise.reject(`Only user #${item.body.who_can_access} can access this item.`)
+// }
+// }
+// })
+// }
+// })
+//
+//
+// var subject = new ResourceTypeCollectionSubject(rt);
+//
+// var accessible_amount = 4;
+// var total_amount = 10;
+// var promises = [];
+// var p;
+//
+// for (var i = 1; i <= accessible_amount; i++){
+// p = subject.perform_action(new Context(), "create", {who_can_access: "1"});
+// promises.push(p);
+// }
+//
+// for (var i = accessible_amount + 1; i <= total_amount; i++){
+// p = subject.perform_action(new Context(), "create", {who_can_access: i});
+// promises.push(p);
+// }
+//
+// var context = new Context(0, null, 1);
+//
+// Promise.all(promises).then(function(){
+// subject.perform_action(context, "show")
+// .then(function(accessible_resources){
+// if (accessible_resources.length === accessible_amount){
+// done();
+// } else {
+// done(new Error("It returned too many/didn't return enough resources"));
+// }
+// }).catch(done);
+// }).catch(done);
+// })
+//
+// it("should only return resources of a given resource-type", function(done){
+// var resource_type_name1 = UUIDGenerator(10);
+//
+// var rt1 = new ResourceType({
+// name: resource_type_name1,
+// fields: [{name: "value", type: "text"}]
+// });
+//
+// var subject1 = new ResourceTypeCollectionSubject(rt1);
+//
+// var resource_type_name2 = UUIDGenerator(10);
+//
+// var rt2 = new ResourceType({
+// name: resource_type_name2,
+// fields: [{name: "value", type: "text"}]
+// });
+//
+// var subject2 = new ResourceTypeCollectionSubject(rt2);
+//
+// var accessible_amount = 4;
+// var total_amount = 10;
+// var promises = [];
+// var p;
+//
+// for (var i = 1; i <= accessible_amount; i++){
+// p = subject1.perform_action(new Context(), "create", {value: i});
+// promises.push(p);
+// }
+//
+// for (var i = accessible_amount + 1; i <= total_amount; i++){
+// p = subject2.perform_action(new Context(), "create", {value: i});
+// promises.push(p);
+// }
+//
+// Promise.all(promises)
+// .then(function(){
+// subject1.perform_action(new Context(), "show")
+// .then(function(visible_resources){
+// if (visible_resources.length === accessible_amount){
+// done();
+// } else {
+// done(new Error("Mismatch between expected visible resource amount and the actual amount"));
+// }
+// })
+// }).catch(done)
+//
+// })
+//
+// it("should throw an error when non-permission error is caught during filtering", function(done){
+// var rt = new ResourceType({
+// name: UUIDGenerator(10),
+// access_strategy: {
+// default: "public",
+// retrieve: new AccessStrategyType({
+// item_sensitive: true,
+// checker_function: function(){
+// throw new Error("Heil hydra");
+// }
+// })
+// }
+// })
+//
+// var subject = new ResourceTypeCollectionSubject(rt);
+//
+// subject.perform_action(new Context(), "create", {})
+// .then(function(){
+// subject.perform_action(new Context(), "show")
+// .then(function(){
+// done(new Error("It didn't throw any error, though..."));
+// }).catch(function(err){
+// if (err.type !== "validation"){
+// done();
+// } else {
+// done(new Error("But id did in fact return a validation error"));
+// }
+// })
+// })
+//
+// })
+//
+// it("should filter the results according to the 'filter' parameter", function(done){
+// var rt = new ResourceType({
+// name: UUIDGenerator(10),
+// fields: [{name: "value", type: "text"}]
+// })
+//
+// var accessible_amount = Math.ceil(Math.random() * 5);
+// var total_amount = accessible_amount + Math.ceil(Math.random() * 5);
+//
+// var promises = [];
+// var p;
+//
+// var subject = new ResourceTypeCollectionSubject(rt);
+//
+// for (var i = 1; i <= accessible_amount; i++){
+// p = subject.perform_action(new Context(), "create", {value: "1"});
+// promises.push(p);
+// }
+//
+// for (var i = accessible_amount + 1; i <= total_amount; i++){
+// p = subject.perform_action(new Context(), "create", {value: "2"});
+// promises.push(p);
+// }
+//
+// Promise.all(promises)
+// .then(function(){
+// return subject.perform_action(new Context(), "show", {filter: {value: "1"}})
+// }).then(function(filtered_resources){
+// if (filtered_resources.length === accessible_amount){
+// done();
+// } else {
+// done(new Error("But it seems it did not."));
+// }
+// })
+//
+//
+// })
+// })
+//
+// describe(".perform_action", function(){
+// it("should throw an error when asked for non-existing action", function(done){
+// var rt = new ResourceType({
+// name: UUIDGenerator(10)
+// });
+//
+// var subject = new ResourceTypeCollectionSubject(rt);
+//
+// try {
+// subject.perform_action(new Context(), "i_dont_exist");
+// done(new Error("But it didn't throw any error at all"));
+// } catch (err){
+// if (err.type === "dev_error"){
+// done();
+// } else {
+// done(new Error("But it threw a different type of error"));
+// }
+// }
+// })
+// })
+//
+// describe(".get_child_subject", function(){
+// it("should return a SingleResource subject tied to a specific resource type and id", function(done){
+// var rt = new ResourceType({});
+//
+// var subject = new ResourceTypeCollectionSubject(rt);
+//
+// var resource_id = "resource_id";
+//
+// subject.get_child_subject(resource_id)
+// .then(function(child_subject){
+// if (!(child_subject instanceof SingleResource)){
+// done(new Error("the child context was of wrong type"));
+// } else if (child_subject.resource_type !== rt){
+// done(new Error("the child context was tied to a different resource type"));
+// } else if (child_subject.resource_id !== resource_id){
+// done(new Error("the child context was tied to a different resource_id"));
+// } else {
+// done();
+// }
+// })
+// })
+// })
+// })
diff --git a/tests/unit-tests/subject/subject.test.js b/tests/unit-tests/subject/subject.test.js
new file mode 100644
index 00000000..8f1e3e76
--- /dev/null
+++ b/tests/unit-tests/subject/subject.test.js
@@ -0,0 +1,36 @@
+"use strict";
+const locreq = require("locreq")(__dirname)
+const Subject = locreq("lib/subject/subject.js");
+const assert = require("assert");
+
+describe("Sealious.Subject", function(){
+ describe(".get_subject", function(){
+ it("Properly traverses subject tree", function(done){
+
+ const me = new Subject();
+ me.get_child_subject = function(key){
+ return null;
+ }
+
+ const my_dad = new Subject();
+ my_dad.get_child_subject = function(key){
+ if (key == "son"){
+ return me;
+ }
+ }
+
+ const my_granddad = new Subject();
+ my_granddad.get_child_subject = function(key){
+ if (key == "son"){
+ return my_dad;
+ }
+ }
+
+ my_granddad.get_subject(["son", "son"])
+ .then(function(result){
+ assert.strictEqual(result, me);
+ done();
+ });
+ });
+ });
+});
diff --git a/tests/unit-tests/user-manager.test.js b/tests/unit-tests/user-manager.test.js
deleted file mode 100644
index d396f0cb..00000000
--- a/tests/unit-tests/user-manager.test.js
+++ /dev/null
@@ -1,115 +0,0 @@
-var Sealious = require('sealious');
-
-module.exports = {
- test_init: function() {
- },
- test_start: function() {
- describe("UserManager", function() {
- it("creates a new user", function(done) {
- Sealious.UserManager.create_user(new Sealious.Context(), "user", "pass")
- .then(function(result) {
- if (result.body.username === "user" && result.body.password === "pass") {
- done();
- }
- else {
- done(new Error("It created wrong user"))
- }
- })
- .catch(function(error) {
- done(new Error(error))
- })
- })
- it("tries to create a user that already exists", function(done) {
- var context = new Sealious.Context()
- Sealious.UserManager.create_user(context, "user_exists", "pass_exists")
- .then(function(result) {
- Sealious.UserManager.create_user(context, "user_exists", "pass_exists")
- .then(function(result){
- done(new Error("It created a user"));
- })
- .catch(function(error) {
- if (error.type === "valueExists"){
- done();
- }
- else {
- done(new Error(error));
- }
- })
- })
- .catch(function(error) {
- done(new Error(error))
- });
- });
- it("gets all users", function(done) {
- Sealious.UserManager.get_all_users(new Sealious.Context)
- .then(function(result) {
- if (typeof result === "object"){
- if (result.length >= 2) {
- done();
- }
- else {
- done(new Error("It didn't return enough elements"));
- }
- }
- else {
- done(new Error("It didn't return an array with users"));
- }
- })
- .catch(function(error) {
- done(new Error(error));
- })
- })
- it("matched given credentials", function(done) {
- Sealious.UserManager.password_match(new Sealious.Context(), "user_exists", "pass_exists")
- .then(function(result) {
- done();
- })
- .catch(function(error) {
- done(new Error(error));
- })
- });
- it("didn't match given credentials", function(done) {
- Sealious.UserManager.password_match(new Sealious.Context(), "blablagarbage", "blablagarbage")
- .then(function(result) {
- done("It found the user");
- })
- .catch(function(error) {
- if (error.type === "authorization") {
- done();
- }
- else {
- done(new Error(error));
- }
- })
- })
- it("misses username and password", function(done) {
- Sealious.UserManager.password_match(new Sealious.Context)
- .then(function(result) {
- done("It worked");
- })
- .catch(function(error) {
- if(error.type === "authorization"){
- done();
- }
- else {
- done(new Error(error));
- }
- })
- })
- it("misses username and password", function(done) {
- Sealious.UserManager.password_match(new Sealious.Context, "username")
- .then(function(result) {
- done("It worked");
- })
- .catch(function(error) {
- if(error.type === "authorization"){
- done();
- }
- else {
- done(new Error(error));
- }
- })
- })
- });
- }
-};
\ No newline at end of file
diff --git a/tests/unit-tests/utils/check-version.test.js b/tests/unit-tests/utils/check-version.test.js
new file mode 100644
index 00000000..1f970cb2
--- /dev/null
+++ b/tests/unit-tests/utils/check-version.test.js
@@ -0,0 +1,62 @@
+"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/accept-correctly.js b/tests/util/accept-correctly.js
new file mode 100644
index 00000000..b5ca0f67
--- /dev/null
+++ b/tests/util/accept-correctly.js
@@ -0,0 +1,9 @@
+"use strict";
+function acceptCorrectly(done) {
+ return {
+ accept: done,
+ reject: (msg) => done(new Error(msg))
+ };
+}
+
+module.exports = acceptCorrectly;
diff --git a/tests/util/assert-error-type.js b/tests/util/assert-error-type.js
new file mode 100644
index 00000000..aa987020
--- /dev/null
+++ b/tests/util/assert-error-type.js
@@ -0,0 +1,15 @@
+"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){
+ 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/assert-error.js b/tests/util/assert-error.js
new file mode 100644
index 00000000..675027c4
--- /dev/null
+++ b/tests/util/assert-error.js
@@ -0,0 +1,10 @@
+"use strict";
+function assert_no_error (promise, done) {
+ promise.then(function(){
+ done(new Error("It didn't reject!"));
+ }).catch(function(error){
+ done();
+ });
+}
+
+module.exports = assert_no_error;
diff --git a/tests/util/assert-no-error.js b/tests/util/assert-no-error.js
new file mode 100644
index 00000000..cbf19110
--- /dev/null
+++ b/tests/util/assert-no-error.js
@@ -0,0 +1,11 @@
+"use strict";
+function assert_no_error (promise, done) {
+ promise.then(function(){
+ done();
+ }).catch(function(error){
+ console.error(error.data);
+ done(error);
+ });
+}
+
+module.exports = assert_no_error;
diff --git a/tests/util/reject-correctly.js b/tests/util/reject-correctly.js
new file mode 100644
index 00000000..a3627a5e
--- /dev/null
+++ b/tests/util/reject-correctly.js
@@ -0,0 +1,9 @@
+"use strict";
+function rejectCorrectly(done) {
+ return {
+ accept: () => done(new Error("It accepted!")),
+ reject: (msg) => done()
+ };
+}
+
+module.exports = rejectCorrectly;

File Metadata

Mime Type
text/x-diff
Expires
Sat, Nov 28, 03:15 (28 m, 25 s)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
1225976
Default Alt Text
(432 KB)

Event Timeline