-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinmemoryStorage.js
69 lines (53 loc) · 1.74 KB
/
inmemoryStorage.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
const shortid = require('shortid');
module.exports = () => {
let todos = [];
let users = [];
const getTodos = filterFn => (filterFn ? filterFn(todos) : todos);
const getUserTodos = (userId, filterFn) =>
getTodos(filterFn).filter(todo => todo.userId === userId);
const setTodos = initial => (todos = initial);
const getTodoById = (id, userId) => todos.find(todo => todo.id === id && todo.userId === userId);
const addTodo = (title, userId) => {
const todo = {
id: shortid.generate(),
title,
userId,
completed: false
};
todos.push(todo);
return todo;
};
const patchTodo = (patchId, newProps) =>
(todos = todos.map(todo => (todo.id === patchId ? Object.assign(todo, newProps) : todo)));
const deleteTodo = deleteId => (todos = todos.filter(todo => todo.id !== deleteId));
const clearUserTodos = userId => {
todos = todos.filter(todo => todo.userId !== userId);
return [];
};
const clearUserCompletedTodos = userId => {
todos = todos.filter(todo => (!todo.completed && todo.userId === userId) || todo.userId !== userId);
return todos.filter(todo => todo.userId === userId);
};
const getUsers = () => users;
const setUsers = initial => (users = initial);
const getUserById = id => users.find(user => user.id === id);
const authenticateUser = (username, password) => {
const user = users.find(user => user.username === username && user.password === password);
return Object.assign({}, user, { password: undefined });
};
return {
getTodos,
getUserTodos,
setTodos,
getTodoById,
addTodo,
patchTodo,
deleteTodo,
clearUserTodos,
clearUserCompletedTodos,
getUsers,
setUsers,
getUserById,
authenticateUser
};
};