Skip to content

Instantly share code, notes, and snippets.

@jeffijoe
Last active September 6, 2016 10:14
Show Gist options
  • Save jeffijoe/cc7e926ca025015a72496c38d4365597 to your computer and use it in GitHub Desktop.
Save jeffijoe/cc7e926ca025015a72496c38d4365597 to your computer and use it in GitHub Desktop.
Snippet for my Medium article
import assert from 'assert'
// Using object destructuring to make it look good.
export function makeTodosService({
// "repository" is a fancy term to descibe an object
// that is used to retrieve data from a datasource - the actual
// data source does not matter. Could be a database, a REST API,
// or some IoT things like sensors or whatever.
todosRepository,
// We also want info about the user that is using the service,
// so we can restrict access to only their own todos.
currentUser
}) {
// Let's assert that we got what we needed.
assert(todosRepository, 'opts.todosRepository is required.')
assert(currentUser, 'opts.currentUser is required.')
return {
// Gets todos for the current users.
getTodos: async (query) => {
// Query is just an object. In this case we can declare what
// todos we want - completed, uncompleted, or all.
const todos = await todosRepository.find({
// can be ALL, INCOMPLETED, COMPLETED
filter: query.filter,
userId: currentUser.id
})
return todos
},
// Creates a new todo for the current user
createTodo: async (data) => {
const newTodo = await todosRepository.create({
text: data.text,
userId: currentUser.id,
completed: false
})
return newTodo
},
// Updates a todo if allowed
updateTodo: async (todoId, data) {
const todo = await todosRepository.get(todoId)
// Verify that we are allowed to modify this todo
if (todo.userId !== currentUser.id) {
throw new Error('Forbidden!')
}
const updatedTodo = await todosRepository.update(todoId, {
text: data.text,
completed: data.completed
})
return updatedTodo
},
// Deletes a todo if allowed
deleteTodo: async (todoId) {
const todo = await todosRepository.get(todoId)
// Verify that we are allowed to delete this todo
if (todo.userId !== currentUser.id) {
throw new Error('Forbidden!')
}
await todosRepository.delete(todoId)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment