lunch/js/actions/GroupActions.js
2017-01-10 08:46:34 -05:00

136 lines
2.5 KiB
JavaScript

var GroupConstants = require('../constants/GroupConstants');
var ErrorActions = require('./ErrorActions');
var models = require('../models');
var Group = models.Group;
var Error = models.Error;
function createGroup(group) {
return {
type: GroupConstants.CREATE_GROUP,
group: group
}
}
function groupCreated(group) {
return {
type: GroupConstants.GROUP_CREATED,
group: group
}
}
function fetchGroups() {
return {
type: GroupConstants.FETCH_GROUPS
}
}
function groupsFetched(groups) {
return {
type: GroupConstants.GROUPS_FETCHED,
groups: groups
}
}
function updateGroup(group) {
return {
type: GroupConstants.UPDATE_GROUP,
group: group
}
}
function groupUpdated(group) {
return {
type: GroupConstants.GROUP_UPDATED,
group: group
}
}
function fetchAll() {
return function (dispatch) {
dispatch(fetchGroups());
$.ajax({
type: "GET",
dataType: "json",
url: "group/",
success: function(data, status, jqXHR) {
var e = new Error();
e.fromJSON(data);
if (e.isError()) {
dispatch(ErrorActions.serverError(e));
} else {
dispatch(groupsFetched(data.groups.map(function(json) {
var g = new Group();
g.fromJSON(json);
return g;
})));
}
},
error: function(jqXHR, status, error) {
dispatch(ErrorActions.ajaxError(error));
}
});
};
}
function create(group) {
return function(dispatch) {
dispatch(createGroup(group));
$.ajax({
type: "POST",
dataType: "json",
url: "group/",
data: {group: group.toJSON()},
success: function(data, status, jqXHR) {
var e = new Error();
e.fromJSON(data);
if (e.isError()) {
dispatch(ErrorActions.serverError(e));
} else {
var u = new Group();
u.fromJSON(data);
dispatch(groupCreated(u));
}
},
error: function(jqXHR, status, error) {
dispatch(ErrorActions.ajaxError(error));
}
});
};
}
function update(group) {
return function (dispatch) {
dispatch(updateGroup());
$.ajax({
type: "PUT",
dataType: "json",
url: "group/"+group.GroupId+"/",
data: {group: group.toJSON()},
success: function(data, status, jqXHR) {
var e = new Error();
e.fromJSON(data);
if (e.isError()) {
dispatch(ErrorActions.serverError(e));
} else {
var g = new Group();
g.fromJSON(data);
dispatch(groupUpdated(u));
}
},
error: function(jqXHR, status, error) {
dispatch(ErrorActions.ajaxError(error));
}
});
};
}
module.exports = {
fetchAll: fetchAll,
create: create,
update: update
};