Skip to content

Instantly share code, notes, and snippets.

@coryhouse
Created August 6, 2015 20:50
Show Gist options
  • Save coryhouse/009cfa4863ee7c385bb3 to your computer and use it in GitHub Desktop.
Save coryhouse/009cfa4863ee7c385bb3 to your computer and use it in GitHub Desktop.
Mock CourseAPI for "Building Applications with React and Flux" on Pluralsight
"use strict";
//This file is mocking a web API by hitting hard coded data.
var courses = require('./courseData').courses;
var _ = require('lodash');
//This would be performed on the server in a real app. Just stubbing in.
var _generateId = function(course) {
return course.title.replace(' ', '-');
};
var _clone = function(item) {
return JSON.parse(JSON.stringify(item)); //return cloned copy so that the item is passed by value instead of by reference
};
var CourseApi = {
getAllCourses: function() {
return _clone(courses);
},
getCoursesById: function(id) {
var course = _.find(courses, {id: id});
return _clone(course);
},
saveCourse: function(course) {
console.log('Imagine saving course via AJAX call...');
if (course.id) {
var existingCourseIndex = _.indexOf(courses, _.find(courses, {id: course.id}));
courses.splice(existingCourseIndex, 1, course);
} else {
//just simulating creation here. This data
//would be generated on the server in a real app.
course.id = _generateId(course);
courses.push(_clone(course));
}
return course;
},
deleteCourse: function(id) {
console.log('Imagine deleting course with id of ' + id + ' via AJAX call...');
_.remove(courses, { id: id});
}
};
module.exports = CourseApi;
@kyle-morton
Copy link

Excellent course, Cory. Thanks so much for creating it.

@wendy321
Copy link

Thanks Cory. Great course!

@siya-07
Copy link

siya-07 commented Sep 6, 2018

Thanks, Cory, I've learned a lot during this course thanks a million

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