From 53fabd5bd6cdda0c2b6b60ccd761a99e71d3d2ee Mon Sep 17 00:00:00 2001 From: Balthazar Gronon Date: Thu, 8 Oct 2015 12:20:08 +0200 Subject: [PATCH] perf(user): update only on change --- api/services/user.service.js | 9 ++++++++- api/services/utils.service.js | 10 ++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 api/services/utils.service.js diff --git a/api/services/user.service.js b/api/services/user.service.js index ecfffdd..e58a8c7 100644 --- a/api/services/user.service.js +++ b/api/services/user.service.js @@ -1,5 +1,8 @@ 'use strict'; +import _ from 'lodash'; +import { propsDiffer } from './utils.service'; + import { User } from '../models'; exports.getById = id => { @@ -14,8 +17,12 @@ exports.updateOrCreate = (githubId, name, avatar) => { return exports.getByGithub(githubId) .then(user => { + if (!user) { return User.create({ githubId, name, avatar }); } - return user; + if (!propsDiffer(user, { name, avatar })) { return user; } + + _.assign(user, { name, avatar }); + return user.save(); }) .then(user => { if (user.banned) { throw new Error('You are banned from KeyCode.'); } diff --git a/api/services/utils.service.js b/api/services/utils.service.js new file mode 100644 index 0000000..33a6ba4 --- /dev/null +++ b/api/services/utils.service.js @@ -0,0 +1,10 @@ +'use strict'; + +export function propsDiffer (one, two, arr) { + if (!arr) { arr = Object.keys(two); } + const len = arr.length; + for (let i = 0; i < len; ++i) { + if (one[i] !== two[i]) { return true; } + } + return false; +};