Last active
April 30, 2021 19:43
-
-
Save jeffijoe/8e8a4fcb7d2fd252ce0d84e91414095b to your computer and use it in GitHub Desktop.
Snippet for my Medium article
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Let's do an in-memory implementation for now. | |
const _todos = [] | |
export default class TodosRepository { | |
// Marking all methods async makes them return promises! | |
async find(query) { | |
const filtered = _todos.filter((todo) => { | |
// Check the user ID | |
if (todo.userId !== query.userId) | |
return false | |
// Check the filter | |
if (query.filter === 'COMPLETED') | |
return todo.completed === true | |
if (query.filter === 'INCOMPLETED') | |
return todo.completed === false | |
return true | |
}) | |
return filtered | |
} | |
async get(id) { | |
const todo = _todos.find(x => x.id === id) | |
return todo | |
} | |
async create(data) { | |
const newTodo = { | |
id: Date.now(), // cheeky ID generation | |
text: data.text, | |
userId: data.userId, | |
completed: data.completed | |
} | |
_todos.push(newTodo) | |
return newTodo | |
} | |
async update(id, data) { | |
const todo = await this.get(id) | |
Object.assign(todo, data) | |
return todo | |
} | |
async delete(id) { | |
const todo = await this.get(id) | |
const idx = _todos.indexOf(todo) | |
if (idx === -1) return | |
_todos.splice(idx, 1) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment