backend-manager 2.0.16 → 2.0.19

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.16",
3
+ "version": "2.0.19",
4
4
  "description": "Quick tools for developing Firebase functions",
5
5
  "main": "src/manager/index.js",
6
6
  "bin": {
@@ -31,7 +31,7 @@
31
31
  "@google-cloud/storage": "^5.19.4",
32
32
  "@sendgrid/mail": "^7.6.2",
33
33
  "@sentry/node": "^6.19.7",
34
- "backend-assistant": "^0.0.62",
34
+ "backend-assistant": "^0.0.63",
35
35
  "busboy": "^1.6.0",
36
36
  "chalk": "^4.1.2",
37
37
  "cors": "^2.8.5",
@@ -64,4 +64,4 @@
64
64
  "src/",
65
65
  "templates/"
66
66
  ]
67
- }
67
+ }
@@ -1,4 +1,5 @@
1
1
  const moment = require('moment');
2
+ const fetch = require('node-fetch');
2
3
  const uuidv5 = require('uuid').v5;
3
4
  const { get, set, merge } = require('lodash');
4
5
 
@@ -18,10 +19,12 @@ let sampleUser = {
18
19
  }
19
20
  }
20
21
 
21
- function ApiManager() {
22
+ function ApiManager(m) {
22
23
  const self = this;
24
+ self.Manager = m;
23
25
  self.options = {
24
- planData: {},
26
+ appId: '',
27
+ plans: {},
25
28
  maxUsersStored: 10000,
26
29
  refetchInterval: 60,
27
30
  resetInterval: 60 * 24,
@@ -33,23 +36,58 @@ function ApiManager() {
33
36
 
34
37
  ApiManager.prototype.init = function (options) {
35
38
  const self = this;
36
- options = options || {};
37
- options.planData = options.planData || {};
38
- options.planData.basic = options.planData.basic || {requests: 93};
39
+ return new Promise(async function(resolve, reject) {
40
+ options = options || {};
41
+ options.app = options.app || '';
42
+ options.plans = options.plans || {};
39
43
 
40
- options.maxUsersStored = options.maxUsersStored || 10000;
41
- options.refetchInterval = options.refetchInterval || 60;
42
- options.resetInterval = options.resetInterval || (60 * 24);
43
- options.officialAPIKeys = options.officialAPIKeys || [];
44
+ // await self.Manager.libraries.admin.firestore
45
+ // options.plans.basic = options.plans.basic || {requests: 93};
44
46
 
45
- self.options = options;
47
+ options.maxUsersStored = options.maxUsersStored || 10000;
48
+ options.refetchInterval = options.refetchInterval || 60;
49
+ options.resetInterval = options.resetInterval || (60 * 24);
50
+ options.officialAPIKeys = options.officialAPIKeys || [];
51
+ options.whitelistedAPIKeys = options.whitelistedAPIKeys || [];
46
52
 
47
- self.initialized = true;
53
+ await fetch('https://us-central1-itw-creative-works.cloudfunctions.net/getApp', {
54
+ method: 'POST',
55
+ headers: { 'Content-Type': 'application/json' },
56
+ body: JSON.stringify({
57
+ id: options.app,
58
+ }),
59
+ })
60
+ .then(res => {
61
+ res.text()
62
+ .then(text => {
63
+ if (res.ok) {
64
+ const data = JSON.parse(text);
48
65
 
49
- return self;
66
+ options.plans = {};
67
+
68
+ Object.keys(data.products)
69
+ .forEach((id, i) => {
70
+ const product = data.products[id]
71
+ options.plans[product.planId] = {}
72
+ options.plans[product.planId].limits = product.limits || {};
73
+ });
74
+
75
+ self.options = options;
76
+ self.initialized = true;
77
+
78
+ return resolve(self);
79
+ } else {
80
+ throw new Error(text || res.statusText || 'Unknown error.')
81
+ }
82
+ })
83
+ })
84
+ .catch(e => {
85
+ return reject(e)
86
+ })
87
+ });
50
88
  };
51
89
 
52
- ApiManager.prototype._createNewUser = function (authenticatedUser, planId, persistentData, isRefetch) {
90
+ ApiManager.prototype._createNewUser = function (authenticatedUser, planId, persistentData, isRefetch, apiKey) {
53
91
  const self = this;
54
92
  persistentData = persistentData || {};
55
93
  persistentData._meta = persistentData._meta || {};
@@ -61,7 +99,7 @@ ApiManager.prototype._createNewUser = function (authenticatedUser, planId, persi
61
99
  plan: {
62
100
  id: planId,
63
101
  limits: {
64
- requests: get(authenticatedUser, 'plan.limits.requests', get(self.options, `planData.${planId}.limits.requests`, 93)),
102
+ requests: get(authenticatedUser, 'plan.limits.requests', get(self.options, `plans.${planId}.limits.requests`, 93)),
65
103
  }
66
104
  },
67
105
  authenticated: authenticatedUser.authenticated,
@@ -73,7 +111,8 @@ ApiManager.prototype._createNewUser = function (authenticatedUser, planId, persi
73
111
  _meta: {
74
112
  lastStatsReset: new Date(),
75
113
  lastUserFetch: new Date(),
76
- }
114
+ },
115
+ _providedAPIKey: apiKey,
77
116
  }
78
117
  // console.log('-----MIN', moment().diff(moment(persistentData._meta.lastStatsReset), 'minutes', true), self.options.resetInterval);
79
118
  if (moment().diff(moment(persistentData._meta.lastStatsReset), 'minutes', true) < self.options.resetInterval) {
@@ -145,14 +184,14 @@ ApiManager.prototype.getUser = async function (assistant) {
145
184
  if (moment().diff(moment(existingUser._meta.lastUserFetch), 'minutes', true) > self.options.refetchInterval) {
146
185
  // console.log('----REFETCHING');
147
186
  self.userList = self.userList.filter(user => user.auth.uid !== workingUID)
148
- existingUser = self._createNewUser(authenticatedUser, planId, persistentData, true);
187
+ existingUser = self._createNewUser(authenticatedUser, planId, persistentData, true, apiKey);
149
188
  existingUser.auth.uid = workingUID;
150
189
  self.userList = self.userList.concat(existingUser);
151
190
  }
152
191
  newUser = existingUser
153
192
  } else {
154
193
  // console.log('---actually doesnt exist making new user');
155
- newUser = self._createNewUser(authenticatedUser, planId, persistentData)
194
+ newUser = self._createNewUser(authenticatedUser, planId, persistentData, false, apiKey)
156
195
  newUser.auth.uid = workingUID;
157
196
  self.userList = self.userList.concat(newUser);
158
197
  }
@@ -164,15 +203,24 @@ ApiManager.prototype.getUser = async function (assistant) {
164
203
 
165
204
  };
166
205
 
206
+ function _getUserStat(self, user, stat, def) {
207
+ const isWhitelistedAPIKey = self.options.whitelistedAPIKeys.includes(
208
+ get(user, `api.privateKey`, get(user, `_providedAPIKey`))
209
+ );
210
+ // console.log('----user', user);
211
+ // console.log('----isWhitelistedAPIKey', isWhitelistedAPIKey);
212
+ return {
213
+ current: !isWhitelistedAPIKey ? get(user, `_stats.${stat}`, typeof def !== 'undefined' ? def : 0) : 0,
214
+ limit: !isWhitelistedAPIKey ? get(user, `plan.limits.${stat}`, typeof def !== 'undefined' ? def : 0) : Infinity,
215
+ }
216
+ }
217
+
167
218
  ApiManager.prototype.getUserStat = function (user, stat, def) {
168
219
  const self = this;
169
220
  if (!user || !stat) {
170
221
  throw new Error('<user> and <stat> required')
171
222
  }
172
- return {
173
- current: get(user, `_stats.${stat}`, def || 0),
174
- limit: get(user, `plan.limits.${stat}`, def || 0),
175
- }
223
+ return _getUserStat(self, user, stat, def);
176
224
  }
177
225
 
178
226
  ApiManager.prototype.incrementUserStat = function (user, stat, amount) {
@@ -181,10 +229,7 @@ ApiManager.prototype.incrementUserStat = function (user, stat, amount) {
181
229
  throw new Error('<user> and <stat> required')
182
230
  }
183
231
  set(user, `_stats.${stat}`, get(user, `_stats.${stat}`, 0) + amount)
184
- return {
185
- current: get(user, `_stats.${stat}`, 0),
186
- limit: get(user, `plan.limits.${stat}`, 0),
187
- }
232
+ return _getUserStat(self, user, stat, 0);
188
233
  }
189
234
 
190
235