Skip to content

Instantly share code, notes, and snippets.

@reneolivo
Created April 20, 2018 18:54
Show Gist options
  • Save reneolivo/18a14a762e3e55a32133a52abd58673e to your computer and use it in GitHub Desktop.
Save reneolivo/18a14a762e3e55a32133a52abd58673e to your computer and use it in GitHub Desktop.
Model Factoy proposal
define([
'common/modules/models'
], function (models) {
'use strict';
CaseModel.$inject = ['CaseInstance', 'ModelFactory'];
models.factory('Case', CaseModel);
function CaseModel (CaseInstance, ModelFactory) {
var Case = ModelFactory({
entity: 'Case',
instance: CaseInstance
// api: CaseApi <--- pass instead of "entity" if you want some custom api
});
// no need to define Case.all
// in case you want to define some custom method for Case models:
Case.findExpired = function () {
// ...
};
return Case;
}
});
define([
'common/modules/services'
], function (services) {
'use strict';
ModelFactory.$inject = ['APIFactory', 'instance', 'Model'];
services.factory('ModelFactory', ModelFactory);
function ModelFactory (APIFactory, genericInstance, Model) {
return function (modelConfiguration) {
var api = modelConfiguration.api || APIFactory(modelConfiguration.entity);
var instance = modelConfiguration.instance || genericInstance;
return Model.extend({
all: all
});
function all (filters, pagination, etc) {
api.all(filters, pagination, etc)
.then(function (response) {
response.list = response.list.map(function (entry) {
return instance.init(entry, true);
});
return response;
});
}
}
}
});
@reneolivo
Copy link
Author

For testing the Case model we'd just check if it passes the right parameters to the ModelFactory and test any custom methods.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment