-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory.js
More file actions
250 lines (212 loc) · 6.8 KB
/
Copy pathmemory.js
File metadata and controls
250 lines (212 loc) · 6.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
import { StorageInterface } from './interface.js';
import { randomUUID } from 'crypto';
import { normalizeCategory } from '../utils/category-utils.js';
import { getRideRoutes, normalizeRoutes } from '../utils/route-links.js';
const BASE62_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
export class MemoryStorage extends StorageInterface {
constructor() {
super();
this.rides = new Map();
this.users = new Map();
}
/**
* Convert a hex string to base62 string
* @param {string} hex
* @returns {string}
*/
hexToBase62(hex) {
let decimal = BigInt('0x' + hex);
let result = '';
while (decimal > 0) {
result = BASE62_CHARS[decimal % BigInt(62)] + result;
decimal = decimal / BigInt(62);
}
return result;
}
/**
* Generate a short unique ID (11 characters)
* Base62 encoding of first 16 characters of UUID (64 bits)
* @returns {string}
*/
generateShortId() {
const uuid = randomUUID().replace(/-/g, '');
const first16Chars = uuid.substring(0, 16); // Take first 64 bits
return this.hexToBase62(first16Chars).padStart(11, '0');
}
async createRide(ride) {
const id = this.generateShortId();
let rideData = { ...ride };
// Ensure messages array exists
if (!rideData.messages) {
rideData.messages = [];
}
const newRide = {
...rideData,
category: normalizeCategory(rideData.category),
id,
createdAt: new Date(),
participation: { joined: [], thinking: [], skipped: [] }
};
if (rideData.routes !== undefined) {
newRide.routes = normalizeRoutes(rideData.routes);
}
this.rides.set(id, newRide);
return this.mapRideToInterface(newRide);
}
async updateRide(rideId, updates) {
const ride = this.rides.get(rideId);
if (!ride) {
throw new Error('Ride not found');
}
// Preserve the messages array if it's not being updated
// This is critical to ensure message tracking works properly
if (!updates.messages && ride.messages) {
updates = {
...updates,
messages: ride.messages
};
}
// Set updatedAt to current time only if updatedBy is set
let updatesToApply = { ...updates };
if (updatesToApply.updatedBy) {
updatesToApply.updatedAt = new Date();
}
if (updatesToApply.category !== undefined) {
updatesToApply.category = normalizeCategory(updatesToApply.category);
}
if (updatesToApply.routes !== undefined) {
updatesToApply.routes = normalizeRoutes(updatesToApply.routes);
}
const updatedRide = {
...ride,
...updatesToApply
};
this.rides.set(rideId, updatedRide);
return this.mapRideToInterface(updatedRide);
}
async getRide(rideId) {
const ride = this.rides.get(rideId);
if (!ride) {
return null;
}
return this.mapRideToInterface(ride);
}
async getRidesByCreator(userId, skip, limit) {
const userRides = Array.from(this.rides.values())
.filter(ride => ride.createdBy === userId)
.sort((a, b) => b.date.getTime() - a.date.getTime());
return {
total: userRides.length,
rides: userRides.slice(skip, skip + limit).map(ride => this.mapRideToInterface(ride))
};
}
async deleteRide(rideId) {
const ride = this.rides.get(rideId);
if (!ride) {
return false;
}
this.rides.delete(rideId);
return true;
}
async setParticipation(rideId, state, participantProfile) {
const ride = this.rides.get(rideId);
if (!ride) {
throw new Error('Ride not found');
}
// Ensure participation structure exists
if (!ride.participation) {
ride.participation = { joined: [], thinking: [], skipped: [] };
}
// Remove user from all states first
ride.participation.joined = ride.participation.joined.filter(p => p.userId !== participantProfile.userId);
ride.participation.thinking = ride.participation.thinking.filter(p => p.userId !== participantProfile.userId);
ride.participation.skipped = ride.participation.skipped.filter(p => p.userId !== participantProfile.userId);
// Add user to the specified state
const participantData = {
userId: participantProfile.userId,
username: participantProfile.username,
firstName: participantProfile.firstName || '',
lastName: participantProfile.lastName || '',
createdAt: new Date()
};
ride.participation[state].push(participantData);
// Update the ride in storage
this.rides.set(rideId, ride);
return { ride: ride };
}
async getParticipation(rideId, userId) {
const ride = this.rides.get(rideId);
if (!ride || !ride.participation) {
return null;
}
if (ride.participation.joined.some(p => p.userId === userId)) return 'joined';
if (ride.participation.thinking.some(p => p.userId === userId)) return 'thinking';
if (ride.participation.skipped.some(p => p.userId === userId)) return 'skipped';
return null;
}
async getAllParticipants(rideId) {
const ride = this.rides.get(rideId);
if (!ride) {
throw new Error('Ride not found');
}
return ride.participation || { joined: [], thinking: [], skipped: [] };
}
async getRideByGroupId(groupId) {
for (const ride of this.rides.values()) {
if (ride.groupId === groupId) {
return this.mapRideToInterface(ride);
}
}
return null;
}
async getRideByStravaId(stravaId, createdBy) {
for (const ride of this.rides.values()) {
if (ride.metadata?.stravaId === stravaId && ride.createdBy === createdBy) {
return this.mapRideToInterface(ride);
}
}
return null;
}
async getUser(userId) {
const user = this.users.get(userId);
if (!user) {
return null;
}
return this.mapUserToInterface(user);
}
async upsertUser(userData) {
const existing = this.users.get(userData.userId);
const now = new Date();
const nextUser = {
userId: userData.userId,
username: userData.username ?? existing?.username ?? '',
firstName: userData.firstName ?? existing?.firstName ?? '',
lastName: userData.lastName ?? existing?.lastName ?? '',
settings: userData.settings !== undefined
? { ...(existing?.settings || {}), ...userData.settings }
: existing?.settings,
createdAt: existing?.createdAt ?? now,
updatedAt: now
};
this.users.set(userData.userId, nextUser);
return this.mapUserToInterface(nextUser);
}
/**
* @param {Object} ride
* @returns {import('./interface.js').Ride}
*/
mapRideToInterface(ride) {
return {
...ride,
routes: getRideRoutes(ride),
category: normalizeCategory(ride.category)
};
}
/**
* @param {Object} user
* @returns {import('./interface.js').UserEntity}
*/
mapUserToInterface(user) {
return { ...user };
}
}