1
0
Fork 0

Merge branch 'devel' of https://github.com/triAGENS/ArangoDB into devel

This commit is contained in:
scottashton 2014-11-20 09:54:00 +01:00
commit fef641be02
32 changed files with 1847 additions and 5 deletions

View File

@ -209,7 +209,7 @@ var helpArangoCollection = arangosh.createHelpHeadline("ArangoCollection help")
' truncate() delete all documents ' + "\n" +
' properties() show collection properties ' + "\n" +
' drop() delete a collection ' + "\n" +
' load() load a collection into memeory ' + "\n" +
' load() load a collection into memory ' + "\n" +
' unload() unload a collection from memory ' + "\n" +
' rename(<new-name>) renames a collection ' + "\n" +
' getIndexes() return defined indexes ' + "\n" +

View File

@ -1033,9 +1033,12 @@ AQLGenerator.prototype._getLastRestrictableStatementInfo = function() {
////////////////////////////////////////////////////////////////////////////////
AQLGenerator.prototype.restrict = function(restrictions) {
var rest = stringToArray(restrictions);
if (rest.length == 0) {
return this;
}
this._addToPrint("restrict", restrictions);
this._clearCursor();
var rest = stringToArray(restrictions);
var lastQueryInfo = this._getLastRestrictableStatementInfo();
var lastQuery = lastQueryInfo.statement;
var opts = lastQueryInfo.options;
@ -1186,6 +1189,7 @@ AQLGenerator.prototype.execute = function() {
AQLGenerator.prototype.toArray = function() {
this._createCursor();
return this.cursor.toArray();
};
@ -4487,6 +4491,83 @@ Graph.prototype._removeVertexCollection = function(vertexCollectionName, dropCol
};
////////////////////////////////////////////////////////////////////////////////
/// @startDocuBlock JSF_general_graph_connectingEdges
/// @brief Get all connecting edges between 2 groups of vertices defined by the examples
///
/// `graph._connectingEdges(vertexExample, vertexExample2, options)`
///
/// The function accepts an id, an example, a list of examples or even an empty
/// example as parameter for vertexExample.
///
/// @PARAMS
///
/// @PARAM{vertexExample1, object, optional}
/// See [Definition of examples](#definition_of_examples)
/// @PARAM{vertexExample2, object, optional}
/// See [Definition of examples](#definition_of_examples)
/// @PARAM{options, object, optional}
/// An object defining further options. Can have the following values:
/// * *edgeExamples*: Filter the edges, see [Definition of examples](#definition_of_examples)
/// * *edgeCollectionRestriction* : One or a list of edge-collection names that should be
/// considered to be on the path.
/// * *vertex1CollectionRestriction* : One or a list of vertex-collection names that should be
/// considered on the intermediate vertex steps.
/// * *vertex2CollectionRestriction* : One or a list of vertex-collection names that should be
/// considered on the intermediate vertex steps.
///
/// @EXAMPLES
///
/// A route planner example, all neighbors of capitals.
///
/// @EXAMPLE_ARANGOSH_OUTPUT{generalGraphModuleNeighbors1}
/// var examples = require("org/arangodb/graph-examples/example-graph.js");
/// var graph = examples.loadGraph("routeplanner");
/// graph._neighbors({isCapital : true});
/// @END_EXAMPLE_ARANGOSH_OUTPUT
///
/// A route planner example, all outbound neighbors of Hamburg.
///
/// @EXAMPLE_ARANGOSH_OUTPUT{generalGraphModuleNeighbors2}
/// var examples = require("org/arangodb/graph-examples/example-graph.js");
/// var graph = examples.loadGraph("routeplanner");
/// graph._neighbors('germanCity/Hamburg', {direction : 'outbound', maxDepth : 2});
/// @END_EXAMPLE_ARANGOSH_OUTPUT
///
/// @endDocuBlock
//
////////////////////////////////////////////////////////////////////////////////
Graph.prototype._getConnectingEdges = function(vertexExample1, vertexExample2, options) {
var AQLStmt = new AQLGenerator(this);
if (!options) {
options = {};
}
var opts = {
};
options.vertex1CollectionRestriction ? opts.startVertexCollectionRestriction = options.vertex1CollectionRestriction : null ;
options.vertex2CollectionRestriction ? opts.endVertexCollectionRestriction = options.vertex2CollectionRestriction : null ;
options.edgeCollectionRestriction ? opts.edgeCollectionRestriction = options.edgeCollectionRestriction : null ;
options.edgeExamples ? opts.edgeExamples = options.edgeExamples : null ;
vertexExample2 ? opts.neighborExamples = vertexExample2 : null ;
var query = "RETURN"
+ " GRAPH_EDGES(@graphName"
+ ',@vertexExample'
+ ',@options'
+ ')';
options = options || {};
var bindVars = {
"graphName": this.__name,
"vertexExample": vertexExample1,
"options": opts
};
var result = db._query(query, bindVars).toArray();
return result[0];
};
////////////////////////////////////////////////////////////////////////////////

View File

@ -208,7 +208,7 @@ var helpArangoCollection = arangosh.createHelpHeadline("ArangoCollection help")
' truncate() delete all documents ' + "\n" +
' properties() show collection properties ' + "\n" +
' drop() delete a collection ' + "\n" +
' load() load a collection into memeory ' + "\n" +
' load() load a collection into memory ' + "\n" +
' unload() unload a collection from memory ' + "\n" +
' rename(<new-name>) renames a collection ' + "\n" +
' getIndexes() return defined indexes ' + "\n" +

84
js/node/node_modules/foxx_generator/.jshintrc generated vendored Normal file
View File

@ -0,0 +1,84 @@
{
"maxerr" : 50, // {int} Maximum error before stopping
// Enforcing
"bitwise" : true, // true: Prohibit bitwise operators (&, |, ^, etc.)
"camelcase" : true, // true: Identifiers must be in camelCase
"curly" : true, // true: Require {} for every new block or scope
"eqeqeq" : true, // true: Require triple equals (===) for comparison
"freeze" : true, // true: prohibits overwriting prototypes of native objects such as Array, Date etc.
"forin" : true, // true: Require filtering for..in loops with obj.hasOwnProperty()
"immed" : true, // true: Require immediate invocations to be wrapped in parens e.g. `(function () { } ());`
"indent" : 2, // {int} Number of spaces to use for indentation
"latedef" : true, // true: Require variables/functions to be defined before being used
"newcap" : true, // true: Require capitalization of all constructor functions e.g. `new F()`
"noarg" : true, // true: Prohibit use of `arguments.caller` and `arguments.callee`
"noempty" : true, // true: Prohibit use of empty blocks
"nonbsp" : true, // true: Prohibit "non-breaking whitespace" characters.
"nonew" : true, // true: Prohibit use of constructors for side-effects (without assignment)
"plusplus" : false, // true: Prohibit use of `++` & `--`
"quotmark" : "single", // Quotation mark consistency:
// false : do nothing (default)
// true : ensure whatever is used is consistent
// "single" : require single quotes
// "double" : require double quotes
"undef" : true, // true: Require all non-global variables to be declared (prevents global leaks)
"unused" : "vars", // "vars": Require all defined variables be used, but not parameters
"strict" : true, // true: Requires all functions run in ES5 Strict Mode
"maxparams" : false, // {int} Max number of formal params allowed per function
"maxdepth" : 2, // {int} Max depth of nested blocks (within functions)
"maxstatements" : false, // {int} Max number statements per function
"maxcomplexity" : 5, // {int} Max cyclomatic complexity per function
"maxlen" : 120, // {int} Max number of characters per line
// Relaxing
"asi" : false, // true: Tolerate Automatic Semicolon Insertion (no semicolons)
"boss" : false, // true: Tolerate assignments where comparisons would be expected
"debug" : false, // true: Allow debugger statements e.g. browser breakpoints.
"eqnull" : false, // true: Tolerate use of `== null`
"es5" : false, // true: Allow ES5 syntax (ex: getters and setters)
"esnext" : false, // true: Allow ES.next (ES6) syntax (ex: `const`)
"moz" : false, // true: Allow Mozilla specific syntax (extends and overrides esnext features)
// (ex: `for each`, multiple try/catch, function expression…)
"evil" : false, // true: Tolerate use of `eval` and `new Function()`
"expr" : false, // true: Tolerate `ExpressionStatement` as Programs
"funcscope" : false, // true: Tolerate defining variables inside control statements
"globalstrict" : false, // true: Allow global "use strict" (also enables 'strict')
"iterator" : false, // true: Tolerate using the `__iterator__` property
"lastsemic" : false, // true: Tolerate omitting a semicolon for the last statement of a 1-line block
"laxbreak" : false, // true: Tolerate possibly unsafe line breakings
"laxcomma" : false, // true: Tolerate comma-first style coding
"loopfunc" : false, // true: Tolerate functions being defined in loops
"multistr" : false, // true: Tolerate multi-line strings
"noyield" : false, // true: Tolerate generator functions with no yield statement in them.
"notypeof" : false, // true: Tolerate invalid typeof operator values
"proto" : false, // true: Tolerate using the `__proto__` property
"scripturl" : false, // true: Tolerate script-targeted URLs
"shadow" : false, // true: Allows re-define variables later in code e.g. `var x=1; x=2;`
"sub" : false, // true: Tolerate using `[]` notation when it can still be expressed in dot notation
"supernew" : false, // true: Tolerate `new function () { ... };` and `new Object;`
"validthis" : false, // true: Tolerate using this in a non-constructor function
// Environments
"browser" : false, // Web Browser (window, document, etc)
"browserify" : false, // Browserify (node.js code in the browser)
"couch" : false, // CouchDB
"devel" : false, // Development/debugging (alert, confirm, etc)
"dojo" : false, // Dojo Toolkit
"jasmine" : false, // Jasmine
"jquery" : false, // jQuery
"mocha" : false, // Mocha
"mootools" : false, // MooTools
"node" : true, // Node.js
"nonstandard" : false, // Widely adopted globals (escape, unescape, etc)
"prototypejs" : false, // Prototype and Scriptaculous
"qunit" : false, // QUnit
"rhino" : false, // Rhino
"shelljs" : false, // ShellJS
"worker" : false, // Web Workers
"wsh" : false, // Windows Scripting Host
"yui" : false, // Yahoo User Interface
// Custom Globals
"globals" : {} // additional predefined global variables
}

3
js/node/node_modules/foxx_generator/.npmignore generated vendored Normal file
View File

@ -0,0 +1,3 @@
.DS_STORE
node_modules
npm-debug.log

202
js/node/node_modules/foxx_generator/LICENSE generated vendored Normal file
View File

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

163
js/node/node_modules/foxx_generator/README.md generated vendored Normal file
View File

@ -0,0 +1,163 @@
# FoxxGenerator
FoxxGenerator is a declarative JavaScript framework that allows developers to describe the API in terms of the domain using statecharts. This declarative approach is based upon a combination of Richardson and Amundsen's design approach described in their book [RESTful Web APIs](http://restfulwebapis.com), Eric Evans' ideas from his book [domain driven design](http://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215) and the Harel's statecharts introduced in his paper *Statecharts: A Visual Formalism For Complex Systems*.
To create an API with FoxxGenerator, first draw a statechart that represents your API. In this statechart, your states can have one of the following types:
* Entity: This state represents something that has an identity and an arbitrary number of (optionally nested) attributes.
* Repository: A repository can store entities.
* Service: A service can do something. What it can do is defined via a JavaScript function that you can define. A service does not have a state.
Connect these states with transitions. When you have modeled your statechart in a way that it can fulfill all your use cases, it is time to classify your transitions. For every transition you have to decide which of the following type it follows:
* `follow`: This is a transition that you can just follow from one state to the next.
* `connect`: This is a point of extension where you can create a transition at runtime. In order to be able to follow this transition, you have to add a `follow` transition as well.
* `disconnect`: With this transition you can remove a transition created with `connect`.
* `modify`: This is a transition that can only be created from an entity to itself. It is used to modify the state of this entity.
You can now translate this annotated statechart into the DSL of FoxxGenerator to create your API.
## Setting up a Foxx application with FoxxGenerator.
First, create a Foxx application as described in [Foxx's manual](http://docs.arangodb.org/Foxx/README.html). In the folder of your Foxx app, you can now install FoxxGenerator with `npm install foxx_generator`. In the same way you would add a controller to your Foxx application, you can now add a FoxxGenerator to your application: In the file that would normally contain your FoxxController, add the following:
```js
var FoxxGenerator = require('foxx_generator').Generator,
Joi = require('joi'),
generator;
generator = new FoxxGenerator('name_of_your_app', {
// To learn more about media types, see below
mediaType: 'application/vnd.siren+json',
applicationContext: applicationContext,
});
// Insert transition definitions here
// Insert states here
generator.generate();
```
For more information on how to choose a media type, see the section about Media types. Now you can define the transitions you used in your statechart and then add the states and the transitions between them.
## Defining the transitions
Every transition needs the following attributes:
* A name for the transition that you can use when you want to add a transition of this type.
* `type`: One of the types described above.
* `to`: Is the target of this transition one or more states? For a `connect` transition this for example determines if you can only connect one state to it or more than that. Acceptable values are `one` and `many`.
You can also add a documentation block (a JavaScript comment starting with `/**`) that will be used for the documentation. The first line should be a short summary, all other lines will be used for a long description. An example for that would be the following transition definition:
```js
/** Show details for a particular item
*
* Show all information about this particular item.
*/
generator.defineTransition('showDetail', {
type: 'follow',
to: 'one'
});
```
For a `connect` and `disconnect` transition you additionally have to determine which `follow` transition can be used to follow the created transition. This is done with `as` and the name of the transition.
You can also add `parameters` to the transition, if in the transition process you need additional information from the user of the API. Each of the parameters needs to be a value object defined with [Joi](https://github.com/hapijs/joi). For example:
```js
/** Modify the title of the entity
*
*/
generator.defineTransition('changeTitle', {
type: 'modify',
to: 'one',
parameters: {
title: Joi.string()
}
});
```
You can also define a `condition` for a transition. This is a JavaScript function that takes the parameters of the HTTP request as its argument and returns either true or false. If it is true, the transition can be executed. If it is false, the transition can not be executed and the link to execute it will be hidden from the representation. This can for example be used for user authorization.
## Adding states and transitions
Now you can add states and transitions to your API. Every state has a name, a type and a number of outgoing transitions. The type is one of the above described ones either `entity`, `repository` or `service`. Every transition needs information about where it leads to and via which transition type. The transition type needs to be defined as described above. Simple example:
```js
generator.addState('ideas', {
type: 'repository',
contains: 'idea',
transitions: [
{ to: 'idea', via: 'showDetail' }
]
});
```
Some states take additional information: Entities need to know which repository they are contained in (via `containedIn`) and repositories need to know which entities they contain (via `contains`).
### Entity
An entity can be `parameterized` (by setting its attribute `parameterized` to `true`) which means that there is not only one state of that type, but there can be an arbitrary amount each of them is identified by a parameter. This is usually the case with entities that are stored in a repository.
It also takes an object of attributes which describe the representation of the entity. Each of the attributes needs to be a value object defined with [Joi](https://github.com/hapijs/joi).
Example for an entity:
```js
generator.addState('idea', {
type: 'entity',
parameterized: true,
containedIn: 'ideas',
attributes: {
description: Joi.string().required(),
title: Joi.string().required()
},
transitions: [
{ to: 'idea', via: 'relatedIdea' }
]
});
```
### Service
A service needs to describe what it does, this is done with an `action` which is a function that takes a request and a response in the [same way that a FoxxController route does](http://docs.arangodb.org/Foxx/FoxxController.html). The default HTTP verb for a service is a `post`, it can be changed by setting the `verb`. Example:
```js
generator.addState('title', {
type: 'service',
verb: 'get',
action: function (req, res) {
var entity = req.params('entity');
res.json({ title: entity.get('title') });
}
});
```
## Media types
FoxxGenerator currently only supports [siren](https://github.com/kevinswiber/siren) which is a media type without application semantics. Use the media type `application/vnd.siren+json`. We plan to support HAL with an extension for forms in the near future.
## Interactive Documentation
During your development, FoxxGenerator will generate an interactive documentation alongside the API. You can use this in an iterative development style to check after each step if the API is as you expected it to be. The documentation allows you to try out each of the generated endpoints. The API documentation can be found in the admin interface of ArangoDB and looks a little like this:
![Overview](screenshots/overview.png)
If you click on one of the routes, you can try it out:
![Try it out](screenshots/try_it_out.png)
## Examples
* An example for a Siren API generated with FoxxGenerator can be found [here](https://github.com/moonglum/siren)
## Linting
To check the project for linting errors, run `npm run jshint`.

54
js/node/node_modules/foxx_generator/foxx_generator.js generated vendored Normal file
View File

@ -0,0 +1,54 @@
(function () {
'use strict';
var Foxx = require('org/arangodb/foxx'),
_ = require('underscore'),
Graph = require('./foxx_generator/graph').Graph,
Generator,
StateFactory = require('./foxx_generator/state_factory').StateFactory,
TransitionFactory = require('./foxx_generator/transition_factory').TransitionFactory,
configureStates = require('./foxx_generator/configure_states').configureStates,
mediaTypes;
mediaTypes = {
'application/vnd.siren+json': require('./foxx_generator/siren').mediaType
};
Generator = function (name, options) {
var applicationContext = options.applicationContext,
graph = new Graph(name, applicationContext),
strategies = mediaTypes[options.mediaType].strategies;
this.controller = new Foxx.Controller(applicationContext, options);
this.states = {};
this.transitions = [];
this.stateFactory = new StateFactory(graph, this.transitions, this.states);
this.transitionFactory = new TransitionFactory(applicationContext, graph, this.controller, strategies);
};
_.extend(Generator.prototype, {
addStartState: function (opts) {
var name = '',
options = _.defaults({ type: 'start', controller: this.controller }, opts);
this.states[name] = this.stateFactory.create(name, options);
},
addState: function (name, opts) {
this.states[name] = this.stateFactory.create(name, opts);
},
defineTransition: function (name, opts) {
this.transitions[name] = this.transitionFactory.create(name, opts);
},
generate: function () {
configureStates(this.states);
_.each(this.states, function (state) { state.prepareTransitions(this.transitions, this.states); }, this);
_.each(this.states, function (state) { state.applyTransitions(); }, this);
}
});
exports.Generator = Generator;
}());

View File

@ -0,0 +1,13 @@
(function () {
'use strict';
var ConditionNotFulfilled;
ConditionNotFulfilled = function (msg) {
this.name = 'ConditionNotFulfilled';
this.msg = msg;
};
ConditionNotFulfilled.prototype = Error.prototype;
exports.ConditionNotFulfilled = ConditionNotFulfilled;
}());

View File

@ -0,0 +1,103 @@
(function () {
'use strict';
var _ = require('underscore'),
R = require('ramda'),
Repository = require('./repository_with_graph').RepositoryWithGraph,
Model = require('./model').Model,
configureStates,
typeIs,
determineSuperstate,
prepareStartState,
prepareServiceState,
determinePrefix,
prependPrefix,
appendIdPlaceholder,
isParameterized,
hasUrlTemplate,
appendIdPlaceholderForParameterizedState,
determineUrlTemplate,
determineUrlTemplateIfNotDetermined,
prepareEntityState,
prepareRepositoryState,
copyInfoFromRepositoryState;
typeIs = R.curry(function (type, state) {
return state.type === type;
});
determineSuperstate = R.curry(function (states, state) {
if (state.superstate) {
state.superstate = states[state.superstate];
}
});
prepareStartState = R.curry(R.func('setAsStart'));
prepareServiceState = R.curry(R.func('addService'));
determinePrefix = function (state) {
var prefix = '/';
if (state.superstate) {
// First determine the entire chain
determineUrlTemplateIfNotDetermined(state.superstate);
prefix = state.superstate.urlTemplate + '/';
}
return prefix;
};
prependPrefix = function (state) {
state.urlTemplate = R.concat(determinePrefix(state), state.name);
return state;
};
appendIdPlaceholder = function(state) {
state.urlTemplate = R.concat(state.urlTemplate, '/:id');
return state;
};
isParameterized = R.prop('parameterized');
hasUrlTemplate = R.prop('urlTemplate');
appendIdPlaceholderForParameterizedState = R.cond(isParameterized, appendIdPlaceholder, R.identity);
determineUrlTemplate = R.pipe(prependPrefix, appendIdPlaceholderForParameterizedState);
determineUrlTemplateIfNotDetermined = R.cond(hasUrlTemplate, R.identity, determineUrlTemplate);
prepareEntityState = R.curry(function (states, entity) {
var repositoryState = states[entity.options.containedIn];
entity.repositoryState = repositoryState;
entity.addModel(Model);
});
prepareRepositoryState = R.curry(function (states, repository) {
var entityState = states[repository.options.contains];
repository.entityState = entityState;
repository.model = entityState.model;
repository.addRepository(Repository);
});
copyInfoFromRepositoryState = function (entity) {
var repositoryState = entity.repositoryState,
repository = repositoryState.repository;
entity.collectionName = repositoryState.collectionName;
entity.collection = repositoryState.collection;
entity.repository = repositoryState.repository;
repository.relations = entity.relations;
};
configureStates = function (states) {
var entities = _.filter(states, typeIs('entity')),
repositories = _.filter(states, typeIs('repository')),
services = _.filter(states, typeIs('service')),
starts = _.filter(states, typeIs('start'));
_.each(states, determineSuperstate(states));
_.each(states, determineUrlTemplateIfNotDetermined);
_.each(starts, prepareStartState);
_.each(services, prepareServiceState);
_.each(entities, prepareEntityState(states));
_.each(repositories, prepareRepositoryState(states));
_.each(entities, copyInfoFromRepositoryState);
};
exports.configureStates = configureStates;
}());

View File

@ -0,0 +1,52 @@
(function () {
'use strict';
var Foxx = require('org/arangodb/foxx'),
ConditionNotFulfilled = require('./condition_not_fulfilled').ConditionNotFulfilled,
VertexNotFound = require('./vertex_not_found').VertexNotFound,
wrapServiceAction = require('./wrap_service_action').wrapServiceAction,
constructBodyParams,
joi = require('joi'),
constructRoute;
constructBodyParams = function (relation) {
return Foxx.Model.extend({ schema: relation.parameters });
};
constructRoute = function (opts) {
var route,
controller = opts.controller,
// from = opts.from,
// graph = opts.graph,
to = opts.to,
verb,
url = opts.url || to.urlTemplate,
action,
relation = opts.relation;
if (to.type === 'service') {
verb = to.verb;
action = wrapServiceAction(to);
} else {
verb = opts.verb;
action = opts.action;
}
route = controller[verb](url, action)
.errorResponse(VertexNotFound, 404, 'The vertex could not be found')
.errorResponse(ConditionNotFulfilled, 403, 'The condition could not be fulfilled')
.onlyIf(relation.condition)
.summary(relation.summary)
.notes(relation.notes);
if (url.indexOf(':') > 0) {
route.pathParam('id', joi.string().description('ID of the entity'));
}
if (opts.body) {
route.bodyParam(opts.body.name, 'TODO', constructBodyParams(relation));
}
};
exports.constructRoute = constructRoute;
}());

View File

@ -0,0 +1,34 @@
(function () {
'use strict';
var Context,
_ = require('underscore'),
extend = require('org/arangodb/extend').extend;
/*jshint maxlen: 200 */
Context = function (from, to, relation) {
from.relations.push(relation);
this.from = from;
this.to = to;
this.relation = relation;
this.strategy = _.find(this.strategies, function (maybeStrategy) {
return maybeStrategy.executable(relation.type, from.type, to.type, relation.cardinality);
});
if (_.isUndefined(this.strategy)) {
require('console').log('Couldn\'t find a strategy for semantic %s from %s to %s (%s)', relation.type, from.type, to.type, relation.cardinality);
throw 'Could not find strategy';
}
};
/*jshint maxlen: 100 */
_.extend(Context.prototype, {
execute: function (controller, graph) {
this.strategy.execute(controller, graph, this.relation, this.from, this.to);
}
});
Context.extend = extend;
exports.Context = Context;
}());

View File

@ -0,0 +1,19 @@
(function () {
'use strict';
var Documentation = function (applicationContext) {
this.summary = '';
this.notes = '';
if (applicationContext.comments.length > 0) {
do {
this.summary = applicationContext.comments.shift();
} while (this.summary === '');
this.notes = applicationContext.comments.join('\n');
}
applicationContext.clearComments();
};
exports.Documentation = Documentation;
}());

View File

@ -0,0 +1,125 @@
(function () {
'use strict';
var graphModule = require('org/arangodb/general-graph'),
ArangoError = require('internal').ArangoError,
_ = require('underscore'),
report = require('./reporter').report,
Graph,
VertexNotFound = require('./vertex_not_found').VertexNotFound,
tryAndHandleArangoError,
alreadyExists;
tryAndHandleArangoError = function (func, errHandler) {
try {
func();
} catch (e) {
if (e instanceof ArangoError) {
errHandler();
} else {
throw e;
}
}
};
alreadyExists = function (type, name) {
return function () {
report('%s "%s" already added. Leaving it untouched.', type, name);
};
};
Graph = function (name, appContext) {
var that = this;
this.appContext = appContext;
tryAndHandleArangoError(function () {
that.graph = graphModule._graph(name);
}, function () {
that.graph = graphModule._create(name);
});
};
_.extend(Graph.prototype, {
extendEdgeDefinitions: function (rawEdgeCollectionName, from, to) {
var vertexCollections, edgeCollectionName, edgeDefinition, graph;
edgeCollectionName = this.appContext.collectionName(rawEdgeCollectionName);
if (from.type === 'entity' && to.type === 'entity' && from.collectionName && to.collectionName) {
vertexCollections = [ from.collectionName, to.collectionName ];
edgeDefinition = graphModule._undirectedRelation(edgeCollectionName, vertexCollections);
graph = this.graph;
tryAndHandleArangoError(function () {
graph._extendEdgeDefinitions(edgeDefinition);
}, alreadyExists('EdgeDefinition', edgeCollectionName));
} else {
report('Invalid edge definition for "%s" and "%s"', from.collectionName, to.collectionName);
}
return edgeCollectionName;
},
addVertexCollection: function (collectionName) {
var prefixedCollectionName = this.appContext.collectionName(collectionName),
graph = this.graph;
tryAndHandleArangoError(function () {
graph._addVertexCollection(prefixedCollectionName, true);
}, alreadyExists('Collection', prefixedCollectionName));
return this.graph[prefixedCollectionName];
},
neighbors: function (id, options) {
return this.graph._neighbors(id, options);
},
edges: function (id, options) {
return this.graph._vertices(id).edges().restrict(options.edgeCollectionRestriction).toArray();
},
removeEdges: function (options) {
var graph = this.graph,
vertexId = options.vertexId,
edgeCollectionName = options.edgeCollectionName,
edges;
edges = this.edges(vertexId, {
edgeCollectionRestriction: [edgeCollectionName],
});
_.each(edges, function (edge) {
graph[edgeCollectionName].remove(edge._id);
});
},
checkIfVerticesExist: function (ids) {
if (!_.every(ids, this.hasVertex, this)) {
throw new VertexNotFound();
}
},
hasVertex: function (id) {
return this.graph._vertices(id).count() > 0;
},
areConnected: function (sourceId, destinationId) {
return this.graph._edges([
{ _from: sourceId, _to: destinationId },
{ _from: destinationId, _to: sourceId }
]).count() > 0;
},
createEdge: function (options) {
var sourceId = options.sourceId,
destinationId = options.destinationId,
edgeCollectionName = options.edgeCollectionName,
edgeCollection = this.graph[edgeCollectionName];
if (!this.areConnected(sourceId, destinationId)) {
edgeCollection.save(sourceId, destinationId, {});
}
}
});
exports.Graph = Graph;
}());

View File

@ -0,0 +1,18 @@
(function () {
'use strict';
var Foxx = require('org/arangodb/foxx'),
Model;
Model = Foxx.Model.extend({
forClient: function () {
var properties = Foxx.Model.prototype.forClient.call(this);
return {
properties: properties,
links: []
};
}
});
exports.Model = Model;
}());

View File

@ -0,0 +1,48 @@
(function () {
'use strict';
var RelationRepository,
_ = require('underscore');
RelationRepository = function (from, to, relation, graph) {
this.edgeCollectionName = relation.edgeCollectionName;
this.fromId = function (key) { return from.collectionName + '/' + key; };
this.toId = function (key) { return to.collectionName + '/' + key; };
this.graph = graph;
};
_.extend(RelationRepository.prototype, {
replaceRelation: function (sourceKey, destinationKey) {
var sourceId = this.fromId(sourceKey),
destinationId = this.toId(destinationKey),
edgeCollectionName = this.edgeCollectionName,
graph = this.graph;
graph.checkIfVerticesExist([destinationId, sourceId]);
graph.removeEdges({ vertexId: sourceId, edgeCollectionName: edgeCollectionName, throwError: false });
graph.createEdge({ edgeCollectionName: edgeCollectionName, sourceId: sourceId, destinationId: destinationId });
},
addRelations: function (sourceKey, destinationKeys) {
var sourceId = this.fromId(sourceKey),
destinationIds = _.map(destinationKeys, this.toId, this),
edgeCollectionName = this.edgeCollectionName,
graph = this.graph;
graph.checkIfVerticesExist(_.union(sourceId, destinationIds));
_.each(destinationIds, function (destinationId) {
graph.createEdge({ edgeCollectionName: edgeCollectionName, sourceId: sourceId, destinationId: destinationId });
});
},
deleteRelation: function (sourceKey) {
var sourceId = this.fromId(sourceKey),
edgeCollectionName = this.edgeCollectionName,
graph = this.graph;
graph.checkIfVerticesExist([sourceId]);
graph.removeEdges({ vertexId: sourceId, edgeCollectionName: edgeCollectionName });
}
});
exports.RelationRepository = RelationRepository;
}());

View File

@ -0,0 +1,13 @@
(function () {
'use strict';
var report,
developmentMode = false;
report = function () {
if (developmentMode) {
require('console').log.apply(this, arguments);
}
};
exports.report = report;
}());

View File

@ -0,0 +1,48 @@
(function () {
'use strict';
var Foxx = require('org/arangodb/foxx'),
_ = require('underscore'),
RepositoryWithGraph;
RepositoryWithGraph = Foxx.Repository.extend({
allWithNeighbors: function (options) {
var results = this.all(options);
_.each(results, function (result) {
this.addLinks(result);
}, this);
return results;
},
byIdWithNeighbors: function (key) {
var result = this.byId(key);
this.addLinks(result);
return result;
},
removeByKey: function (key) {
this.collection.remove(key);
},
addLinks: function (model) {
var links = {},
graph = this.graph,
relations = _.filter(this.relations, function (relation) { return relation.type === 'follow'; });
_.each(relations, function (relation) {
var neighbors = graph.neighbors(model.get('_id'), {
edgeCollectionRestriction: [relation.edgeCollectionName]
});
if (relation.cardinality === 'one' && neighbors.length > 0) {
links[relation.name] = neighbors[0]._key;
} else if (relation.cardinality === 'many') {
links[relation.name] = _.pluck(neighbors, '_key');
}
});
model.set('links', links);
}
});
exports.RepositoryWithGraph = RepositoryWithGraph;
}());

View File

@ -0,0 +1,304 @@
(function () {
'use strict';
var RelationRepository = require('./relation_repository').RelationRepository,
Strategy = require('./strategy').Strategy,
constructRoute = require('./construct_route').constructRoute,
ModifyAnEntity,
AddEntityToRepository,
ConnectRepoWithEntity,
ConnectStartWithRepository,
ConnectToService,
DisconnectTwoEntities,
DisconnectTwoEntitiesToMany,
ConnectEntityToService,
ConnectTwoEntities,
ConnectTwoEntitiesToMany,
FollowToEntity,
FollowToEntityToMany,
FollowFromRepositoryToService;
ConnectEntityToService = Strategy.extend({
type: 'follow',
from: 'entity',
to: 'service',
cardinality: 'one',
execute: function (controller, graph, relation, from, to) {
constructRoute({
controller: controller,
graph: graph,
from: from,
to: to,
relation: relation
});
}
});
ModifyAnEntity = Strategy.extend({
type: 'modify',
from: 'entity',
to: 'entity',
cardinality: 'one',
execute: function (controller, graph, relation, from, to) {
constructRoute({
controller: controller,
graph: graph,
verb: 'patch',
url: from.urlTemplate,
action: function (req, res) {
var id = req.params('id'),
patch = req.params(from.name),
result;
from.repository.updateById(id, patch.forDB());
result = from.repository.byIdWithNeighbors(id);
res.json(result.forClient());
},
from: from,
to: to,
relation: relation,
body: from
});
}
});
ConnectTwoEntities = Strategy.extend({
type: 'connect',
from: 'entity',
to: 'entity',
cardinality: 'one',
execute: function (controller, graph, relation, from, to) {
var relationRepository = new RelationRepository(from, to, relation, graph);
constructRoute({
controller: controller,
graph: graph,
verb: 'post',
url: from.urlForRelation(relation),
action: function (req, res) {
relationRepository.replaceRelation(req.params('id'), req.body()[relation.name]);
res.status(204);
},
from: from,
to: to,
relation: relation
});
}
});
ConnectTwoEntitiesToMany = Strategy.extend({
type: 'connect',
from: 'entity',
to: 'entity',
cardinality: 'many',
execute: function (controller, graph, relation, from, to) {
var relationRepository = new RelationRepository(from, to, relation, graph);
constructRoute({
controller: controller,
graph: graph,
verb: 'post',
url: from.urlForRelation(relation),
action: function (req, res) {
relationRepository.addRelations(req.params('id'), req.body()[relation.name]);
res.status(204);
},
from: from,
to: to,
relation: relation
});
}
});
DisconnectTwoEntities = Strategy.extend({
type: 'disconnect',
from: 'entity',
to: 'entity',
cardinality: 'one',
execute: function (controller, graph, relation, from, to) {
var relationRepository = new RelationRepository(from, to, relation, graph);
constructRoute({
controller: controller,
graph: graph,
verb: 'delete',
url: from.urlForRelation(relation),
action: function (req, res) {
relationRepository.deleteRelation(req.params('id'));
res.status(204);
},
from: from,
to: to,
relation: relation
});
}
});
DisconnectTwoEntitiesToMany = Strategy.extend({
type: 'disconnect',
from: 'entity',
to: 'entity',
cardinality: 'many'
});
FollowToEntity = Strategy.extend({
type: 'follow',
from: 'entity',
to: 'entity',
cardinality: 'one'
});
FollowToEntityToMany = Strategy.extend({
type: 'follow',
from: 'entity',
to: 'entity',
cardinality: 'many'
});
AddEntityToRepository = Strategy.extend({
type: 'connect',
from: 'repository',
to: 'entity',
cardinality: 'one',
execute: function (controller, graph, relation, from, to) {
from.addActionWithMethodForRelation('POST', relation);
constructRoute({
controller: controller,
graph: graph,
verb: 'post',
url: from.urlTemplate,
action: function (req, res) {
var data = {},
model = req.params(to.name);
data[to.name] = from.repository.save(model).forClient();
res.status(201);
res.json(data);
},
from: from,
to: to,
relation: relation,
body: to
});
}
});
ConnectRepoWithEntity = Strategy.extend({
type: 'follow',
from: 'repository',
to: 'entity',
cardinality: 'one',
execute: function (controller, graph, relation, from, to) {
constructRoute({
controller: controller,
graph: graph,
verb: 'get',
action: function (req, res) {
var id = req.params('id'),
entry = from.repository.byIdWithNeighbors(id);
res.json(entry.forClient());
},
from: from,
to: to,
relation: relation
});
from.addLinkToEntities(relation, to);
}
});
ConnectStartWithRepository = Strategy.extend({
type: 'follow',
from: 'start',
to: 'repository',
cardinality: 'one',
execute: function (controller, graph, relation, from, to) {
from.addLinkViaTransitionTo(relation, to);
constructRoute({
controller: controller,
graph: graph,
verb: 'get',
action: function (req, res) {
res.json({
properties: to.properties(),
entities: to.entities(),
links: to.filteredLinks(req),
actions: to.filteredActions(req)
});
},
from: from,
to: to,
relation: relation
});
}
});
ConnectToService = Strategy.extend({
type: 'follow',
from: 'start',
to: 'service',
cardinality: 'one',
execute: function (controller, graph, relation, from, to) {
from.addLinkViaTransitionTo(relation, to);
constructRoute({
controller: controller,
graph: graph,
from: from,
to: to,
relation: relation,
body: to
});
}
});
FollowFromRepositoryToService = Strategy.extend({
type: 'follow',
from: 'repository',
to: 'service',
cardinality: 'one',
execute: function (controller, graph, relation, from, to) {
from.addLinkViaTransitionTo(relation, to);
constructRoute({
controller: controller,
graph: graph,
from: from,
to: to,
relation: relation
});
}
});
exports.mediaType = {
strategies: [
new ModifyAnEntity(),
new ConnectTwoEntities(),
new DisconnectTwoEntities(),
new DisconnectTwoEntitiesToMany(),
new FollowToEntity(),
new FollowToEntityToMany(),
new AddEntityToRepository(),
new ConnectRepoWithEntity(),
new ConnectEntityToService(),
new ConnectToService(),
new ConnectTwoEntitiesToMany(),
new ConnectStartWithRepository(),
new FollowFromRepositoryToService()
]
};
}());

View File

@ -0,0 +1,203 @@
(function () {
'use strict';
var stateTypes = ['entity', 'repository', 'service', 'start'],
extend = require('org/arangodb/extend').extend,
_ = require('underscore'),
constructFields,
State;
constructFields = function (relation) {
return _.map(relation.parameters, function (joi, name) {
var fieldDescription = { name: name, type: joi._type };
if (!_.isNull(joi._description)) {
fieldDescription.description = joi._description;
}
if (!_.isUndefined(joi._flags.default)) {
fieldDescription.value = joi._flags.default;
}
return fieldDescription;
});
};
State = function (name, graph, options) {
this.name = name;
this.graph = graph;
this.options = options;
this.parameterized = this.options.parameterized;
this.superstate = this.options.superstate;
this.type = this.options.type;
if (!_.contains(stateTypes, this.type)) {
require('console').log('Unknown state type "' + options.type + '"');
throw 'Unknown State Type';
}
this.links = [];
this.actions = [];
this.childLinks = [];
this.relations = [];
};
_.extend(State.prototype, {
prepareTransitions: function (definitions, states) {
this.transitions = _.map(this.options.transitions, function (transitionDescription) {
var transition = definitions[transitionDescription.via],
to = states[transitionDescription.to];
return {
transition: transition,
to: to
};
}, this);
},
applyTransitions: function () {
_.each(this.transitions, function (transitionDescription) {
transitionDescription.transition.apply(this, transitionDescription.to);
}, this);
},
properties: function () {
return {};
},
setAsStart: function () {
var that = this;
this.options.controller.get('/', function (req, res) {
res.json({
properties: {},
links: that.filteredLinks(req),
actions: that.filteredActions(req)
});
}).summary('Billboard URL')
.notes('This is the starting point for using the API');
},
addRepository: function (Repository) {
this.collection = this.graph.addVertexCollection(this.name);
this.collectionName = this.collection.name();
this.repository = new Repository(this.collection, {
model: this.model,
graph: this.graph
});
},
addModel: function (Model) {
this.model = Model.extend({
schema: _.extend(this.options.attributes, { links: { type: 'object' } })
}, {
state: this,
});
},
addService: function () {
this.action = this.options.action;
this.verb = this.options.verb.toLowerCase();
},
urlForEntity: function (selector) {
if (!this.parameterized) {
throw 'This is not a paremeterized state';
}
return this.urlTemplate.replace(':id', selector);
},
urlForRelation: function (relation) {
return this.urlTemplate + '/links/' + relation.name;
},
entities: function () {
var entities = [];
if (this.type === 'repository') {
entities = _.map(this.repository.all(), function (entity) {
var result = entity.forClient();
_.each(this.childLinks, function (link) {
result.links.push({
rel: link.rel,
href: link.target.urlForEntity(entity.get('_key')),
title: link.title
});
});
return result;
}, this);
}
return entities;
},
filteredLinks: function (req) {
return _.filter(this.links, function (link) {
return link.precondition(req);
});
},
filteredActions: function (req) {
return _.filter(this.actions, function (action) {
return action.precondition(req);
});
},
addLink: function (rel, href, title, precondition) {
this.links.push({
precondition: precondition,
rel: rel,
href: href,
title: title
});
},
addLinkViaTransitionTo: function (relation, to) {
this.addLink([relation.name], to.urlTemplate, relation.summary, relation.precondition);
},
addLinkToEntities: function (relation, to) {
var rel = relation.name,
href = to.urlTemplate,
title = relation.summary,
target = to;
this.childLinks.push({
rel: rel,
href: href,
title: title,
target: target
});
},
addAction: function (name, method, href, title, fields, precondition) {
this.actions.push({
precondition: precondition,
name: name,
// class: ?,
method: method,
href: href,
title: title,
type: 'application/json',
fields: fields
});
},
addActionWithMethodForRelation: function (method, relation) {
var name = relation.name,
urlTemplate = this.urlTemplate,
summary = relation.summary,
fields = constructFields(relation),
precondition = relation.precondition;
this.addAction(name, method, urlTemplate, summary, fields, precondition);
}
});
State.extend = extend;
exports.State = State;
}());

View File

@ -0,0 +1,32 @@
(function () {
'use strict';
var _ = require('underscore'),
State = require('./state').State,
defaultsForStateOptions,
StateFactory;
defaultsForStateOptions = {
parameterized: false,
superstate: false,
verb: 'post',
maxFailures: 1,
queue: 'defaultQueue'
};
StateFactory = function (graph, transitions, states) {
this.graph = graph;
this.transitions = transitions;
this.states = states;
};
_.extend(StateFactory.prototype, {
create: function (name, opts) {
var options = _.defaults(opts, defaultsForStateOptions),
state = new State(name, this.graph, options);
return state;
}
});
exports.StateFactory = StateFactory;
}());

View File

@ -0,0 +1,27 @@
(function () {
'use strict';
var Strategy,
_ = require('underscore'),
extend = require('org/arangodb/extend').extend;
Strategy = function () {
};
_.extend(Strategy.prototype, {
executable: function (type, from, to, cardinality) {
return type === this.type && from === this.from && to === this.to && cardinality === this.cardinality;
},
execute: function () {
require('console').log('Nothing to do for strategy type "%s" from "%s" to "%s" with cardinality "%s"',
this.type,
this.from,
this.to,
this.cardinality);
}
});
Strategy.extend = extend;
exports.Strategy = Strategy;
}());

View File

@ -0,0 +1,54 @@
(function () {
'use strict';
var extend = require('org/arangodb/extend').extend,
ConditionNotFulfilled = require('./condition_not_fulfilled').ConditionNotFulfilled,
_ = require('underscore'),
Transition;
Transition = function (graph, controller) {
this.graph = graph;
this.controller = controller;
};
_.extend(Transition.prototype, {
extendEdgeDefinitions: function(from, to) {
var edgeCollectionName = this.collectionBaseName + '_' + from.name + '_' + to.name;
return this.graph.extendEdgeDefinitions(edgeCollectionName, from, to);
},
wrappedCondition: function () {
var condition = this.condition;
return function (req) {
if (!condition(req)) {
throw new ConditionNotFulfilled('Condition was not fulfilled');
}
};
},
createContext: function(from, to) {
var context = new this.Context(from, to, {
name: this.relationName,
edgeCollectionName: this.extendEdgeDefinitions(from, to),
cardinality: this.cardinality,
type: this.type,
parameters: this.parameters,
summary: this.summary,
notes: this.notes,
condition: this.wrappedCondition(),
precondition: this.precondition,
to: to
});
return context;
},
apply: function (from, to) {
this.createContext(from, to).execute(this.controller, this.graph);
}
});
Transition.extend = extend;
exports.Transition = Transition;
}());

View File

@ -0,0 +1,62 @@
(function () {
'use strict';
var _ = require('underscore'),
defaultsForTransitionOptions,
parseOptions,
Transition = require('./transition').Transition,
BaseContext = require('./context').Context,
Documentation = require('./documentation').Documentation;
defaultsForTransitionOptions = {
type: 'follow',
to: 'one',
condition: function () { return true; }
};
parseOptions = function (name, opts, applicationContext) {
var options,
documentation = new Documentation(applicationContext);
opts = opts || {};
options = _.defaults(opts, defaultsForTransitionOptions);
options.precondition = options.precondition || options.condition;
return _.extend(options, {
collectionBaseName: options.as || name,
relationName: name,
cardinality: options.to,
summary: documentation.summary,
notes: documentation.notes
});
};
var TransitionFactory = function (applicationContext, graph, controller, strategies) {
this.applicationContext = applicationContext;
this.graph = graph;
this.controller = controller;
var Context = BaseContext.extend({
strategies: strategies
});
this.Transition = Transition.extend({
Context: Context
});
};
_.extend(TransitionFactory.prototype, {
create: function (name, opts) {
var Transition,
options = parseOptions(name, opts, this.applicationContext),
transition;
Transition = this.Transition.extend(options);
transition = new Transition(this.graph, this.controller);
return transition;
}
});
exports.TransitionFactory = TransitionFactory;
}());

View File

@ -0,0 +1,12 @@
(function () {
'use strict';
var VertexNotFound;
VertexNotFound = function () {
this.name = 'VertexNotFound';
this.message = 'The vertex could not be found';
};
VertexNotFound.prototype = Error.prototype;
exports.VertexNotFound = VertexNotFound;
}());

View File

@ -0,0 +1,53 @@
(function () {
'use strict';
var wrapEntity,
wrapRepository,
selectByStateType,
wrapServiceAction;
wrapEntity = function (state) {
return function (req) {
var id = req.params('id');
return {
superstate: {
repository: state.repository,
entity: state.repository.byId(id)
}
};
};
};
wrapRepository = function (state) {
return function () {
return {
superstate: {
repository: state.repository
}
};
};
};
selectByStateType = function (state) {
var wrapper;
if (!state) {
return function () { return {}; };
}
if (state.type === 'entity') {
wrapper = wrapEntity;
} else if (state.type === 'repository') {
wrapper = wrapRepository;
}
return wrapper(state);
};
wrapServiceAction = function (serviceState) {
return function (req, res) {
serviceState.action(req, res, selectByStateType(serviceState.superstate)(req));
};
};
exports.wrapServiceAction = wrapServiceAction;
}());

34
js/node/node_modules/foxx_generator/package.json generated vendored Normal file

File diff suppressed because one or more lines are too long

Binary file not shown.

After

Width:  |  Height:  |  Size: 105 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

View File

@ -6,6 +6,7 @@
"coffee-script": "1.7.1",
"decimal": "0.0.2",
"docco": "0.6.3",
"foxx_generator": "^0.5.0",
"htmlparser2": "3.7.2",
"iced-coffee-script": "1.7.1-f",
"joi": "4.6.1",

View File

@ -502,7 +502,7 @@ StatisticsDistribution* TRI_BytesReceivedDistributionStatistics;
TRI_server_statistics_t TRI_ServerStatistics;
////////////////////////////////////////////////////////////////////////////////
/// @brief physical memeory
/// @brief physical memory
////////////////////////////////////////////////////////////////////////////////
uint64_t TRI_PhysicalMemory;

View File

@ -280,7 +280,7 @@ extern triagens::basics::StatisticsDistribution* TRI_BytesReceivedDistributionSt
extern TRI_server_statistics_t TRI_ServerStatistics;
////////////////////////////////////////////////////////////////////////////////
/// @brief physical memeory
/// @brief physical memory
////////////////////////////////////////////////////////////////////////////////
extern uint64_t TRI_PhysicalMemory;