From 25ecac846f4bbb2172cbdb876c47ea2796974574 Mon Sep 17 00:00:00 2001 From: Roger Braun Date: Wed, 30 Nov 2016 18:29:44 +0100 Subject: [PATCH] Add users repository in users module. --- src/modules/users.js | 57 ++++++++++++++++++++------- test/unit/specs/modules/users.spec.js | 20 ++++++++++ 2 files changed, 62 insertions(+), 15 deletions(-) create mode 100644 test/unit/specs/modules/users.spec.js diff --git a/src/modules/users.js b/src/modules/users.js index 199799b8..46a2e087 100644 --- a/src/modules/users.js +++ b/src/modules/users.js @@ -1,23 +1,50 @@ import timelineFetcher from '../services/timeline_fetcher/timeline_fetcher.service.js' import backendInteractorService from '../services/backend_interactor_service/backend_interactor_service.js' +import { map, each, find, merge } from 'lodash' + +// TODO: Unify with mergeOrAdd in statuses.js +export const mergeOrAdd = (arr, item) => { + const oldItem = find(arr, {id: item.id}) + if (oldItem) { + // We already have this, so only merge the new info. + merge(oldItem, item) + return {item: oldItem, new: false} + } else { + // This is a new item, prepare it + arr.push(item) + return {item, new: true} + } +} + +export const mutations = { + setCurrentUser (state, user) { + state.currentUser = user + }, + beginLogin (state) { + state.loggingIn = true + }, + endLogin (state) { + state.loggingIn = false + }, + addNewUsers (state, users) { + each(users, (user) => mergeOrAdd(state.users, user)) + } +} + +export const defaultState = { + currentUser: false, + loggingIn: false, + users: [] +} const users = { - state: { - currentUser: false, - loggingIn: false - }, - mutations: { - setCurrentUser (state, user) { - state.currentUser = user - }, - beginLogin (state) { - state.loggingIn = true - }, - endLogin (state) { - state.loggingIn = false - } - }, + state: defaultState, + mutations, actions: { + addNewStatuses (store, { statuses }) { + const users = map(statuses, 'user') + store.commit('addNewUsers', users) + }, loginUser (store, userCredentials) { const commit = store.commit commit('beginLogin') diff --git a/test/unit/specs/modules/users.spec.js b/test/unit/specs/modules/users.spec.js new file mode 100644 index 00000000..07c71e32 --- /dev/null +++ b/test/unit/specs/modules/users.spec.js @@ -0,0 +1,20 @@ +import { cloneDeep } from 'lodash' + +import { defaultState, mutations } from '../../../../src/modules/users.js' + +describe('The users module', () => { + it('adds new users to the set, merging in new information for old users', () => { + const state = cloneDeep(defaultState) + const user = { id: 1, name: 'Guy' } + const modUser = { id: 1, name: 'Dude' } + + mutations.addNewUsers(state, [user]) + expect(state.users).to.have.length(1) + expect(state.users).to.eql([user]) + + mutations.addNewUsers(state, [modUser]) + expect(state.users).to.have.length(1) + expect(state.users).to.eql([user]) + expect(state.users[0].name).to.eql('Dude') + }) +})