lunch/js/actions/AttendeeActions.js
2016-12-23 20:38:59 -05:00

94 lines
1.8 KiB
JavaScript

var AttendeeConstants = require('../constants/AttendeeConstants');
var ErrorActions = require('./ErrorActions');
var models = require('../models.js');
var Attendee = models.Attendee;
var Error = models.Error;
function fetchAttendees() {
return {
type: AttendeeConstants.FETCH_ATTENDEES
}
}
function attendeesFetched(attendees) {
return {
type: AttendeeConstants.ATTENDEES_FETCHED,
attendees: attendees
}
}
function createAttendee() {
return {
type: AttendeeConstants.CREATE_ATTENDEE
}
}
function attendeeCreated(attendee) {
return {
type: AttendeeConstants.ATTENDEE_CREATED,
attendee: attendee
}
}
function fetchAll() {
return function (dispatch) {
dispatch(fetchAttendees());
$.ajax({
type: "GET",
dataType: "json",
url: "attendee/",
success: function(data, status, jqXHR) {
var e = new Error();
e.fromJSON(data);
if (e.isError()) {
ErrorActions.serverError(e);
} else {
dispatch(attendeesFetched(data.attendees.map(function(json) {
var a = new Attendee();
a.fromJSON(json);
return a;
})));
}
},
error: function(jqXHR, status, error) {
ErrorActions.ajaxError(e);
}
});
};
}
function create(attendee) {
return function (dispatch) {
dispatch(createAttendee());
$.ajax({
type: "POST",
dataType: "json",
url: "attendee/",
data: {attendee: attendee.toJSON()},
success: function(data, status, jqXHR) {
var e = new Error();
e.fromJSON(data);
if (e.isError()) {
ErrorActions.serverError(e);
} else {
var a = new Attendee();
a.fromJSON(data);
dispatch(attendeeCreated(a));
}
},
error: function(jqXHR, status, error) {
ErrorActions.ajaxError(e);
}
});
};
}
module.exports = {
fetchAll: fetchAll,
create: create
};