Skip to content

Commit c589565

Browse files
committed
feat: get session switching working
Signed-off-by: Alexander Alemayhu <alexander@alemayhu.com>
1 parent 0757980 commit c589565

File tree

3 files changed

+236
-106
lines changed

3 files changed

+236
-106
lines changed

src/data_layer/SessionRepository.ts

Lines changed: 49 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -31,50 +31,70 @@ export default class SessionRepository {
3131
});
3232
}
3333

34-
getSession(userId: string | number) {
34+
async getSession(userId: string | number) {
3535
console.log('[SESSION] Getting session for user:', userId);
36-
return this.database('sessions')
36+
const session = await this.database('sessions')
3737
.where({ userId })
38-
.first()
39-
.then((session) => {
40-
if (!session) return null;
41-
try {
42-
const parsedData =
43-
typeof session.data === 'string'
44-
? JSON.parse(session.data)
45-
: session.data;
46-
return {
47-
...session,
48-
data: parsedData,
49-
};
50-
} catch (error) {
51-
console.warn('[SESSION] Failed to parse session data:', error);
52-
return {
53-
...session,
54-
data: session.data,
55-
};
56-
}
57-
});
38+
.orderBy('created_at', 'desc')
39+
.first();
40+
41+
if (!session) return null;
42+
try {
43+
const parsedData =
44+
typeof session.data === 'string'
45+
? JSON.parse(session.data)
46+
: session.data;
47+
return {
48+
...session,
49+
data: parsedData,
50+
};
51+
} catch (error) {
52+
console.warn('[SESSION] Failed to parse session data:', error);
53+
return {
54+
...session,
55+
data: session.data,
56+
};
57+
}
5858
}
5959

60-
async updateSession(userId: string | number, data: any) {
61-
console.log('[SESSION] Updating session for user:', userId);
62-
const old = await this.getSession(userId);
60+
async updateSession(userId: string | number, data: any, sessionId: string) {
61+
console.log(
62+
'[SESSION] Updating session for user:',
63+
userId,
64+
'session:',
65+
sessionId
66+
);
67+
const query = this.database('sessions').where({ userId });
68+
69+
if (sessionId) {
70+
query.where({ id: sessionId });
71+
} else {
72+
query.orderBy('created_at', 'desc');
73+
}
74+
75+
const old = await query.first();
76+
if (!old) return null;
77+
6378
return this.database('sessions')
64-
.where({ userId })
79+
.where({ id: old.id })
6580
.update({
6681
data: JSON.stringify({
67-
...old?.data,
82+
...old.data,
6883
...data,
6984
}),
7085
});
7186
}
7287

73-
deleteSession(userId: string | number) {
74-
console.log('[SESSION] Deleting session for user:', userId);
88+
deleteAllSessions(userId: string | number) {
89+
console.log('[SESSION] Deleting all sessions for user:', userId);
7590
return this.database('sessions').where({ userId }).del();
7691
}
7792

93+
deleteSessionById(sessionId: string, userId: string | number) {
94+
console.log('[SESSION] Deleting session:', sessionId, 'for user:', userId);
95+
return this.database('sessions').where({ id: sessionId, userId }).del();
96+
}
97+
7898
async getUserSessions(userId: string): Promise<Session[]> {
7999
const sessions = await this.database('sessions')
80100
.where({ userId })

src/routes/ki/KiRouter.ts

Lines changed: 68 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -237,22 +237,41 @@ const KiRouter = () => {
237237
res.redirect('/login?redirect=/ki');
238238
return false;
239239
}
240-
let s = await sessionRepository.getSession(user.owner);
241-
if (!s) {
240+
241+
// Create new session if requested or get existing one
242+
const isNewSession = req.query.new === 'true';
243+
let s;
244+
245+
if (isNewSession) {
242246
const w = new Workspace(true, 'fs');
243247
await sessionRepository.createSession(user.owner, {
244248
uploadedFiles: [],
245249
deckInfo: [],
246250
workspace: w,
247251
});
248252
s = await sessionRepository.getSession(user.owner);
253+
} else {
254+
s = await sessionRepository.getSession(user.owner);
255+
if (!s) {
256+
const w = new Workspace(true, 'fs');
257+
await sessionRepository.createSession(user.owner, {
258+
uploadedFiles: [],
259+
deckInfo: [],
260+
workspace: w,
261+
});
262+
s = await sessionRepository.getSession(user.owner);
263+
}
249264
}
250265

251266
if (!s.data?.workspace?.location) {
252267
s.data.workspace = new Workspace(true, 'fs');
253-
await sessionRepository.updateSession(user.owner, {
254-
workspace: s.data.workspace,
255-
});
268+
await sessionRepository.updateSession(
269+
user.owner,
270+
{
271+
workspace: s.data.workspace,
272+
},
273+
s.id
274+
);
256275
}
257276

258277
const exists = oldFs.existsSync(s.data.workspace.location);
@@ -447,9 +466,13 @@ const KiRouter = () => {
447466
}
448467

449468
// Update session with uploaded files (ONLY update files here)
450-
await sessionRepository.updateSession(userId, {
451-
uploadedFiles: userSession.data.uploadedFiles,
452-
});
469+
await sessionRepository.updateSession(
470+
userId,
471+
{
472+
uploadedFiles: userSession.data.uploadedFiles,
473+
},
474+
userSession.id
475+
);
453476
} catch (error) {
454477
console.error('[UPLOAD] Error during upload process:', error);
455478
res.status(500).json({
@@ -490,9 +513,13 @@ const KiRouter = () => {
490513
userSession.data.uploadedFiles = userSession.data.uploadedFiles.filter(
491514
(f: { id: string }) => f.id !== fileId
492515
);
493-
await sessionRepository.updateSession(user.owner, {
494-
uploadedFiles: userSession.data.uploadedFiles,
495-
});
516+
await sessionRepository.updateSession(
517+
user.owner,
518+
{
519+
uploadedFiles: userSession.data.uploadedFiles,
520+
},
521+
userSession.id
522+
);
496523
}
497524
res.send('');
498525
} catch (error) {
@@ -980,16 +1007,24 @@ const KiRouter = () => {
9801007
userSession.data.deckInfo = transformToDecks(userSession.data.deckInfo);
9811008

9821009
// Update session with FINAL deck info
983-
await sessionRepository.updateSession(user.owner, {
984-
deckInfo: userSession.data.deckInfo,
985-
});
1010+
await sessionRepository.updateSession(
1011+
user.owner,
1012+
{
1013+
deckInfo: userSession.data.deckInfo,
1014+
},
1015+
userSession.id
1016+
);
9861017

9871018
// Store text input in session data
9881019
if (content.trim().length > 0) {
9891020
userSession.data.text = content;
990-
await sessionRepository.updateSession(user.owner, {
991-
text: content,
992-
});
1021+
await sessionRepository.updateSession(
1022+
user.owner,
1023+
{
1024+
text: content,
1025+
},
1026+
userSession.id
1027+
);
9931028
}
9941029

9951030
res.write(
@@ -1160,7 +1195,6 @@ const KiRouter = () => {
11601195

11611196
router.delete('/ki/session/delete', async (req, res) => {
11621197
const canDeleteSession = await canContinue(req, res);
1163-
console.log('[DELETE SESSION] Can delete session:', canDeleteSession);
11641198
if (!canDeleteSession) {
11651199
return; // Exit if the user cannot continue
11661200
}
@@ -1171,18 +1205,21 @@ const KiRouter = () => {
11711205
return false;
11721206
}
11731207

1174-
const userSession = await sessionRepository.getSession(user.owner);
1175-
if (!userSession) {
1176-
console.error('[DELETE SESSION] User session not found');
1177-
return res.status(403).json({ error: 'Session expired' });
1208+
const { sessionId } = req.query;
1209+
if (!sessionId) {
1210+
console.error('[DELETE SESSION] No session ID provided');
1211+
return res.status(400).json({ error: 'Session ID is required' });
11781212
}
11791213

11801214
try {
1181-
await sessionRepository.deleteSession(user.owner);
1182-
console.log('[DELETE SESSION] Session cleared for user:', user.owner);
1215+
await sessionRepository.deleteSessionById(
1216+
sessionId as string,
1217+
user.owner
1218+
);
1219+
console.log('[DELETE SESSION] Session deleted:', sessionId);
11831220
res.status(200).json({ message: 'Session deleted successfully' });
11841221
} catch (error) {
1185-
console.error('[DELETE SESSION] Error clearing session:', error);
1222+
console.error('[DELETE SESSION] Error deleting session:', error);
11861223
res.status(500).json({ error: 'Failed to delete session' });
11871224
}
11881225
});
@@ -1244,13 +1281,15 @@ const KiRouter = () => {
12441281
const sessions = await sessionRepository.getUserSessions(
12451282
user.owner.toString()
12461283
);
1247-
res.json(
1248-
sessions.map((session) => ({
1284+
const currentSession = await sessionRepository.getSession(user.owner);
1285+
res.json({
1286+
sessions: sessions.map((session) => ({
12491287
id: session.id,
12501288
createdAt: session.createdAt,
12511289
updatedAt: session.updatedAt,
1252-
}))
1253-
);
1290+
})),
1291+
currentSessionId: currentSession?.id,
1292+
});
12541293
} catch (error) {
12551294
console.error('[HISTORY] Error fetching session history:', error);
12561295
res.status(500).json({ error: 'Failed to fetch session history' });

0 commit comments

Comments
 (0)