UNPKG

@jsynple/core

Version:

All the core modules and types for the Synple application

50 lines (49 loc) 1.75 kB
import { find, findIndex, remove } from 'lodash'; /** * A list service provides utility methods for handling lists of specific items, a thing we tend to do * a lot in the applciation, especially on the administration side. It allows the addition, update and * removal of items on a list, by calling the specific methods on the linked repository for this kind * of items. * @author Vincent Courtois <courtois.vincent@outlook.com> */ export class ListService { constructor(repository, token) { // The list of items queried on the repository, supposed to reflect the state on the API. this.items = []; this.repository = repository; this.token = token; } async fetch() { const results = this.repository.list(this.token); results.then((items = []) => { for (const item of items) this.append(item); }); return results; } get all() { return this.items; } async create(item) { const promise = this.repository.create(item, this.token); promise.then((item) => this.append(item)); return promise; } update(item) { const index = findIndex(this.items, i => i.id === item.id); if (index >= 0) { const newItem = { ...this.items[index], ...item }; this.items[index] = newItem; return this.repository.update(newItem, this.token); } } delete(item) { const id = typeof item === 'string' ? item : item.id; this.repository.delete(id, this.token); remove(this.items, (iteratee) => id === iteratee.id); } append(item) { if (!find(this.items, { id: item.id })) this.items.push(item); } }