1
0
Fork 0

Merge pull request #1140 from stackmagic/args-for-transform

Allow passing addition arguments to transforms in Foxx queries.
This commit is contained in:
Alan Plum 2014-12-02 13:10:49 +01:00
commit 0731d03e58
2 changed files with 53 additions and 5 deletions

View File

@ -19,11 +19,12 @@ exports.repository = TodosRepository;
You can define custom query methods using Foxx.createQuery and Foxx.Repository.extend.
For more details see the chapter on Foxx Queries.
*Examples*
Making a simple query in the repository and using it from the controller:
```javascript
// in the repository
var Foxx = require("org/arangodb/foxx");
var TodosRepository = Foxx.Repository.extend({
@ -31,6 +32,52 @@ var TodosRepository = Foxx.Repository.extend({
'FOR todo IN my_todos FILTER todo.completed == false RETURN todo'
)
});
// in the controller
ctrl.get("/", function(req, res) {
req.json(todosRepository.getPendingItems());
});
```
It is also possible to supply parameters to the query:
```javascript
// in the repository
getPendingItemById: Foxx.createQuery(
'FOR todo IN my_todos FILTER todo.completed == false FILTER todo._key == @id RETURN todo'
)
// in the controller
ctrl.get("/:id", function(req, res) {
var id = req.params("id");
var rv = todosRepository.getPendingItemById({ id: id });
res.json(rv);
});
```
The list of results can also be transformed before returning it from the repository:
```javascript
// in the repository
getPendingItemById: Foxx.createQuery({
query: 'FOR todo IN my_todos FILTER todo.completed == false FILTER todo._key == @id RETURN todo',
transform: function(results, args) {
for (var i = 0; i < results.length; i++) {
results[i].extraProperty = args.extra;
}
}
})
// in the controller
ctrl.get("/:id", function(req, res) {
var id = req.params("id");
var extra = req.params("extra");
var rv = todosRepository.getPendingItemById(
{ id: id },
{ extra: extra }
);
res.json(rv);
});
```
!SECTION Attributes of a Repository

View File

@ -61,7 +61,7 @@ exports.createQuery = function createQuery (cfg) {
throw new Error('Expected transform to be a function.');
}
return function query(vars) {
return function query(vars, trArgs) {
vars = _.extend({}, defaults, vars);
if (context) {
_.each(vars, function (value, key) {
@ -76,6 +76,7 @@ exports.createQuery = function createQuery (cfg) {
return new Model(data);
});
}
return transform ? transform(result) : result;
return transform ? transform(result, trArgs) : result;
};
};
};