|
1 | 1 | import DeskbookersError from '../../DeskbookersError' |
2 | 2 | import Resource from '../Resource' |
| 3 | +import { pickAll } from 'ramda' |
| 4 | + |
| 5 | +// Construct and return Map |
| 6 | +function constructMap (obj) { |
| 7 | + const map = new Map() |
| 8 | + |
| 9 | + for (const key in obj) { |
| 10 | + map.set(key, obj[key]) |
| 11 | + } |
| 12 | + |
| 13 | + return map |
| 14 | +} |
3 | 15 |
|
4 | 16 | export default class Preferences extends Resource { |
5 | 17 | constructor (api) { |
6 | 18 | super(api) |
7 | 19 | this.endpoint = 'user/preferences' |
8 | 20 | } |
9 | 21 |
|
10 | | - async retrieve (key) { |
11 | | - const value = await this.request({ |
| 22 | + async getCurrentPreferences () { |
| 23 | + const res = await this.request({ |
12 | 24 | method: 'GET', |
13 | | - path: this.endpoint, |
14 | | - params: { |
15 | | - keys: [key] |
16 | | - } |
| 25 | + path: this.endpoint |
17 | 26 | }) |
18 | 27 |
|
19 | | - return value[0] |
| 28 | + return JSON.parse(res) |
| 29 | + } |
| 30 | + |
| 31 | + /** |
| 32 | + * Retrieve a single preference |
| 33 | + */ |
| 34 | + async retrieve (key) { |
| 35 | + const prefs = await this.list([key]) |
| 36 | + return prefs.get(key) || null |
20 | 37 | } |
21 | 38 |
|
| 39 | + /** |
| 40 | + * List all preferences, or a subset |
| 41 | + */ |
22 | 42 | async list (...keys) { |
23 | | - const preferences = await this.request({ |
24 | | - method: 'GET', |
25 | | - path: this.endpoint, |
26 | | - params: { |
27 | | - keys |
28 | | - } |
29 | | - }) |
| 43 | + const current = await this.getCurrentPreferences() |
| 44 | + |
| 45 | + // Filter preferences based on desired keys |
| 46 | + const prefs = keys.length ? pickAll(keys, current): current |
30 | 47 |
|
31 | | - // Construct and return Map |
32 | | - const map = new Map() |
33 | | - keys.forEach((key, i) => map.set(key, preferences[i])) |
34 | | - return map |
| 48 | + return constructMap(prefs) |
35 | 49 | } |
36 | 50 |
|
| 51 | + /** |
| 52 | + * Update preferences by key |
| 53 | + */ |
37 | 54 | async update (preferences = {}) { |
38 | | - const prefs = await this.request({ |
| 55 | + const prefs = await this.getCurrentPreferences() |
| 56 | + |
| 57 | + for (const key in preferences) { |
| 58 | + prefs[key] = preferences[key] |
| 59 | + } |
| 60 | + |
| 61 | + const res = await this.request({ |
39 | 62 | method: 'POST', |
40 | 63 | path: this.endpoint, |
41 | 64 | params: { |
42 | | - preferences |
| 65 | + preferences: prefs |
43 | 66 | } |
44 | 67 | }) |
45 | 68 |
|
46 | | - // Construct and return Map |
47 | | - const map = new Map() |
48 | | - Object.keys(prefs).forEach(key => map.set(key, prefs[key])) |
49 | | - return map |
| 69 | + return constructMap(JSON.parse(res)) |
50 | 70 | } |
51 | 71 | } |
0 commit comments