1 | | /** |
2 | | * Simulates a server with a database |
3 | | */ |
4 | 1 | var _ = require('lodash') |
5 | 1 | var Promise = require('es6-promise').Promise |
6 | | |
7 | 1 | var DATA = { |
8 | | user: { |
9 | | 1: { |
10 | | id: 1, |
11 | | name: 'jordan', |
12 | | email: 'jordan@nuclear.com', |
13 | | }, |
14 | | 2: { |
15 | | id: 2, |
16 | | name: 'jane', |
17 | | email: 'jane@nuclear.com', |
18 | | }, |
19 | | } |
20 | | } |
21 | | |
22 | | /** |
23 | | * Stubable function to get data |
24 | | */ |
25 | 1 | exports.__getData = function(entity) { |
26 | 0 | return DATA[entity] |
27 | | } |
28 | | |
29 | 1 | exports.create = function(entity, instance) { |
30 | 1 | var entityMap = exports.__getData(entity) |
31 | 1 | var lastEntity = _(entityMap) |
32 | | .toArray() |
33 | | .sortBy(function(entry) { |
34 | 2 | return entry.id |
35 | | }) |
36 | | .last() |
37 | | |
38 | 1 | var savedInstance = _.cloneDeep(instance) |
39 | 1 | savedInstance.id = lastEntity.id + 1 |
40 | | |
41 | 1 | entityMap[savedInstance.id] = savedInstance |
42 | | |
43 | 1 | return new Promise(function(resolve, reject) { |
44 | 1 | resolve(savedInstance) |
45 | | }) |
46 | | } |
47 | | |
48 | 1 | exports.update = function(entity, instance) { |
49 | 2 | return new Promise(function(resolve, reject) { |
50 | 2 | var entityMap = exports.__getData(entity) |
51 | 2 | if (!entityMap[instance.id]) { |
52 | 1 | reject('No entity with id=' + instance.id) |
53 | 1 | return |
54 | | } |
55 | | |
56 | 1 | entityMap[instance.id] = instance |
57 | 1 | resolve(instance) |
58 | | }) |
59 | | } |
60 | | |
61 | 1 | exports.fetch = function(entity, id) { |
62 | 2 | return new Promise(function(resolve, reject) { |
63 | 2 | var entityMap = exports.__getData(entity) |
64 | 2 | if (!entityMap[id]) { |
65 | 1 | reject('No entity with id=' + id) |
66 | 1 | return |
67 | | } |
68 | | |
69 | 1 | resolve(entityMap[id]) |
70 | | }) |
71 | | } |
72 | | |
73 | 1 | exports.fetchAll = function(entity, params) { |
74 | 3 | return new Promise(function(resolve, reject) { |
75 | 3 | var entityMap = exports.__getData(entity) |
76 | 3 | var results = _(entityMap) |
77 | | .filter(params) |
78 | | .toArray() |
79 | | .value() |
80 | | |
81 | 3 | resolve(results) |
82 | | }) |
83 | | } |
84 | | |
85 | 1 | exports.delete = function(entity, instance) { |
86 | 2 | return new Promise(function(resolve, reject) { |
87 | 2 | var entityMap = exports.__getData(entity) |
88 | 2 | if (!entityMap[instance.id]) { |
89 | 1 | reject('No entity with id=' + instance.id) |
90 | 1 | return |
91 | | } |
92 | | |
93 | 1 | delete entityMap[instance.id] |
94 | 1 | return resolve(instance) |
95 | | }) |
96 | | } |
97 | | |