propro-utils 1.5.65 → 1.5.67

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.
@@ -1,6 +1,5 @@
1
1
  require('dotenv').config();
2
2
  const axios = require('axios');
3
- const mongoose = require('mongoose');
4
3
  const { getOrSetCache } = require('../utils/redis');
5
4
  const { v4: uuidv4 } = require('uuid');
6
5
  const ServiceManager = require('../utils/serviceManager');
@@ -100,272 +99,80 @@ async function createDefaultFolders(folderSchema, accountId) {
100
99
  }
101
100
  }
102
101
 
103
- const debugLog = (area, message, data = null) => {
104
- const timestamp = new Date().toISOString();
105
- console.log(
106
- `[${timestamp}] [${area}] ${message}`,
107
- data ? JSON.stringify(data, null, 2) : ''
108
- );
109
- };
110
-
111
- const DEFAULT_THEME = {
112
- canvasBackground: '#000000',
113
- defaultItemWidth: 200,
114
- defaultColor: '#ffffff',
115
- fontSize: '16px',
116
- name: 'Default Theme',
117
- };
118
-
119
- const timeoutPromise = (promise, timeout, name) => {
120
- return Promise.race([
121
- promise,
122
- new Promise((_, reject) =>
123
- setTimeout(
124
- () =>
125
- reject(new Error(`${name} operation timed out after ${timeout}ms`)),
126
- timeout
127
- )
128
- ),
129
- ]);
130
- };
131
-
102
+ /**
103
+ * Checks if a user exists based on the given account ID.
104
+ * If the user does not exist, creates a new user with the given account ID.
105
+ * If the user exists but doesn't have global styles, creates them.
106
+ *
107
+ * @param {string} accountId - The account ID of the user to check/create.
108
+ * @returns {Promise<Object>} A promise that resolves to the user object.
109
+ * @throws {Error} If there's an issue with database operations.
110
+ */
132
111
  const checkIfUserExists = async accountId => {
133
- const startTime = Date.now();
134
112
  try {
135
- if (!accountId) {
136
- throw new Error('AccountId is required');
137
- }
138
- debugLog('init', `Starting user check for accountId: ${accountId}`);
139
-
140
- // Initialize services with timeout and individual error handling
141
- let services;
142
- try {
143
- debugLog('services', 'Initializing services...');
144
- services = await timeoutPromise(
145
- Promise.all([
146
- ServiceManager.getService('UserSchema').catch(e => {
147
- throw new Error(`Failed to get UserSchema: ${e.message}`);
148
- }),
149
- ServiceManager.getService('UserStyleSchema').catch(e => {
150
- throw new Error(`Failed to get UserStyleSchema: ${e.message}`);
151
- }),
152
- ServiceManager.getService('FolderSchema').catch(e => {
153
- throw new Error(`Failed to get FolderSchema: ${e.message}`);
154
- }),
155
- ServiceManager.getService('Theme').catch(e => {
156
- throw new Error(`Failed to get Theme: ${e.message}`);
157
- }),
158
- ]),
159
- 5000,
160
- 'Service initialization'
161
- );
162
-
163
- debugLog('services', 'Services initialized successfully', {
164
- serviceCount: services.length,
165
- initTime: Date.now() - startTime,
166
- });
167
- } catch (error) {
168
- debugLog('error', 'Service initialization failed', {
169
- error: error.message,
170
- });
171
- throw error;
172
- }
113
+ const userSchema = await ServiceManager.getService('UserSchema');
114
+ const userStyleSchema = await ServiceManager.getService('UserStyleSchema');
115
+ const folderSchema = await ServiceManager.getService('FolderSchema');
173
116
 
174
- const [userSchema, userStyleSchema, folderSchema, Theme] = services;
175
-
176
- // Find user and theme with timeout
177
- let user, existingTheme;
178
- try {
179
- debugLog('query', 'Starting user and theme queries');
180
- [user, existingTheme] = await timeoutPromise(
181
- Promise.all([
182
- userSchema
183
- .findOne({ accountId })
184
- .populate('userGlobalStyles')
185
- .exec()
186
- .catch(e => {
187
- throw new Error(`Failed to find user: ${e.message}`);
188
- }),
189
- Theme.findOne({
190
- name: 'Default Theme',
191
- accountId,
192
- })
193
- .exec()
194
- .catch(e => {
195
- throw new Error(`Failed to find theme: ${e.message}`);
196
- }),
197
- ]),
198
- 5000,
199
- 'Initial queries'
200
- );
117
+ let user = await userSchema
118
+ .findOne({ accountId })
119
+ .populate('userGlobalStyles');
201
120
 
202
- debugLog('query', 'Queries completed', {
203
- userFound: !!user,
204
- themeFound: !!existingTheme,
205
- queryTime: Date.now() - startTime,
206
- });
207
- } catch (error) {
208
- debugLog('error', 'Query operations failed', { error: error.message });
209
- throw error;
210
- }
211
-
212
- // Create or use existing theme
213
- let defaultTheme;
214
- try {
215
- if (!existingTheme) {
216
- debugLog('theme', 'Creating new theme');
217
- defaultTheme = await timeoutPromise(
218
- Theme.create({
219
- ...DEFAULT_THEME,
220
- id: uuidv4(),
221
- accountId,
222
- }),
223
- 5000,
224
- 'Theme creation'
121
+ if (user) {
122
+ if (!user.userGlobalStyles) {
123
+ user.userGlobalStyles = await createUserGlobalStyles(
124
+ userStyleSchema,
125
+ accountId
225
126
  );
226
- debugLog('theme', 'New theme created', { themeId: defaultTheme._id });
227
- } else {
228
- defaultTheme = existingTheme;
229
- debugLog('theme', 'Using existing theme', {
230
- themeId: defaultTheme._id,
231
- });
127
+ await user.save();
128
+ } else if (user.userGlobalStyles.styleShortcuts.length === 0) {
129
+ user.userGlobalStyles.styleShortcuts = defaultUserGlobalStyleShortcuts;
130
+ await user.userGlobalStyles.save();
232
131
  }
233
- } catch (error) {
234
- debugLog('error', 'Theme operation failed', { error: error.message });
235
- throw error;
236
- }
132
+ // Check if user has any folders
133
+ const userFolders = await folderSchema.find({ user_id: user.id });
134
+ const defaultFolderNames = defaultFolders.map(folder => folder.name);
135
+ const userFolderNames = userFolders.map(folder => folder.name);
237
136
 
238
- if (user) {
239
- debugLog('user', 'Processing existing user');
240
- const updates = [];
241
-
242
- try {
243
- // Theme update if needed
244
- if (!user.theme) {
245
- debugLog('update', 'Adding theme to user');
246
- user.theme = defaultTheme._id;
247
- updates.push('theme');
248
- }
249
-
250
- // Global styles update if needed
251
- if (!user.userGlobalStyles) {
252
- debugLog('update', 'Creating user global styles');
253
- user.userGlobalStyles = await timeoutPromise(
254
- createUserGlobalStyles(userStyleSchema, accountId),
255
- 5000,
256
- 'Global styles creation'
257
- );
258
- updates.push('userGlobalStyles');
259
- } else if (user.userGlobalStyles.styleShortcuts.length === 0) {
260
- debugLog('update', 'Updating empty style shortcuts');
261
- user.userGlobalStyles.styleShortcuts =
262
- defaultUserGlobalStyleShortcuts;
263
- await timeoutPromise(
264
- user.userGlobalStyles.save(),
265
- 5000,
266
- 'Style shortcuts update'
267
- );
268
- }
269
-
270
- // Folder checks
271
- debugLog('folders', 'Checking user folders');
272
- const userFolders = await timeoutPromise(
273
- folderSchema.find({ user_id: user.id }, { name: 1 }),
274
- 5000,
275
- 'Folder query'
276
- );
137
+ const foldersToCreate = defaultFolders.filter(
138
+ folder => !userFolderNames.includes(folder.name)
139
+ );
277
140
 
278
- const userFolderNames = new Set(userFolders.map(f => f.name));
279
- const foldersToCreate = defaultFolders.filter(
280
- f => !userFolderNames.has(f.name)
141
+ if (foldersToCreate.length > 0) {
142
+ await Promise.all(
143
+ foldersToCreate.map(folder =>
144
+ folderSchema.create({
145
+ ...folder,
146
+ user_id: user.id,
147
+ })
148
+ )
281
149
  );
282
-
283
- if (foldersToCreate.length > 0) {
284
- debugLog('folders', 'Creating missing folders', {
285
- count: foldersToCreate.length,
286
- });
287
- await timeoutPromise(
288
- Promise.all(
289
- foldersToCreate.map(folder =>
290
- folderSchema.create({
291
- ...folder,
292
- user_id: user.id,
293
- })
294
- )
295
- ),
296
- 5000,
297
- 'Folder creation'
298
- );
299
- }
300
-
301
- // Save user if there were updates
302
- if (updates.length > 0) {
303
- debugLog('update', 'Saving user updates', { updates });
304
- await timeoutPromise(user.save(), 5000, 'User save');
305
- }
306
- } catch (error) {
307
- debugLog('error', 'User update operations failed', {
308
- error: error.message,
309
- });
310
- throw error;
311
150
  }
312
151
 
313
- debugLog('complete', 'Existing user processed', {
314
- userId: user.id,
315
- totalTime: Date.now() - startTime,
316
- });
317
152
  return user;
318
153
  }
319
154
 
320
- // Create new user
321
- try {
322
- debugLog('create', 'Creating new user');
323
- const userGlobalStyles = await timeoutPromise(
324
- createUserGlobalStyles(userStyleSchema, accountId),
325
- 5000,
326
- 'Global styles creation'
327
- );
328
-
329
- const newUserId = uuidv4();
155
+ const userGlobalStyles = await createUserGlobalStyles(
156
+ userStyleSchema,
157
+ accountId
158
+ );
330
159
 
331
- const [newUser, newFolders] = await timeoutPromise(
332
- Promise.all([
333
- userSchema.create({
334
- accountId,
335
- id: newUserId,
336
- verified: false,
337
- userGlobalStyles: userGlobalStyles._id,
338
- theme: defaultTheme._id,
339
- }),
340
- createDefaultFolders(folderSchema, newUserId),
341
- ]),
342
- 5000,
343
- 'User and folders creation'
344
- );
160
+ user = await userSchema.create({
161
+ accountId,
162
+ id: uuidv4(),
163
+ verified: false,
164
+ userGlobalStyles: userGlobalStyles._id,
165
+ });
345
166
 
346
- newUser.folders = newFolders.map(folder => folder._id);
347
- await timeoutPromise(newUser.save(), 5000, 'New user save');
167
+ const folders = await createDefaultFolders(folderSchema, user.id);
168
+ console.log('Folders created:', folders);
169
+ user.folders = folders.map(folder => folder._id);
170
+ await user.save();
348
171
 
349
- debugLog('complete', 'New user created', {
350
- userId: newUser.id,
351
- totalTime: Date.now() - startTime,
352
- });
353
- return newUser;
354
- } catch (error) {
355
- debugLog('error', 'User creation failed', { error: error.message });
356
- throw error;
357
- }
172
+ return user;
358
173
  } catch (error) {
359
- const totalTime = Date.now() - startTime;
360
- debugLog('error', 'Operation failed', {
361
- error: error.message,
362
- stack: error.stack,
363
- totalTime,
364
- });
365
-
366
- throw new Error(`Failed to get or create user: ${error.message}`, {
367
- cause: error,
368
- });
174
+ console.error('Error in checkIfUserExists:', error);
175
+ throw new Error('Failed to get or create user');
369
176
  }
370
177
  };
371
178
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "propro-utils",
3
- "version": "1.5.65",
3
+ "version": "1.5.67",
4
4
  "description": "Auth middleware for propro-auth",
5
5
  "main": "src/index.js",
6
6
  "scripts": {