backend-manager 2.0.18 → 2.0.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "backend-manager",
3
- "version": "2.0.18",
3
+ "version": "2.0.21",
4
4
  "description": "Quick tools for developing Firebase functions",
5
5
  "main": "src/manager/index.js",
6
6
  "bin": {
@@ -13,9 +13,11 @@ let sampleUser = {
13
13
  }
14
14
  },
15
15
  authenticated: false,
16
- _meta: {
17
- lastStatsReset: new Date(),
18
- lastUserFetch: new Date(),
16
+ _APIManager: {
17
+ meta: {
18
+ lastStatsReset: new Date(),
19
+ lastUserFetch: new Date(),
20
+ }
19
21
  }
20
22
  }
21
23
 
@@ -42,12 +44,13 @@ ApiManager.prototype.init = function (options) {
42
44
  options.plans = options.plans || {};
43
45
 
44
46
  // await self.Manager.libraries.admin.firestore
45
- // options.plans.basic = options.plans.basic || {requests: 93};
47
+ // options.plans.basic = options.plans.basic || {requests: 100};
46
48
 
47
49
  options.maxUsersStored = options.maxUsersStored || 10000;
48
50
  options.refetchInterval = options.refetchInterval || 60;
49
51
  options.resetInterval = options.resetInterval || (60 * 24);
50
52
  options.officialAPIKeys = options.officialAPIKeys || [];
53
+ options.whitelistedAPIKeys = options.whitelistedAPIKeys || [];
51
54
 
52
55
  await fetch('https://us-central1-itw-creative-works.cloudfunctions.net/getApp', {
53
56
  method: 'POST',
@@ -86,11 +89,20 @@ ApiManager.prototype.init = function (options) {
86
89
  });
87
90
  };
88
91
 
89
- ApiManager.prototype._createNewUser = function (authenticatedUser, planId, persistentData, isRefetch) {
92
+ ApiManager.prototype._createNewUser = function (authenticatedUser, planId, persistentData, isRefetch, apiKey) {
90
93
  const self = this;
94
+ const _APIManager_default = {
95
+ stats: {
96
+ requests: 0,
97
+ },
98
+ meta: {
99
+ lastStatsReset: new Date(),
100
+ lastUserFetch: new Date(),
101
+ },
102
+ providedAPIKey: apiKey,
103
+ }
91
104
  persistentData = persistentData || {};
92
- persistentData._meta = persistentData._meta || {};
93
- persistentData._stats = persistentData._stats || {};
105
+ persistentData._APIManager = persistentData._APIManager || merge({}, _APIManager_default);
94
106
 
95
107
  let newUser = {
96
108
  api: get(authenticatedUser, 'api', {}),
@@ -98,35 +110,43 @@ ApiManager.prototype._createNewUser = function (authenticatedUser, planId, persi
98
110
  plan: {
99
111
  id: planId,
100
112
  limits: {
101
- requests: get(authenticatedUser, 'plan.limits.requests', get(self.options, `plans.${planId}.limits.requests`, 93)),
102
113
  }
103
114
  },
104
115
  authenticated: authenticatedUser.authenticated,
105
116
  ip: authenticatedUser.ip,
106
117
  country: authenticatedUser.country,
107
- _stats: {
108
- requests: 0,
109
- },
110
- _meta: {
111
- lastStatsReset: new Date(),
112
- lastUserFetch: new Date(),
113
- }
118
+ _APIManager: merge({}, _APIManager_default),
114
119
  }
115
- // console.log('-----MIN', moment().diff(moment(persistentData._meta.lastStatsReset), 'minutes', true), self.options.resetInterval);
116
- if (moment().diff(moment(persistentData._meta.lastStatsReset), 'minutes', true) < self.options.resetInterval) {
117
- newUser._meta.lastStatsReset = persistentData._meta.lastStatsReset || newUser._meta.lastStatsReset;
118
- newUser._meta.lastUserFetch = persistentData._meta.lastUserFetch || newUser._meta.lastUserFetch;
119
- Object.keys(persistentData._stats)
120
+
121
+ // Setup newUser
122
+ const currentPlan = get(self.options, `plans.${planId}.limits`, {})
123
+ Object.keys(currentPlan)
124
+ .forEach((id, i) => {
125
+ // console.log('----id', id);
126
+ // console.log('======currentPlan[id]', currentPlan[id]);
127
+ newUser.plan.limits[id] = get(authenticatedUser, `plan.limits.${id}`, currentPlan[id])
128
+ // const product = data.products[id]
129
+ // options.plans[product.planId] = {}
130
+ // options.plans[product.planId].limits = product.limits || {};
131
+ });
132
+
133
+
134
+
135
+ // console.log('-----MIN', moment().diff(moment(persistentData._APIManager.meta.lastStatsReset), 'minutes', true), self.options.resetInterval);
136
+ if (moment().diff(moment(persistentData._APIManager.meta.lastStatsReset), 'minutes', true) < self.options.resetInterval) {
137
+ newUser._APIManager.meta.lastStatsReset = persistentData._APIManager.meta.lastStatsReset || newUser._APIManager.meta.lastStatsReset;
138
+ newUser._APIManager.meta.lastUserFetch = persistentData._APIManager.meta.lastUserFetch || newUser._APIManager.meta.lastUserFetch;
139
+ Object.keys(persistentData._APIManager.stats)
120
140
  .forEach((key, i) => {
121
- newUser._stats[key] = persistentData._stats[key];
141
+ newUser._APIManager.stats[key] = persistentData._APIManager.stats[key];
122
142
  });
123
143
  } else {
124
144
  // console.log('---RESSET INTERVAL REACHED');
125
- newUser._meta.lastUserFetch = persistentData._meta.lastUserFetch;
145
+ newUser._APIManager.meta.lastUserFetch = persistentData._APIManager.meta.lastUserFetch;
126
146
  }
127
147
 
128
148
  if (isRefetch) {
129
- newUser._meta.lastUserFetch = new Date();
149
+ newUser._APIManager.meta.lastUserFetch = new Date();
130
150
  }
131
151
 
132
152
  return newUser;
@@ -143,14 +163,14 @@ ApiManager.prototype.getUser = async function (assistant) {
143
163
  if (apiKey) {
144
164
  newUser = self.userList.filter(user => user.api.privateKey === apiKey);
145
165
  if (newUser[0]) {
146
- if (newUser.length > 1 || moment().diff(moment(newUser[0]._meta.lastUserFetch), 'minutes', true) > self.options.refetchInterval) {
166
+ if (newUser.length > 1 || moment().diff(moment(newUser[0]._APIManager.meta.lastUserFetch), 'minutes', true) > self.options.refetchInterval) {
147
167
  // console.log('----REFETCHING');
148
- persistentData = {set: true, _stats: merge({}, newUser[0]._stats), _meta: merge({}, newUser[0]._meta)};
168
+ persistentData = {set: true, _APIManager: merge({}, newUser[0]._APIManager)};
149
169
 
150
170
  self.userList = self.userList.filter(user => user.api.privateKey !== apiKey)
151
171
  newUser = null;
152
172
  } else {
153
- persistentData = {set: true, _stats: merge({}, newUser[0]._stats), _meta: merge({}, newUser[0]._meta)};
173
+ persistentData = {set: true, _APIManager: merge({}, newUser[0]._APIManager)};
154
174
 
155
175
  newUser = newUser[0];
156
176
  }
@@ -176,20 +196,20 @@ ApiManager.prototype.getUser = async function (assistant) {
176
196
  let existingUser = self.userList.find(user => user.auth.uid === workingUID);
177
197
  if (existingUser) {
178
198
  // console.log('---actually does exist so setting');
179
- // console.log('----1111 MIN lastUserFetch', moment().diff(moment(existingUser._meta.lastUserFetch), 'minutes', true), self.options.refetchInterval);
180
- persistentData = !persistentData.set ? {set: true, _stats: merge({}, existingUser._stats), _meta: merge({}, existingUser._meta)} : persistentData;
199
+ // console.log('----1111 MIN lastUserFetch', moment().diff(moment(existingUser._APIManager.meta.lastUserFetch), 'minutes', true), self.options.refetchInterval);
200
+ persistentData = !persistentData.set ? {set: true, _APIManager: merge({}, existingUser._APIManager)} : persistentData;
181
201
  // console.log('----persistentData 2', persistentData);
182
- if (moment().diff(moment(existingUser._meta.lastUserFetch), 'minutes', true) > self.options.refetchInterval) {
202
+ if (moment().diff(moment(existingUser._APIManager.meta.lastUserFetch), 'minutes', true) > self.options.refetchInterval) {
183
203
  // console.log('----REFETCHING');
184
204
  self.userList = self.userList.filter(user => user.auth.uid !== workingUID)
185
- existingUser = self._createNewUser(authenticatedUser, planId, persistentData, true);
205
+ existingUser = self._createNewUser(authenticatedUser, planId, persistentData, true, apiKey);
186
206
  existingUser.auth.uid = workingUID;
187
207
  self.userList = self.userList.concat(existingUser);
188
208
  }
189
209
  newUser = existingUser
190
210
  } else {
191
211
  // console.log('---actually doesnt exist making new user');
192
- newUser = self._createNewUser(authenticatedUser, planId, persistentData)
212
+ newUser = self._createNewUser(authenticatedUser, planId, persistentData, false, apiKey)
193
213
  newUser.auth.uid = workingUID;
194
214
  self.userList = self.userList.concat(newUser);
195
215
  }
@@ -201,27 +221,56 @@ ApiManager.prototype.getUser = async function (assistant) {
201
221
 
202
222
  };
203
223
 
204
- ApiManager.prototype.getUserStat = function (user, stat, def) {
224
+ function _getUserStat(self, user, stat, def) {
225
+ const isWhitelistedAPIKey = self.options.whitelistedAPIKeys.includes(
226
+ get(user, `api.privateKey`, get(user, `_APIManager.providedAPIKey`))
227
+ );
228
+ // console.log('----user', user);
229
+ // console.log('----isWhitelistedAPIKey', isWhitelistedAPIKey);
230
+ return {
231
+ current: !isWhitelistedAPIKey ? get(user, `_APIManager.stats.${stat}`, typeof def !== 'undefined' ? def : 0) : 0,
232
+ limit: !isWhitelistedAPIKey ? get(user, `plan.limits.${stat}`, typeof def !== 'undefined' ? def : 0) : Infinity,
233
+ }
234
+ }
235
+
236
+ ApiManager.prototype.isUserOverStat = function (user, stat, def, frame) {
205
237
  const self = this;
206
238
  if (!user || !stat) {
207
239
  throw new Error('<user> and <stat> required')
208
240
  }
209
- return {
210
- current: get(user, `_stats.${stat}`, def || 0),
211
- limit: get(user, `plan.limits.${stat}`, def || 0),
241
+ const result = self.getUserStat(user, stat, def);
242
+ frame = frame || 'daily';
243
+ let limit = result.limit;
244
+ // console.log('---result', result);
245
+ // console.log('---typeof result.current', typeof result.current);
246
+ // console.log('----limit', limit);
247
+ if (typeof result.limit === 'number') {
248
+ if (frame === 'daily') {
249
+ limit = Math.floor(result.limit / 31);
250
+ }
251
+ // console.log('----limit', limit);
252
+ // console.log('-----result.current < limit', result.current < limit);
253
+ return limit >= result.current;
212
254
  }
255
+
256
+ return false;
213
257
  }
214
258
 
215
- ApiManager.prototype.incrementUserStat = function (user, stat, amount) {
259
+ ApiManager.prototype.getUserStat = function (user, stat, def, ) {
216
260
  const self = this;
217
261
  if (!user || !stat) {
218
262
  throw new Error('<user> and <stat> required')
219
263
  }
220
- set(user, `_stats.${stat}`, get(user, `_stats.${stat}`, 0) + amount)
221
- return {
222
- current: get(user, `_stats.${stat}`, 0),
223
- limit: get(user, `plan.limits.${stat}`, 0),
264
+ return _getUserStat(self, user, stat, def);
265
+ }
266
+
267
+ ApiManager.prototype.incrementUserStat = function (user, stat, amount) {
268
+ const self = this;
269
+ if (!user || !stat) {
270
+ throw new Error('<user> and <stat> required')
224
271
  }
272
+ set(user, `_APIManager.stats.${stat}`, get(user, `_APIManager.stats.${stat}`, 0) + amount)
273
+ return _getUserStat(self, user, stat, 0);
225
274
  }
226
275
 
227
276
 
@@ -11,7 +11,7 @@ function User(settings, options) {
11
11
  options = options || {};
12
12
  let now = powertools.timestamp(new Date(), {output: 'string'});
13
13
  let nowUNIX = powertools.timestamp(now, {output: 'unix'});
14
- let oldDate = powertools.timestamp(new Date('1999/01/01'), {output: 'string'})
14
+ let oldDate = powertools.timestamp(new Date(0), {output: 'string'})
15
15
  let oldDateUNIX = powertools.timestamp(oldDate, {output: 'unix'});
16
16
 
17
17
  const useDefaults = typeof options.defaults === 'undefined' ? true : options.defaults;
@@ -34,7 +34,7 @@ function User(settings, options) {
34
34
  timestampUNIX: _.get(settings, 'plan.expires.timestampUNIX', useDefaults ? oldDateUNIX : null),
35
35
  },
36
36
  limits: {
37
- devices: _.get(settings, 'plan.limits.devices', useDefaults ? 1 : null),
37
+ // devices: _.get(settings, 'plan.limits.devices', null),
38
38
  },
39
39
  payment: {
40
40
  processor: _.get(settings, 'plan.payment.processor', null), // paypal | stripe | chargebee, etc