|
import delay from './delay'; |
|
|
|
import { authors } from './authorData' |
|
//This would be performed on the server in a real app. Just stubbing in. |
|
|
|
let maxid = authors.reduce(((currentMax, {id}) => currentMax>id ? currentMax : id), 0 ); |
|
|
|
const generateId = (author) => { |
|
return ++maxid; |
|
}; |
|
|
|
const sleep = function (timeout) { |
|
return new Promise((resolve) => setTimeout(resolve, timeout)); |
|
}; |
|
|
|
|
|
class AuthorApi { |
|
static async getAllAuthors() { |
|
await sleep(delay); |
|
return Object.assign([], authors); // so users can change their copy without breaking this list |
|
} |
|
|
|
static async saveAuthor(author) { |
|
author = Object.assign({}, author); // to avoid manipulating object passed in. |
|
await sleep(delay); |
|
|
|
// Simulate server-side validation |
|
const minAuthorNameLength = 3; |
|
if (author.firstName.length < minAuthorNameLength) { |
|
throw new Error(`First Name must be at least ${minAuthorNameLength} characters.`); |
|
} |
|
|
|
if (author.lastName.length < minAuthorNameLength) { |
|
throw new Error(`Last Name must be at least ${minAuthorNameLength} characters.`); |
|
} |
|
|
|
if (author.id) { |
|
const existingAuthorIndex = authors.findIndex(a => a.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(); |
|
authors.push(author); |
|
} |
|
|
|
return author; |
|
} |
|
|
|
static async deleteAuthor(authorId) { |
|
await sleep(delay); |
|
|
|
const indexOfAuthorToDelete = authors.findIndex(author => ( |
|
author.id === authorId) |
|
); |
|
|
|
authors.splice(indexOfAuthorToDelete, 1); |
|
} |
|
} |
|
|
|
|
|
export default AuthorApi; |