Skip to content

Instantly share code, notes, and snippets.

@coryhouse
Created August 6, 2015 13:04
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save coryhouse/fd6232f95f9d601158e4 to your computer and use it in GitHub Desktop.
Save coryhouse/fd6232f95f9d601158e4 to your computer and use it in GitHub Desktop.
Mock Author API for "Building Applications with React and Flux" on Pluralsight
"use strict";
//This file is mocking a web API by hitting hard coded data.
var authors = require('./authorData').authors;
var _ = require('lodash');
//This would be performed on the server in a real app. Just stubbing in.
var _generateId = function(author) {
return author.firstName.toLowerCase() + '-' + author.lastName.toLowerCase();
};
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 AuthorApi = {
getAllAuthors: function() {
return _clone(authors);
},
getAuthorById: function(id) {
var author = _.find(authors, {id: id});
return _clone(author);
},
saveAuthor: function(author) {
//pretend an ajax call to web api is made here
console.log('Pretend this just saved the author to the DB via AJAX call...');
if (author.id) {
var existingAuthorIndex = _.indexOf(authors, _.find(authors, {id: author.id}));
authors.splice(existingAuthorIndex, 1, author);
} else {
//Just simulating creation here.
//The server would generate ids for new authors in a real app.
//Cloning so copy returned is passed by value rather than by reference.
author.id = _generateId(author);
authors.push(author);
}
return _clone(author);
},
deleteAuthor: function(id) {
console.log('Pretend this just deleted the author from the DB via an AJAX call...');
_.remove(authors, { id: id});
}
};
module.exports = AuthorApi;
@coryhouse
Copy link
Author

This file belongs in /src/api/authorApi.js

@juampick
Copy link

Thanks @coryhouse

@saikumarp
Copy link

thanks @coryhouse

@jeffreyyong
Copy link

thanks @coryhouse

@gameoft
Copy link

gameoft commented Feb 2, 2017

thanks @coryhouse

@destino92
Copy link

destino92 commented Feb 6, 2017

hello i am trying to load authors for the dropdown but it seems that they never get loaded and i get this error.
I am stuck at this line and when i console state it doesn't have authors.
const authorsFormattedForDropdown = state.authors.map(author => { return { value: author.id, text: author.firstName + ' ' + author.lastName }; });
screenshot 23

@dmsergeev
Copy link

@destino92 Did you add authorData.js?

@rtorres90
Copy link

Thanks!!

@mark-zacharias
Copy link

@bozdoganCihangir
Copy link

Thank you.

@igomolskyi
Copy link

Thank you :)

@leonardo-anjos
Copy link

Thanks!

@viviramji
Copy link

Thanks 👍

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