What is the appropriate way to load a child model property of an Ampersand model when doing a fetch on the collection?
I have a Task object:
{
"id": 1
"projectId": 2 // child entity id
"name": "This task for project 1"
}
And I have created an Ampersand model:
var AmpModel = require('ampersand-model');
var Project = require('../project');
module.exports = AmpModel.extend({
props: {
id: ['number'],
projectId: ['number'],
name: ['string']
},
children: {
project: Project
}
});
And a collection:
var AmpCollection = require('ampersand-rest-collection');
var Task = require('./task');
module.exports = AmpCollection.extend({
model: Task,
url: '/api/task'
});
My API is very simple, as the app only stores input in memory:
var _ = require('lodash');
var store = require('../data'); // this is a file with some init data
function get(id) {
return _.findWhere(store.tasks.data, { id: parseInt(id + '', 10) });
}
exports.list = function (req, res) {
res.send(store.tasks.data);
};
exports.add = function (req, res) {
var item = req.body;
item.id = store.tasks.id++;
store.tasks.data.push(item);
res.status(201).send(item);
};
exports.get = function (req, res) {
var found = get(req.params.id);
res.status(found ? 200 : 404);
res.send(found);
};
In Entity Framework I would have included the child entity when retrieving. The projectId
field would map to the projects
table and the framework would take care of it for me.
After reading the doco and some help in the JavaScript chat room, I realise I have been looking at this architecture the wrong way.
My API should read the tasks data source and use the retrieved project ID to load the project data. The project object would be assigned to the projects
property on the task and the whole task object returned. Ampersand will then take over and assemble my model as expected.