refactor(collab, collections, maps): async DB-touching methods; transactions through UnitOfWork

This commit is contained in:
jubnl
2026-09-22 01:49:18 +02:00
parent fdb12aed1e
commit 6b755314d8
26 changed files with 1115 additions and 1116 deletions
+41 -41
View File
@@ -110,15 +110,15 @@ export class CollabController {
private readonly storage: StorageService,
) {}
private requireTrip(tripId: string, user: User) {
const trip = this.collab.verifyTripAccess(tripId, user.id);
private async requireTrip(tripId: string, user: User) {
const trip = await this.collab.verifyTripAccess(tripId, user.id);
if (!trip) {
throw new HttpException({ error: 'Trip not found' }, 404);
}
return trip;
}
private async requireEdit(trip: NonNullable<ReturnType<CollabService['verifyTripAccess']>>, user: User): Promise<void> {
private async requireEdit(trip: NonNullable<Awaited<ReturnType<CollabService['verifyTripAccess']>>>, user: User): Promise<void> {
if (!(await this.collab.canEdit(trip, user))) {
throw new HttpException({ error: 'No permission' }, 403);
}
@@ -127,15 +127,15 @@ export class CollabController {
// ── Notes ───────────────────────────────────────────────────────────────
@UseGuards(TripAccessGuard)
@Get('notes')
listNotes(@CurrentUser() user: User, @Param('tripId') tripId: string) {
return { notes: this.collab.listNotes(tripId) };
async listNotes(@CurrentUser() user: User, @Param('tripId') tripId: string) {
return { notes: await this.collab.listNotes(tripId) };
}
@UseGuards(TripAccessGuard)
@RequirePermission('collab_edit')
@Post('notes')
createNote(@CurrentUser() user: User, @Param('tripId') tripId: string, @Body() body: CollabNoteCreateDto, @Headers('x-socket-id') socketId?: string) {
const note = this.collab.createNote(tripId, user.id, {
async createNote(@CurrentUser() user: User, @Param('tripId') tripId: string, @Body() body: CollabNoteCreateDto, @Headers('x-socket-id') socketId?: string) {
const note = await this.collab.createNote(tripId, user.id, {
title: body.title,
content: body.content,
category: body.category,
@@ -143,15 +143,15 @@ export class CollabController {
website: body.website,
});
this.collab.broadcast(tripId, 'collab:note:created', { note }, socketId);
this.collab.notifyCollab(tripId, user);
await this.collab.notifyCollab(tripId, user);
return { note };
}
@UseGuards(TripAccessGuard)
@RequirePermission('collab_edit')
@Put('notes/:id')
updateNote(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Body() body: CollabNoteUpdateDto, @Headers('x-socket-id') socketId?: string) {
const note = this.collab.updateNote(tripId, id, {
async updateNote(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Body() body: CollabNoteUpdateDto, @Headers('x-socket-id') socketId?: string) {
const note = await this.collab.updateNote(tripId, id, {
title: body.title,
content: body.content,
category: body.category,
@@ -187,7 +187,7 @@ export class CollabController {
if (file?.path) { try { fs.unlinkSync(file.path); } catch { /* best-effort */ } }
};
try {
const trip = this.requireTrip(tripId, user);
const trip = await this.requireTrip(tripId, user);
if (!(await this.collab.canUploadFiles(trip, user))) {
throw new HttpException({ error: 'No permission to upload files' }, 403);
}
@@ -201,13 +201,13 @@ export class CollabController {
// Commit the spooled upload to its final storage location (atomic
// same-volume rename) before the DB row references the final path.
await this.storage.put('files', file.filename, { tmpPath: file.path });
const result = this.collab.addNoteFile(tripId, id, file);
const result = await this.collab.addNoteFile(tripId, id, file);
if (!result) {
// Already committed, so the spool file is gone; drop the final object.
await this.storage.delete('files', file.filename).catch(() => {});
throw new HttpException({ error: 'Note not found' }, 404);
}
this.collab.broadcast(tripId, 'collab:note:updated', { note: this.collab.getFormattedNoteById(tripId, id) }, socketId);
this.collab.broadcast(tripId, 'collab:note:updated', { note: await this.collab.getFormattedNoteById(tripId, id) }, socketId);
return result;
}
@@ -218,22 +218,22 @@ export class CollabController {
if (!(await this.collab.deleteNoteFile(tripId, id, fileId))) {
throw new HttpException({ error: 'File not found' }, 404);
}
this.collab.broadcast(tripId, 'collab:note:updated', { note: this.collab.getFormattedNoteById(tripId, id) }, socketId);
this.collab.broadcast(tripId, 'collab:note:updated', { note: await this.collab.getFormattedNoteById(tripId, id) }, socketId);
return { success: true };
}
// ── Shared links ────────────────────────────────────────────────────────
@UseGuards(TripAccessGuard)
@Get('links')
listLinks(@CurrentUser() user: User, @Param('tripId') tripId: string) {
return { links: this.collab.listLinks(tripId) };
async listLinks(@CurrentUser() user: User, @Param('tripId') tripId: string) {
return { links: await this.collab.listLinks(tripId) };
}
@UseGuards(TripAccessGuard)
@RequirePermission('collab_edit')
@Post('links')
createLink(@CurrentUser() user: User, @Param('tripId') tripId: string, @Body() body: CollabLinkCreateDto, @Headers('x-socket-id') socketId?: string) {
const link = this.collab.createLink(tripId, user.id, { title: body.title, url: body.url, pinned: Boolean(body.pinned) });
async createLink(@CurrentUser() user: User, @Param('tripId') tripId: string, @Body() body: CollabLinkCreateDto, @Headers('x-socket-id') socketId?: string) {
const link = await this.collab.createLink(tripId, user.id, { title: body.title, url: body.url, pinned: Boolean(body.pinned) });
this.collab.broadcast(tripId, 'collab:link:created', { link }, socketId);
return { link };
}
@@ -241,8 +241,8 @@ export class CollabController {
@UseGuards(TripAccessGuard)
@RequirePermission('collab_edit')
@Put('links/:id')
updateLink(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Body() body: CollabLinkUpdateDto, @Headers('x-socket-id') socketId?: string) {
const link = this.collab.updateLink(tripId, id, {
async updateLink(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Body() body: CollabLinkUpdateDto, @Headers('x-socket-id') socketId?: string) {
const link = await this.collab.updateLink(tripId, id, {
title: body.title,
url: body.url,
pinned: body.pinned === undefined ? undefined : Boolean(body.pinned),
@@ -255,8 +255,8 @@ export class CollabController {
@UseGuards(TripAccessGuard)
@RequirePermission('collab_edit')
@Delete('links/:id')
deleteLink(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Headers('x-socket-id') socketId?: string) {
if (!this.collab.deleteLink(tripId, id)) throw new HttpException({ error: 'Link not found' }, 404);
async deleteLink(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Headers('x-socket-id') socketId?: string) {
if (!(await this.collab.deleteLink(tripId, id))) throw new HttpException({ error: 'Link not found' }, 404);
this.collab.broadcast(tripId, 'collab:link:deleted', { linkId: Number(id) }, socketId);
return { success: true };
}
@@ -264,15 +264,15 @@ export class CollabController {
// ── Polls ───────────────────────────────────────────────────────────────
@UseGuards(TripAccessGuard)
@Get('polls')
listPolls(@CurrentUser() user: User, @Param('tripId') tripId: string) {
return { polls: this.collab.listPolls(tripId) };
async listPolls(@CurrentUser() user: User, @Param('tripId') tripId: string) {
return { polls: await this.collab.listPolls(tripId) };
}
@UseGuards(TripAccessGuard)
@RequirePermission('collab_edit')
@Post('polls')
createPoll(@CurrentUser() user: User, @Param('tripId') tripId: string, @Body() body: CollabPollCreateDto, @Headers('x-socket-id') socketId?: string) {
const poll = this.collab.createPoll(tripId, user.id, {
async createPoll(@CurrentUser() user: User, @Param('tripId') tripId: string, @Body() body: CollabPollCreateDto, @Headers('x-socket-id') socketId?: string) {
const poll = await this.collab.createPoll(tripId, user.id, {
question: body.question,
options: body.options,
multiple: body.multiple,
@@ -287,8 +287,8 @@ export class CollabController {
@RequirePermission('collab_edit')
@Post('polls/:id/vote')
@HttpCode(200)
votePoll(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Body() body: CollabPollVoteDto, @Headers('x-socket-id') socketId?: string) {
const result = this.collab.votePoll(tripId, id, user.id, body.option_index);
async votePoll(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Body() body: CollabPollVoteDto, @Headers('x-socket-id') socketId?: string) {
const result = await this.collab.votePoll(tripId, id, user.id, body.option_index);
if (result.error === 'not_found') throw new HttpException({ error: 'Poll not found' }, 404);
if (result.error === 'closed') throw new HttpException({ error: 'Poll is closed' }, 400);
if (result.error === 'invalid_index') throw new HttpException({ error: 'Invalid option index' }, 400);
@@ -299,8 +299,8 @@ export class CollabController {
@UseGuards(TripAccessGuard)
@RequirePermission('collab_edit')
@Put('polls/:id/close')
closePoll(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Headers('x-socket-id') socketId?: string) {
const poll = this.collab.closePoll(tripId, id);
async closePoll(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Headers('x-socket-id') socketId?: string) {
const poll = await this.collab.closePoll(tripId, id);
if (!poll) {
throw new HttpException({ error: 'Poll not found' }, 404);
}
@@ -311,8 +311,8 @@ export class CollabController {
@UseGuards(TripAccessGuard)
@RequirePermission('collab_edit')
@Delete('polls/:id')
deletePoll(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Headers('x-socket-id') socketId?: string) {
if (!this.collab.deletePoll(tripId, id)) {
async deletePoll(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Headers('x-socket-id') socketId?: string) {
if (!(await this.collab.deletePoll(tripId, id))) {
throw new HttpException({ error: 'Poll not found' }, 404);
}
this.collab.broadcast(tripId, 'collab:poll:deleted', { pollId: Number(id) }, socketId);
@@ -322,8 +322,8 @@ export class CollabController {
// ── Messages ────────────────────────────────────────────────────────────
@UseGuards(TripAccessGuard)
@Get('messages')
listMessages(@CurrentUser() user: User, @Param('tripId') tripId: string, @Query('before') before?: string) {
return { messages: this.collab.listMessages(tripId, before) };
async listMessages(@CurrentUser() user: User, @Param('tripId') tripId: string, @Query('before') before?: string) {
return { messages: await this.collab.listMessages(tripId, before) };
}
// No guard decorators, deliberately, like every other upload route in this
@@ -344,7 +344,7 @@ export class CollabController {
const cleanupSpool = () => uploaded.forEach(file => { if (file.path) { try { fs.unlinkSync(file.path); } catch { /* best-effort */ } } });
let trip;
try {
trip = this.requireTrip(tripId, user);
trip = await this.requireTrip(tripId, user);
await this.requireEdit(trip, user);
} catch (err) {
cleanupSpool();
@@ -376,7 +376,7 @@ export class CollabController {
throw err;
}
const replyTo = body.reply_to === undefined || body.reply_to === '' || body.reply_to === null ? null : Number(body.reply_to);
const result = this.collab.createMessage(
const result = await this.collab.createMessage(
tripId,
user.id,
text,
@@ -389,7 +389,7 @@ export class CollabController {
}
this.collab.broadcast(tripId, 'collab:message:created', { message: result.message }, socketId);
const preview = text || 'sent an image';
this.collab.notifyCollab(tripId, user, preview.length > 80 ? preview.substring(0, 80) + '...' : preview);
await this.collab.notifyCollab(tripId, user, preview.length > 80 ? preview.substring(0, 80) + '...' : preview);
return { message: result.message };
}
@@ -397,8 +397,8 @@ export class CollabController {
@RequirePermission('collab_edit')
@Post('messages/:id/react')
@HttpCode(200)
react(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Body() body: CollabReactionDto, @Headers('x-socket-id') socketId?: string) {
const result = this.collab.reactMessage(id, tripId, user.id, body.emoji);
async react(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Body() body: CollabReactionDto, @Headers('x-socket-id') socketId?: string) {
const result = await this.collab.reactMessage(id, tripId, user.id, body.emoji);
if (!result.found) {
throw new HttpException({ error: 'Message not found' }, 404);
}
@@ -409,8 +409,8 @@ export class CollabController {
@UseGuards(TripAccessGuard)
@RequirePermission('collab_edit')
@Delete('messages/:id')
deleteMessage(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Headers('x-socket-id') socketId?: string) {
const result = this.collab.deleteMessage(tripId, id, user.id);
async deleteMessage(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Headers('x-socket-id') socketId?: string) {
const result = await this.collab.deleteMessage(tripId, id, user.id);
if (result.error === 'not_found') throw new HttpException({ error: 'Message not found' }, 404);
if (result.error === 'not_owner') throw new HttpException({ error: 'You can only delete your own messages' }, 403);
this.collab.broadcast(tripId, 'collab:message:deleted', { messageId: Number(id), username: result.username || user.username }, socketId);
+29 -29
View File
@@ -95,9 +95,9 @@ export class CollabMcp {
ctx: McpContext,
) {
if (await this.auth.isDemoUser(ctx.userId)) return demoDenied();
if (!this.collab.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!(await this.collab.verifyTripAccess(tripId, ctx.userId))) return noAccess();
if (!(await this.guards.hasTripPermission('collab_edit', tripId, ctx.userId))) return permissionDenied();
const note = this.collab.createNote(tripId, ctx.userId, { title, content, category, color, website, pinned });
const note = await this.collab.createNote(tripId, ctx.userId, { title, content, category, color, website, pinned });
this.guards.safeBroadcast(tripId, 'collab:note:created', { note });
return ok({ note });
}
@@ -126,9 +126,9 @@ export class CollabMcp {
ctx: McpContext,
) {
if (await this.auth.isDemoUser(ctx.userId)) return demoDenied();
if (!this.collab.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!(await this.collab.verifyTripAccess(tripId, ctx.userId))) return noAccess();
if (!(await this.guards.hasTripPermission('collab_edit', tripId, ctx.userId))) return permissionDenied();
const note = this.collab.updateNote(tripId, noteId, { title, content, category, color, website, pinned });
const note = await this.collab.updateNote(tripId, noteId, { title, content, category, color, website, pinned });
if (!note) return errorResult('Note not found.');
this.guards.safeBroadcast(tripId, 'collab:note:updated', { note });
return ok({ note });
@@ -147,7 +147,7 @@ export class CollabMcp {
})
async deleteCollabNote({ tripId, noteId }: { tripId: number; noteId: number }, ctx: McpContext) {
if (await this.auth.isDemoUser(ctx.userId)) return demoDenied();
if (!this.collab.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!(await this.collab.verifyTripAccess(tripId, ctx.userId))) return noAccess();
if (!(await this.guards.hasTripPermission('collab_edit', tripId, ctx.userId))) return permissionDenied();
const deleted = await this.collab.deleteNote(tripId, noteId);
if (!deleted) return errorResult('Note not found.');
@@ -168,8 +168,8 @@ export class CollabMcp {
access: { group: 'collab', mode: 'read' },
})
async listCollabPolls({ tripId }: { tripId: number }, ctx: McpContext) {
if (!this.collab.verifyTripAccess(tripId, ctx.userId)) return noAccess();
const polls = this.collab.listPolls(tripId);
if (!(await this.collab.verifyTripAccess(tripId, ctx.userId))) return noAccess();
const polls = await this.collab.listPolls(tripId);
return ok({ polls });
}
@@ -194,9 +194,9 @@ export class CollabMcp {
ctx: McpContext,
) {
if (await this.auth.isDemoUser(ctx.userId)) return demoDenied();
if (!this.collab.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!(await this.collab.verifyTripAccess(tripId, ctx.userId))) return noAccess();
if (!(await this.guards.hasTripPermission('collab_edit', tripId, ctx.userId))) return permissionDenied();
const poll = this.collab.createPoll(tripId, ctx.userId, { question, options, multiple, deadline });
const poll = await this.collab.createPoll(tripId, ctx.userId, { question, options, multiple, deadline });
this.guards.safeBroadcast(tripId, 'collab:poll:created', { poll });
return ok({ poll });
}
@@ -215,9 +215,9 @@ export class CollabMcp {
})
async voteCollabPoll({ tripId, pollId, optionIndex }: { tripId: number; pollId: number; optionIndex: number }, ctx: McpContext) {
if (await this.auth.isDemoUser(ctx.userId)) return demoDenied();
if (!this.collab.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!(await this.collab.verifyTripAccess(tripId, ctx.userId))) return noAccess();
if (!(await this.guards.hasTripPermission('collab_edit', tripId, ctx.userId))) return permissionDenied();
const result = this.collab.votePoll(tripId, pollId, ctx.userId, optionIndex);
const result = await this.collab.votePoll(tripId, pollId, ctx.userId, optionIndex);
if (result.error) return errorResult(result.error);
this.guards.safeBroadcast(tripId, 'collab:poll:voted', { poll: result.poll });
return ok({ poll: result.poll });
@@ -236,9 +236,9 @@ export class CollabMcp {
})
async closeCollabPoll({ tripId, pollId }: { tripId: number; pollId: number }, ctx: McpContext) {
if (await this.auth.isDemoUser(ctx.userId)) return demoDenied();
if (!this.collab.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!(await this.collab.verifyTripAccess(tripId, ctx.userId))) return noAccess();
if (!(await this.guards.hasTripPermission('collab_edit', tripId, ctx.userId))) return permissionDenied();
const poll = this.collab.closePoll(tripId, pollId);
const poll = await this.collab.closePoll(tripId, pollId);
if (!poll) return errorResult('Poll not found.');
this.guards.safeBroadcast(tripId, 'collab:poll:closed', { poll });
return ok({ poll });
@@ -257,9 +257,9 @@ export class CollabMcp {
})
async deleteCollabPoll({ tripId, pollId }: { tripId: number; pollId: number }, ctx: McpContext) {
if (await this.auth.isDemoUser(ctx.userId)) return demoDenied();
if (!this.collab.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!(await this.collab.verifyTripAccess(tripId, ctx.userId))) return noAccess();
if (!(await this.guards.hasTripPermission('collab_edit', tripId, ctx.userId))) return permissionDenied();
const deleted = this.collab.deletePoll(tripId, pollId);
const deleted = await this.collab.deletePoll(tripId, pollId);
if (!deleted) return errorResult('Poll not found.');
this.guards.safeBroadcast(tripId, 'collab:poll:deleted', { pollId });
return ok({ success: true });
@@ -277,8 +277,8 @@ export class CollabMcp {
access: { group: 'collab', mode: 'read' },
})
async listCollabMessages({ tripId, before }: { tripId: number; before?: number }, ctx: McpContext) {
if (!this.collab.verifyTripAccess(tripId, ctx.userId)) return noAccess();
const messages = this.collab.listMessages(tripId, before);
if (!(await this.collab.verifyTripAccess(tripId, ctx.userId))) return noAccess();
const messages = await this.collab.listMessages(tripId, before);
return ok({ messages });
}
@@ -296,9 +296,9 @@ export class CollabMcp {
})
async sendCollabMessage({ tripId, text, replyTo }: { tripId: number; text: string; replyTo?: number }, ctx: McpContext) {
if (await this.auth.isDemoUser(ctx.userId)) return demoDenied();
if (!this.collab.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!(await this.collab.verifyTripAccess(tripId, ctx.userId))) return noAccess();
if (!(await this.guards.hasTripPermission('collab_edit', tripId, ctx.userId))) return permissionDenied();
const result = this.collab.createMessage(tripId, ctx.userId, text, replyTo ?? null);
const result = await this.collab.createMessage(tripId, ctx.userId, text, replyTo ?? null);
if (result.error) return errorResult(result.error);
this.guards.safeBroadcast(tripId, 'collab:message:created', { message: result.message });
return ok({ message: result.message });
@@ -317,9 +317,9 @@ export class CollabMcp {
})
async deleteCollabMessage({ tripId, messageId }: { tripId: number; messageId: number }, ctx: McpContext) {
if (await this.auth.isDemoUser(ctx.userId)) return demoDenied();
if (!this.collab.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!(await this.collab.verifyTripAccess(tripId, ctx.userId))) return noAccess();
if (!(await this.guards.hasTripPermission('collab_edit', tripId, ctx.userId))) return permissionDenied();
const result = this.collab.deleteMessage(tripId, messageId, ctx.userId);
const result = await this.collab.deleteMessage(tripId, messageId, ctx.userId);
if (result.error) return errorResult(result.error);
this.guards.safeBroadcast(tripId, 'collab:message:deleted', { messageId, username: result.username });
return ok({ success: true });
@@ -339,9 +339,9 @@ export class CollabMcp {
})
async reactCollabMessage({ tripId, messageId, emoji }: { tripId: number; messageId: number; emoji: string }, ctx: McpContext) {
if (await this.auth.isDemoUser(ctx.userId)) return demoDenied();
if (!this.collab.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!(await this.collab.verifyTripAccess(tripId, ctx.userId))) return noAccess();
if (!(await this.guards.hasTripPermission('collab_edit', tripId, ctx.userId))) return permissionDenied();
const result = this.collab.reactMessage(messageId, tripId, ctx.userId, emoji);
const result = await this.collab.reactMessage(messageId, tripId, ctx.userId, emoji);
if (!result.found) return errorResult('Message not found.');
this.guards.safeBroadcast(tripId, 'collab:message:reacted', { messageId, reactions: result.reactions });
return ok({ reactions: result.reactions });
@@ -359,8 +359,8 @@ export class CollabMcp {
})
async tripCollabNotesResource(uri: URL, { tripId }: { tripId: string | string[] }, ctx: McpContext) {
const id = parseId(tripId);
if (id === null || !this.collab.verifyTripAccess(id, ctx.userId)) return accessDenied(uri.href);
const notes = this.collab.listNotes(id);
if (id === null || !(await this.collab.verifyTripAccess(id, ctx.userId))) return accessDenied(uri.href);
const notes = await this.collab.listNotes(id);
return jsonContent(uri.href, notes);
}
@@ -374,8 +374,8 @@ export class CollabMcp {
})
async tripCollabPollsResource(uri: URL, { tripId }: { tripId: string | string[] }, ctx: McpContext) {
const id = parseId(tripId);
if (id === null || !this.collab.verifyTripAccess(id, ctx.userId)) return accessDenied(uri.href);
const polls = this.collab.listPolls(id);
if (id === null || !(await this.collab.verifyTripAccess(id, ctx.userId))) return accessDenied(uri.href);
const polls = await this.collab.listPolls(id);
return jsonContent(uri.href, polls);
}
@@ -389,8 +389,8 @@ export class CollabMcp {
})
async tripCollabMessagesResource(uri: URL, { tripId }: { tripId: string | string[] }, ctx: McpContext) {
const id = parseId(tripId);
if (id === null || !this.collab.verifyTripAccess(id, ctx.userId)) return accessDenied(uri.href);
const messages = this.collab.listMessages(id);
if (id === null || !(await this.collab.verifyTripAccess(id, ctx.userId))) return accessDenied(uri.href);
const messages = await this.collab.listMessages(id);
return jsonContent(uri.href, messages);
}
}
+7 -7
View File
@@ -33,7 +33,7 @@ export class CollabRpc {
listNotes(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
return this.guards.tripRead(params, ctx, async () => {
await this.requireCollabAddon();
return this.collab.listNotes(num(params.tripId, 'tripId')) as unknown[];
return (await this.collab.listNotes(num(params.tripId, 'tripId'))) as unknown[];
});
}
@@ -41,7 +41,7 @@ export class CollabRpc {
listPolls(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
return this.guards.tripRead(params, ctx, async () => {
await this.requireCollabAddon();
return this.collab.listPolls(num(params.tripId, 'tripId')) as unknown[];
return (await this.collab.listPolls(num(params.tripId, 'tripId'))) as unknown[];
});
}
@@ -50,7 +50,7 @@ export class CollabRpc {
return this.guards.tripRead(params, ctx, async () => {
await this.requireCollabAddon();
const before = params.before != null ? num(params.before, 'before') : undefined;
return this.collab.listMessages(num(params.tripId, 'tripId'), before) as unknown[];
return (await this.collab.listMessages(num(params.tripId, 'tripId'), before)) as unknown[];
});
}
@@ -62,7 +62,7 @@ export class CollabRpc {
if (typeof input.title !== 'string' || input.title.trim() === '') throw new BadParams('note title is required');
await this.guards.requireTripEdit(tripId, actor, COLLAB_EDIT_ACTION);
await this.requireCollabAddon();
const note = this.collab.createNote(String(tripId), actor, input as never);
const note = await this.collab.createNote(String(tripId), actor, input as never);
this.realtime.broadcast(tripId, 'collab:note:created', { note }, undefined);
return note;
}
@@ -76,7 +76,7 @@ export class CollabRpc {
if (!Array.isArray(input.options) || input.options.length < 2) throw new BadParams('a poll needs at least two options');
await this.guards.requireTripEdit(tripId, actor, COLLAB_EDIT_ACTION);
await this.requireCollabAddon();
const poll = this.collab.createPoll(String(tripId), actor, input as never);
const poll = await this.collab.createPoll(String(tripId), actor, input as never);
this.realtime.broadcast(tripId, 'collab:poll:created', { poll }, undefined);
return poll;
}
@@ -87,7 +87,7 @@ export class CollabRpc {
const actor = this.guards.requireActor(ctx, 'collab poll');
await this.guards.requireTripEdit(tripId, actor, COLLAB_EDIT_ACTION);
await this.requireCollabAddon();
const result = this.collab.votePoll(String(tripId), String(num(params.pollId, 'pollId')), actor, num(params.optionIndex, 'optionIndex'));
const result = await this.collab.votePoll(String(tripId), String(num(params.pollId, 'pollId')), actor, num(params.optionIndex, 'optionIndex'));
// The service reports its own validation failures rather than throwing.
if (result.error) throw new BadParams(result.error);
this.realtime.broadcast(tripId, 'collab:poll:voted', { poll: result.poll }, undefined);
@@ -104,7 +104,7 @@ export class CollabRpc {
await this.guards.requireTripEdit(tripId, actor, COLLAB_EDIT_ACTION);
await this.requireCollabAddon();
const replyTo = typeof params.replyTo === 'number' ? params.replyTo : null;
const result = this.collab.createMessage(String(tripId), actor, params.text, replyTo);
const result = await this.collab.createMessage(String(tripId), actor, params.text, replyTo);
if (result.error) throw new BadParams(result.error);
this.realtime.broadcast(tripId, 'collab:message:created', { message: result.message }, undefined);
return result.message;
+42 -37
View File
@@ -11,6 +11,7 @@ import type { CollabNote, CollabPoll, CollabMessage, TripFile, User } from '../.
import { NotificationsService } from '../notifications/notifications.service';
import { StorageService } from '../storage/storage.service';
import { RateLimitService } from '../common/rate-limit.service';
import { UnitOfWork } from '../database/unit-of-work';
type Trip = TripAccess;
@@ -111,7 +112,8 @@ function scrapeOpenGraph(html: string): Omit<LinkPreviewResult, 'url'> {
* strings). Trip access, the 'collab_edit' / 'file_upload' permissions and the
* WebSocket broadcast keep their legacy call paths. Post-migration hardening
* on top of the 1:1 move: the multi-statement writes (deleteNote, votePoll)
* run in db.transaction(), getFormattedNoteById is trip-scoped and null-safe,
* run through UnitOfWork.transactional(), getFormattedNoteById is trip-scoped
* and null-safe,
* votePoll rejects non-integer indexes, and linkPreview absorbs malformed URLs
* instead of throwing.
* All consumers are in-container since the trip fold (TripsService and
@@ -127,6 +129,7 @@ export class CollabService {
private readonly notifications: NotificationsService,
private readonly storage: StorageService,
private readonly rateLimit: RateLimitService,
private readonly uow: UnitOfWork,
) {}
/**
@@ -143,7 +146,7 @@ export class CollabService {
/** Preview fetches currently in flight, so simultaneous askers share one request. */
private readonly inFlight = new Map<string, Promise<LinkPreviewResult>>();
verifyTripAccess(tripId: string | number, userId: number) {
async verifyTripAccess(tripId: string | number, userId: number) {
return this.db.canAccessTrip(tripId, userId);
}
@@ -163,7 +166,7 @@ export class CollabService {
/* Reactions */
/* ------------------------------------------------------------------ */
private loadReactions(messageId: number | string): ReactionRow[] {
private async loadReactions(messageId: number | string): Promise<ReactionRow[]> {
return this.db.all<ReactionRow>(`
SELECT r.emoji, r.user_id, u.username
FROM collab_message_reactions r
@@ -181,7 +184,7 @@ export class CollabService {
return Object.entries(map).map(([emoji, users]) => ({ emoji, users, count: users.length }));
}
reactMessage(messageId: number | string, tripId: number | string, userId: number, emoji: string): { found: boolean; reactions: GroupedReaction[] } {
async reactMessage(messageId: number | string, tripId: number | string, userId: number, emoji: string): Promise<{ found: boolean; reactions: GroupedReaction[] }> {
const msg = this.db.get('SELECT id FROM collab_messages WHERE id = ? AND trip_id = ?', messageId, tripId);
if (!msg) return { found: false, reactions: [] };
@@ -192,14 +195,14 @@ export class CollabService {
this.db.run('INSERT INTO collab_message_reactions (message_id, user_id, emoji) VALUES (?, ?, ?)', messageId, userId, emoji);
}
return { found: true, reactions: this.groupReactions(this.loadReactions(messageId)) };
return { found: true, reactions: this.groupReactions(await this.loadReactions(messageId)) };
}
/* ------------------------------------------------------------------ */
/* Notes */
/* ------------------------------------------------------------------ */
private formatNote(note: CollabNote) {
private async formatNote(note: CollabNote) {
const attachments = this.db.all<NoteFileRow>('SELECT id, filename, original_name, file_size, mime_type FROM trip_files WHERE note_id = ?', note.id);
return {
...note,
@@ -208,7 +211,7 @@ export class CollabService {
};
}
listNotes(tripId: string | number) {
async listNotes(tripId: string | number) {
const notes = this.db.all<CollabNote>(`
SELECT n.*, u.username, u.avatar
FROM collab_notes n
@@ -217,10 +220,10 @@ export class CollabService {
ORDER BY n.pinned DESC, n.updated_at DESC
`, tripId);
return notes.map(note => this.formatNote(note));
return Promise.all(notes.map(note => this.formatNote(note)));
}
createNote(tripId: string | number, userId: number, data: { title: string; content?: string | null; category?: string | null; color?: string | null; website?: string | null; pinned?: boolean }) {
async createNote(tripId: string | number, userId: number, data: { title: string; content?: string | null; category?: string | null; color?: string | null; website?: string | null; pinned?: boolean }) {
const pinned = data.pinned ? 1 : 0;
const result = this.db.run(`
INSERT INTO collab_notes (trip_id, user_id, title, content, category, color, website, pinned)
@@ -234,7 +237,7 @@ export class CollabService {
return this.formatNote(note);
}
updateNote(tripId: string | number, noteId: string | number, data: { title?: string; content?: string | null; category?: string | null; color?: string | null; pinned?: number | boolean; website?: string | null }): ReturnType<CollabService['formatNote']> | null {
async updateNote(tripId: string | number, noteId: string | number, data: { title?: string; content?: string | null; category?: string | null; color?: string | null; pinned?: number | boolean; website?: string | null }): Promise<Awaited<ReturnType<CollabService['formatNote']>> | null> {
const existing = this.db.get('SELECT * FROM collab_notes WHERE id = ? AND trip_id = ?', noteId, tripId);
if (!existing) return null;
@@ -277,7 +280,7 @@ export class CollabService {
for (const f of noteFiles) {
await this.storage.delete('files', path.basename(f.filename)).catch(() => { /* ignore */ });
}
this.db.transaction(() => {
await this.uow.transactional(async () => {
this.db.run('DELETE FROM trip_files WHERE note_id = ?', noteId);
this.db.run('DELETE FROM collab_notes WHERE id = ?', noteId);
});
@@ -288,7 +291,7 @@ export class CollabService {
/* Note files */
/* ------------------------------------------------------------------ */
addNoteFile(tripId: string | number, noteId: string | number, file: { filename: string; originalname: string; size: number; mimetype: string }): { file: TripFile & { url: string } } | null {
async addNoteFile(tripId: string | number, noteId: string | number, file: { filename: string; originalname: string; size: number; mimetype: string }): Promise<{ file: TripFile & { url: string } } | null> {
const note = this.db.get('SELECT id FROM collab_notes WHERE id = ? AND trip_id = ?', noteId, tripId);
if (!note) return null;
@@ -301,7 +304,7 @@ export class CollabService {
return { file: { ...saved, url: `/api/trips/${tripId}/files/${saved.id}/download` } };
}
getFormattedNoteById(tripId: string | number, noteId: string | number) {
async getFormattedNoteById(tripId: string | number, noteId: string | number) {
const note = this.db.get<CollabNote>('SELECT n.*, u.username, u.avatar FROM collab_notes n JOIN users u ON n.user_id = u.id WHERE n.id = ? AND n.trip_id = ?', noteId, tripId);
if (!note) return null;
return this.formatNote(note);
@@ -325,7 +328,7 @@ export class CollabService {
/* Polls */
/* ------------------------------------------------------------------ */
private getPollWithVotes(pollId: number | bigint | string) {
private async getPollWithVotes(pollId: number | bigint | string) {
const poll = this.db.get<CollabPoll>(`
SELECT p.*, u.username, u.avatar
FROM collab_polls p
@@ -365,15 +368,15 @@ export class CollabService {
};
}
listPolls(tripId: string | number) {
async listPolls(tripId: string | number) {
const rows = this.db.all<{ id: number }>(`
SELECT id FROM collab_polls WHERE trip_id = ? ORDER BY created_at DESC
`, tripId);
return rows.map(row => this.getPollWithVotes(row.id)).filter(Boolean);
return (await Promise.all(rows.map(row => this.getPollWithVotes(row.id)))).filter(Boolean);
}
createPoll(tripId: string | number, userId: number, data: { question: string; options: unknown[]; multiple?: boolean; multiple_choice?: boolean; deadline?: string }) {
async createPoll(tripId: string | number, userId: number, data: { question: string; options: unknown[]; multiple?: boolean; multiple_choice?: boolean; deadline?: string }) {
const isMultiple = data.multiple || data.multiple_choice;
const result = this.db.run(`
@@ -384,7 +387,7 @@ export class CollabService {
return this.getPollWithVotes(result.lastInsertRowid);
}
votePoll(tripId: string | number, pollId: string | number, userId: number, optionIndex: number): { error?: string; poll?: ReturnType<CollabService['getPollWithVotes']> } {
async votePoll(tripId: string | number, pollId: string | number, userId: number, optionIndex: number): Promise<{ error?: string; poll?: Awaited<ReturnType<CollabService['getPollWithVotes']>> }> {
const poll = this.db.get<CollabPoll>('SELECT * FROM collab_polls WHERE id = ? AND trip_id = ?', pollId, tripId);
if (!poll) return { error: 'not_found' };
if (poll.closed) return { error: 'closed' };
@@ -402,7 +405,7 @@ export class CollabService {
if (existingVote) {
this.db.run('DELETE FROM collab_poll_votes WHERE id = ?', existingVote.id);
} else {
this.db.transaction(() => {
await this.uow.transactional(async () => {
if (!poll.multiple) {
this.db.run('DELETE FROM collab_poll_votes WHERE poll_id = ? AND user_id = ?', pollId, userId);
}
@@ -410,10 +413,10 @@ export class CollabService {
});
}
return { poll: this.getPollWithVotes(pollId) };
return { poll: await this.getPollWithVotes(pollId) };
}
closePoll(tripId: string | number, pollId: string | number): ReturnType<CollabService['getPollWithVotes']> | null {
async closePoll(tripId: string | number, pollId: string | number): Promise<Awaited<ReturnType<CollabService['getPollWithVotes']>> | null> {
const poll = this.db.get('SELECT * FROM collab_polls WHERE id = ? AND trip_id = ?', pollId, tripId);
if (!poll) return null;
@@ -421,7 +424,7 @@ export class CollabService {
return this.getPollWithVotes(pollId);
}
deletePoll(tripId: string | number, pollId: string | number): boolean {
async deletePoll(tripId: string | number, pollId: string | number): Promise<boolean> {
const poll = this.db.get('SELECT id FROM collab_polls WHERE id = ? AND trip_id = ?', pollId, tripId);
if (!poll) return false;
@@ -433,7 +436,7 @@ export class CollabService {
/* Shared links */
/* ------------------------------------------------------------------ */
listLinks(tripId: string | number) {
async listLinks(tripId: string | number) {
return this.db.all(
`SELECT l.*, u.username FROM collab_links l JOIN users u ON u.id = l.user_id
WHERE l.trip_id = ? ORDER BY l.pinned DESC, l.created_at DESC`,
@@ -441,7 +444,7 @@ export class CollabService {
);
}
createLink(tripId: string | number, userId: number, data: { title: string; url: string; pinned?: boolean }) {
async createLink(tripId: string | number, userId: number, data: { title: string; url: string; pinned?: boolean }) {
const result = this.db.run(
'INSERT INTO collab_links (trip_id,user_id,title,url,pinned) VALUES (?,?,?,?,?)',
tripId, userId, data.title.trim(), data.url.trim(), data.pinned ? 1 : 0,
@@ -449,7 +452,7 @@ export class CollabService {
return this.db.get('SELECT l.*, u.username FROM collab_links l JOIN users u ON u.id = l.user_id WHERE l.id = ?', result.lastInsertRowid);
}
updateLink(tripId: string | number, linkId: string | number, data: { title?: string; url?: string; pinned?: boolean | number }) {
async updateLink(tripId: string | number, linkId: string | number, data: { title?: string; url?: string; pinned?: boolean | number }) {
const existing = this.db.get<any>('SELECT * FROM collab_links WHERE id = ? AND trip_id = ?', linkId, tripId);
if (!existing) return null;
this.db.run(
@@ -463,7 +466,7 @@ export class CollabService {
return this.db.get('SELECT l.*, u.username FROM collab_links l JOIN users u ON u.id = l.user_id WHERE l.id = ?', linkId);
}
deleteLink(tripId: string | number, linkId: string | number): boolean {
async deleteLink(tripId: string | number, linkId: string | number): Promise<boolean> {
return this.db.run('DELETE FROM collab_links WHERE id = ? AND trip_id = ?', linkId, tripId).changes > 0;
}
@@ -471,7 +474,7 @@ export class CollabService {
/* Messages */
/* ------------------------------------------------------------------ */
private formatMessage(msg: CollabMessage, reactions?: GroupedReaction[]) {
private async formatMessage(msg: CollabMessage, reactions?: GroupedReaction[]) {
const attachments = msg.id && msg.trip_id
? this.db.all<any>(
`SELECT id, trip_id, message_id, filename, original_name, file_size, mime_type
@@ -496,12 +499,12 @@ export class CollabService {
};
}
countMessages(tripId: string | number): number {
async countMessages(tripId: string | number): Promise<number> {
const row = this.db.get<{ cnt: number }>('SELECT COUNT(*) as cnt FROM collab_messages WHERE trip_id = ?', tripId)!;
return row.cnt;
}
listMessages(tripId: string | number, before?: string | number) {
async listMessages(tripId: string | number, before?: string | number) {
const query = `
SELECT m.*, u.username, u.avatar,
CASE WHEN rm.deleted = 1 THEN '' ELSE rm.text END AS reply_text,
@@ -542,16 +545,16 @@ export class CollabService {
}
}
return messages.map(m => this.formatMessage(m, this.groupReactions(reactionsByMsg[m.id] || [])));
return Promise.all(messages.map(m => this.formatMessage(m, this.groupReactions(reactionsByMsg[m.id] || []))));
}
createMessage(
async createMessage(
tripId: string | number,
userId: number,
text: string,
replyTo?: number | null,
files: Array<{ filename: string; originalname: string; size: number; mimetype: string }> = [],
): { error?: string; message?: ReturnType<CollabService['formatMessage']> } {
): Promise<{ error?: string; message?: Awaited<ReturnType<CollabService['formatMessage']>> }> {
if (replyTo) {
// A soft-deleted message is gone as far as anyone replying is concerned:
// its row survives only so the placeholder can be drawn where it was.
@@ -564,7 +567,7 @@ export class CollabService {
// One transaction: the caller has already committed the image bytes to
// storage, so a message row that lands without its attachment rows would
// leave those bytes with nothing pointing at them and nothing to sweep them.
const result = this.db.transaction(() => {
const result = await this.uow.transactional(async () => {
const inserted = this.db.run(`
INSERT INTO collab_messages (trip_id, user_id, text, reply_to) VALUES (?, ?, ?, ?)
`, tripId, userId, text.trim(), replyTo || null);
@@ -590,16 +593,16 @@ export class CollabService {
WHERE m.id = ?
`, result.lastInsertRowid)!;
return { message: this.formatMessage(message) };
return { message: await this.formatMessage(message) };
}
deleteMessage(tripId: string | number, messageId: string | number, userId: number): { error?: string; username?: string } {
async deleteMessage(tripId: string | number, messageId: string | number, userId: number): Promise<{ error?: string; username?: string }> {
const message = this.db.get<CollabMessage>('SELECT * FROM collab_messages WHERE id = ? AND trip_id = ?', messageId, tripId);
if (!message) return { error: 'not_found' };
if (Number(message.user_id) !== Number(userId)) return { error: 'not_owner' };
const attachments = this.db.all<{ filename: string }>('SELECT filename FROM trip_files WHERE message_id = ? AND trip_id = ?', messageId, tripId);
this.db.transaction(() => {
await this.uow.transactional(async () => {
this.db.run('DELETE FROM trip_files WHERE message_id = ? AND trip_id = ?', messageId, tripId);
this.db.run('UPDATE collab_messages SET deleted = 1 WHERE id = ?', messageId);
});
@@ -643,6 +646,8 @@ export class CollabService {
return { ...fallback, rateLimited: true };
}
// Memoised in-flight fetch, not a missing await: the promise is stored so the
// concurrent askers above can join it, and this frame awaits it below.
const task = this.fetchPreview(url, fallback);
this.inFlight.set(url, task);
try {
@@ -725,7 +730,7 @@ export class CollabService {
}
/** Fire-and-forget collab notification (mirrors the legacy route's dynamic import). */
notifyCollab(tripId: string, actor: User, preview?: string): void {
async notifyCollab(tripId: string, actor: User, preview?: string): Promise<void> {
// Injected, not a lazy import of the old notifications bridge. The laziness bought
// nothing the module graph does not already give — NotificationsModule
// reaches nothing in this direction — and it hid the edge while handing the
@@ -99,8 +99,8 @@ export class CollectionsController {
@Post('reorder')
@HttpCode(200)
reorder(@CurrentUser() user: User, @Body() body: CollectionReorderDto) {
this.collections.reorderCollections(user.id, body.orderedIds);
async reorder(@CurrentUser() user: User, @Body() body: CollectionReorderDto) {
await this.collections.reorderCollections(user.id, body.orderedIds);
return { success: true };
}
@@ -260,8 +260,8 @@ export class CollectionsController {
}
@Delete('labels/:lid')
deleteLabel(@CurrentUser() user: User, @Param('lid') lid: string, @Headers('x-socket-id') socketId?: string) {
this.collections.deleteLabel(user.id, Number(lid), socketId);
async deleteLabel(@CurrentUser() user: User, @Param('lid') lid: string, @Headers('x-socket-id') socketId?: string) {
await this.collections.deleteLabel(user.id, Number(lid), socketId);
return { success: true };
}
@@ -307,12 +307,12 @@ export class CollectionsController {
// ── Fusion invitations ──────────────────────────────────────────────────────
@Post('invite')
@HttpCode(200)
invite(@CurrentUser() user: User, @Body() body: CollectionInviteDto) {
this.collections.assertAccess(user.id, body.collection_id); // 404 if not visible (no enumeration)
if (!this.collections.isOwner(user.id, body.collection_id)) {
async invite(@CurrentUser() user: User, @Body() body: CollectionInviteDto) {
await this.collections.assertAccess(user.id, body.collection_id); // 404 if not visible (no enumeration)
if (!(await this.collections.isOwner(user.id, body.collection_id))) {
throw new HttpException({ error: 'Only the owner can invite' }, 403);
}
const result = this.collections.sendInvite(body.collection_id, user.id, user.username, user.email, body.user_id, body.role);
const result = await this.collections.sendInvite(body.collection_id, user.id, user.username, user.email, body.user_id, body.role);
if (result.error) {
throw new HttpException({ error: result.error }, result.status!);
}
@@ -321,8 +321,8 @@ export class CollectionsController {
@Post('invite/accept')
@HttpCode(200)
acceptInvite(@CurrentUser() user: User, @Body() body: CollectionInviteActionDto, @Headers('x-socket-id') socketId?: string) {
const result = this.collections.acceptInvite(user.id, body.collection_id, socketId);
async acceptInvite(@CurrentUser() user: User, @Body() body: CollectionInviteActionDto, @Headers('x-socket-id') socketId?: string) {
const result = await this.collections.acceptInvite(user.id, body.collection_id, socketId);
if (result.error) {
throw new HttpException({ error: result.error }, result.status!);
}
@@ -331,59 +331,59 @@ export class CollectionsController {
@Post('invite/decline')
@HttpCode(200)
declineInvite(@CurrentUser() user: User, @Body() body: CollectionInviteActionDto, @Headers('x-socket-id') socketId?: string) {
this.collections.declineInvite(user.id, body.collection_id, socketId);
async declineInvite(@CurrentUser() user: User, @Body() body: CollectionInviteActionDto, @Headers('x-socket-id') socketId?: string) {
await this.collections.declineInvite(user.id, body.collection_id, socketId);
return { success: true };
}
@Post('invite/cancel')
@HttpCode(200)
cancelInvite(@CurrentUser() user: User, @Body() body: CollectionInviteCancelDto) {
this.collections.assertAccess(user.id, body.collection_id); // 404 if not visible
if (!this.collections.isOwner(user.id, body.collection_id)) {
async cancelInvite(@CurrentUser() user: User, @Body() body: CollectionInviteCancelDto) {
await this.collections.assertAccess(user.id, body.collection_id); // 404 if not visible
if (!(await this.collections.isOwner(user.id, body.collection_id))) {
throw new HttpException({ error: 'Only the owner can cancel invites' }, 403);
}
this.collections.cancelInvite(body.collection_id, user.id, body.user_id);
await this.collections.cancelInvite(body.collection_id, user.id, body.user_id);
return { success: true };
}
@Post('leave')
@HttpCode(200)
leave(@CurrentUser() user: User, @Body() body: CollectionInviteActionDto, @Headers('x-socket-id') socketId?: string) {
this.collections.leaveCollection(user.id, body.collection_id, socketId);
async leave(@CurrentUser() user: User, @Body() body: CollectionInviteActionDto, @Headers('x-socket-id') socketId?: string) {
await this.collections.leaveCollection(user.id, body.collection_id, socketId);
return { success: true };
}
@Post('members/remove')
@HttpCode(200)
removeMember(@CurrentUser() user: User, @Body() body: CollectionRemoveMemberDto) {
this.collections.assertAccess(user.id, body.collection_id); // 404 if not visible
if (!this.collections.isOwner(user.id, body.collection_id)) {
async removeMember(@CurrentUser() user: User, @Body() body: CollectionRemoveMemberDto) {
await this.collections.assertAccess(user.id, body.collection_id); // 404 if not visible
if (!(await this.collections.isOwner(user.id, body.collection_id))) {
throw new HttpException({ error: 'Only the owner can remove members' }, 403);
}
this.collections.removeMember(user.id, body.collection_id, body.user_id);
await this.collections.removeMember(user.id, body.collection_id, body.user_id);
return { success: true };
}
@Post('members/role')
@HttpCode(200)
setMemberRole(@CurrentUser() user: User, @Body() body: CollectionSetMemberRoleDto) {
this.collections.assertAccess(user.id, body.collection_id); // 404 if not visible
if (!this.collections.isOwner(user.id, body.collection_id)) {
async setMemberRole(@CurrentUser() user: User, @Body() body: CollectionSetMemberRoleDto) {
await this.collections.assertAccess(user.id, body.collection_id); // 404 if not visible
if (!(await this.collections.isOwner(user.id, body.collection_id))) {
throw new HttpException({ error: 'Only the owner can change member roles' }, 403);
}
this.collections.setMemberRole(user.id, body.collection_id, body.user_id, body.role);
await this.collections.setMemberRole(user.id, body.collection_id, body.user_id, body.role);
return { success: true };
}
// ── /:id (declared last so static prefixes win) ─────────────────────────────
@Get(':id/available-users')
availableUsers(@CurrentUser() user: User, @Param('id') id: string) {
this.collections.assertAccess(user.id, Number(id)); // 404 if not visible (no enumeration)
if (!this.collections.isOwner(user.id, Number(id))) {
async availableUsers(@CurrentUser() user: User, @Param('id') id: string) {
await this.collections.assertAccess(user.id, Number(id)); // 404 if not visible (no enumeration)
if (!(await this.collections.isOwner(user.id, Number(id)))) {
throw new HttpException({ error: 'Only the owner can manage members' }, 403);
}
return { users: this.collections.availableUsers(user.id, Number(id)) };
return { users: await this.collections.availableUsers(user.id, Number(id)) };
}
@Post(':id/cover')
@@ -458,8 +458,8 @@ export class CollectionsController {
}
@Delete(':id')
remove(@CurrentUser() user: User, @Param('id') id: string) {
this.collections.deleteCollection(user.id, Number(id));
async remove(@CurrentUser() user: User, @Param('id') id: string) {
await this.collections.deleteCollection(user.id, Number(id));
return { success: true };
}
}
+26 -26
View File
@@ -77,7 +77,7 @@ export class CollectionsMcp {
access: { group: 'collections', mode: 'read' },
})
async listCollections(_args: Record<string, never>, ctx: McpContext) {
try { return ok(this.collections.listCollections(ctx.userId)); } catch (err) { return fail(err); }
try { return ok(await this.collections.listCollections(ctx.userId)); } catch (err) { return fail(err); }
}
@Tool({
@@ -89,7 +89,7 @@ export class CollectionsMcp {
access: { group: 'collections', mode: 'read' },
})
async getCollection({ collectionId }: { collectionId: number }, ctx: McpContext) {
try { return ok(this.collections.getCollection(ctx.userId, collectionId)); } catch (err) { return fail(err); }
try { return ok(await this.collections.getCollection(ctx.userId, collectionId)); } catch (err) { return fail(err); }
}
@Tool({
@@ -104,11 +104,11 @@ export class CollectionsMcp {
try {
// Owner-only, mirroring the REST gate — availableUsers() itself does no
// access check, so without this any token could enumerate the user list.
this.collections.assertAccess(ctx.userId, collectionId);
if (!this.collections.isOwner(ctx.userId, collectionId)) {
await this.collections.assertAccess(ctx.userId, collectionId);
if (!(await this.collections.isOwner(ctx.userId, collectionId))) {
return { content: [{ type: 'text' as const, text: 'Only the collection owner can view invitable users.' }], isError: true };
}
return ok({ users: this.collections.availableUsers(ctx.userId, collectionId) });
return ok({ users: await this.collections.availableUsers(ctx.userId, collectionId) });
} catch (err) { return fail(err); }
}
@@ -130,7 +130,7 @@ export class CollectionsMcp {
query: { google_place_id?: string; google_ftid?: string; name?: string; lat?: number; lng?: number },
ctx: McpContext,
) {
try { return ok(this.collections.findMembership(ctx.userId, query)); } catch (err) { return fail(err); }
try { return ok(await this.collections.findMembership(ctx.userId, query)); } catch (err) { return fail(err); }
}
// ── Collections CRUD ─────────────────────────────────────────────────
@@ -145,7 +145,7 @@ export class CollectionsMcp {
})
async createCollection(body: CollectionCreateRequest, ctx: McpContext) {
const demo = await this.denyDemo(ctx.userId); if (demo) return demo;
try { return ok({ collection: this.collections.createCollection(ctx.userId, body) }); } catch (err) { return fail(err); }
try { return ok({ collection: await this.collections.createCollection(ctx.userId, body) }); } catch (err) { return fail(err); }
}
@Tool({
@@ -158,7 +158,7 @@ export class CollectionsMcp {
})
async updateCollection({ collectionId, ...body }: { collectionId: number } & CollectionUpdateRequest, ctx: McpContext) {
const demo = await this.denyDemo(ctx.userId); if (demo) return demo;
try { return ok({ collection: this.collections.updateCollection(ctx.userId, collectionId, body) }); } catch (err) { return fail(err); }
try { return ok({ collection: await this.collections.updateCollection(ctx.userId, collectionId, body) }); } catch (err) { return fail(err); }
}
@Tool({
@@ -171,7 +171,7 @@ export class CollectionsMcp {
})
async deleteCollection({ collectionId }: { collectionId: number }, ctx: McpContext) {
const demo = await this.denyDemo(ctx.userId); if (demo) return demo;
try { this.collections.deleteCollection(ctx.userId, collectionId); return ok({ success: true }); } catch (err) { return fail(err); }
try { await this.collections.deleteCollection(ctx.userId, collectionId); return ok({ success: true }); } catch (err) { return fail(err); }
}
@Tool({
@@ -184,7 +184,7 @@ export class CollectionsMcp {
})
async reorderCollections({ orderedIds }: { orderedIds: number[] }, ctx: McpContext) {
const demo = await this.denyDemo(ctx.userId); if (demo) return demo;
try { this.collections.reorderCollections(ctx.userId, orderedIds); return ok({ success: true }); } catch (err) { return fail(err); }
try { await this.collections.reorderCollections(ctx.userId, orderedIds); return ok({ success: true }); } catch (err) { return fail(err); }
}
// ── Places ────────────────────────────────────────────────────────────
@@ -199,7 +199,7 @@ export class CollectionsMcp {
})
async savePlaceToCollection(body: CollectionSavePlaceRequest, ctx: McpContext) {
const demo = await this.denyDemo(ctx.userId); if (demo) return demo;
try { return ok(this.collections.savePlace(ctx.userId, body)); } catch (err) { return fail(err); }
try { return ok(await this.collections.savePlace(ctx.userId, body)); } catch (err) { return fail(err); }
}
@Tool({
@@ -220,7 +220,7 @@ export class CollectionsMcp {
ctx: McpContext,
) {
const demo = await this.denyDemo(ctx.userId); if (demo) return demo;
try { return ok(this.collections.saveFromTripPlaces(ctx.userId, collectionId, tripId, placeIds, force)); } catch (err) { return fail(err); }
try { return ok(await this.collections.saveFromTripPlaces(ctx.userId, collectionId, tripId, placeIds, force)); } catch (err) { return fail(err); }
}
@Tool({
@@ -246,7 +246,7 @@ export class CollectionsMcp {
})
async setCollectionPlaceStatus({ placeId, status }: { placeId: number; status: CollectionStatus }, ctx: McpContext) {
const demo = await this.denyDemo(ctx.userId); if (demo) return demo;
try { return ok({ place: this.collections.setStatus(ctx.userId, placeId, status) }); } catch (err) { return fail(err); }
try { return ok({ place: await this.collections.setStatus(ctx.userId, placeId, status) }); } catch (err) { return fail(err); }
}
@Tool({
@@ -262,7 +262,7 @@ export class CollectionsMcp {
ctx: McpContext,
) {
const demo = await this.denyDemo(ctx.userId); if (demo) return demo;
try { return ok(this.collections.setStatusFromTrip(ctx.userId, trip_id, place_ids, status)); } catch (err) { return fail(err); }
try { return ok(await this.collections.setStatusFromTrip(ctx.userId, trip_id, place_ids, status)); } catch (err) { return fail(err); }
}
@Tool({
@@ -278,7 +278,7 @@ export class CollectionsMcp {
})
async rateCollectionPlace({ placeId, rating }: { placeId: number; rating?: number | null }, ctx: McpContext) {
const demo = await this.denyDemo(ctx.userId); if (demo) return demo;
try { return ok({ place: this.collections.setRating(ctx.userId, placeId, rating ?? null) }); } catch (err) { return fail(err); }
try { return ok({ place: await this.collections.setRating(ctx.userId, placeId, rating ?? null) }); } catch (err) { return fail(err); }
}
@Tool({
@@ -319,7 +319,7 @@ export class CollectionsMcp {
})
async createCollectionLabel({ collection_id, name, color }: CollectionLabelCreateRequest, ctx: McpContext) {
const demo = await this.denyDemo(ctx.userId); if (demo) return demo;
try { return ok({ label: this.collections.createLabel(ctx.userId, collection_id, name, color) }); } catch (err) { return fail(err); }
try { return ok({ label: await this.collections.createLabel(ctx.userId, collection_id, name, color) }); } catch (err) { return fail(err); }
}
@Tool({
@@ -332,7 +332,7 @@ export class CollectionsMcp {
})
async updateCollectionLabel({ labelId, ...body }: { labelId: number } & CollectionLabelUpdateRequest, ctx: McpContext) {
const demo = await this.denyDemo(ctx.userId); if (demo) return demo;
try { return ok({ label: this.collections.updateLabel(ctx.userId, labelId, body) }); } catch (err) { return fail(err); }
try { return ok({ label: await this.collections.updateLabel(ctx.userId, labelId, body) }); } catch (err) { return fail(err); }
}
@Tool({
@@ -345,7 +345,7 @@ export class CollectionsMcp {
})
async deleteCollectionLabel({ labelId }: { labelId: number }, ctx: McpContext) {
const demo = await this.denyDemo(ctx.userId); if (demo) return demo;
try { this.collections.deleteLabel(ctx.userId, labelId); return ok({ success: true }); } catch (err) { return fail(err); }
try { await this.collections.deleteLabel(ctx.userId, labelId); return ok({ success: true }); } catch (err) { return fail(err); }
}
@Tool({
@@ -361,7 +361,7 @@ export class CollectionsMcp {
ctx: McpContext,
) {
const demo = await this.denyDemo(ctx.userId); if (demo) return demo;
try { return ok(this.collections.assignLabels(ctx.userId, label_ids, place_ids, remove ?? false)); } catch (err) { return fail(err); }
try { return ok(await this.collections.assignLabels(ctx.userId, label_ids, place_ids, remove ?? false)); } catch (err) { return fail(err); }
}
// ── Sharing ───────────────────────────────────────────────────────────
@@ -380,7 +380,7 @@ export class CollectionsMcp {
// of two where an unexpected throw escaped to the SDK instead of isError.
try {
const me = this.db.get<{ username: string; email: string }>('SELECT username, email FROM users WHERE id = ?', ctx.userId);
const res = this.collections.sendInvite(collection_id, ctx.userId, me?.username ?? '', me?.email ?? '', user_id, role);
const res = await this.collections.sendInvite(collection_id, ctx.userId, me?.username ?? '', me?.email ?? '', user_id, role);
if (res.error) return { content: [{ type: 'text' as const, text: res.error }], isError: true };
return ok({ success: true });
} catch (err) { return fail(err); }
@@ -403,7 +403,7 @@ export class CollectionsMcp {
ctx: McpContext,
) {
const demo = await this.denyDemo(ctx.userId); if (demo) return demo;
try { this.collections.setMemberRole(ctx.userId, collectionId, targetUserId, role); return ok({ success: true }); } catch (err) { return fail(err); }
try { await this.collections.setMemberRole(ctx.userId, collectionId, targetUserId, role); return ok({ success: true }); } catch (err) { return fail(err); }
}
@Tool({
@@ -419,7 +419,7 @@ export class CollectionsMcp {
ctx: McpContext,
) {
const demo = await this.denyDemo(ctx.userId); if (demo) return demo;
try { this.collections.removeMember(ctx.userId, collectionId, targetUserId); return ok({ success: true }); } catch (err) { return fail(err); }
try { await this.collections.removeMember(ctx.userId, collectionId, targetUserId); return ok({ success: true }); } catch (err) { return fail(err); }
}
@Tool({
@@ -435,7 +435,7 @@ export class CollectionsMcp {
ctx: McpContext,
) {
const demo = await this.denyDemo(ctx.userId); if (demo) return demo;
try { this.collections.cancelInvite(collectionId, ctx.userId, targetUserId); return ok({ success: true }); } catch (err) { return fail(err); }
try { await this.collections.cancelInvite(collectionId, ctx.userId, targetUserId); return ok({ success: true }); } catch (err) { return fail(err); }
}
@Tool({
@@ -450,7 +450,7 @@ export class CollectionsMcp {
const demo = await this.denyDemo(ctx.userId); if (demo) return demo;
// try/catch added with the post-fold quirk pass (see inviteToCollection).
try {
const res = this.collections.acceptInvite(ctx.userId, collectionId, undefined);
const res = await this.collections.acceptInvite(ctx.userId, collectionId, undefined);
if (res.error) return { content: [{ type: 'text' as const, text: res.error }], isError: true };
return ok({ success: true });
} catch (err) { return fail(err); }
@@ -466,7 +466,7 @@ export class CollectionsMcp {
})
async declineCollectionInvite({ collectionId }: { collectionId: number }, ctx: McpContext) {
const demo = await this.denyDemo(ctx.userId); if (demo) return demo;
try { this.collections.declineInvite(ctx.userId, collectionId, undefined); return ok({ success: true }); } catch (err) { return fail(err); }
try { await this.collections.declineInvite(ctx.userId, collectionId, undefined); return ok({ success: true }); } catch (err) { return fail(err); }
}
@Tool({
@@ -479,6 +479,6 @@ export class CollectionsMcp {
})
async leaveCollection({ collectionId }: { collectionId: number }, ctx: McpContext) {
const demo = await this.denyDemo(ctx.userId); if (demo) return demo;
try { this.collections.leaveCollection(ctx.userId, collectionId, undefined); return ok({ success: true }); } catch (err) { return fail(err); }
try { await this.collections.leaveCollection(ctx.userId, collectionId, undefined); return ok({ success: true }); } catch (err) { return fail(err); }
}
}
@@ -87,9 +87,9 @@ export class CollectionsRpc {
const userId = this.requireCollectionsUser(ctx, 'writes');
const placeId = num(params.placeId, 'placeId');
await this.requireCollectionsAddon();
// deletePlace is async (it deletes the underlying storage object): await it so a
// refusal actually reaches the plugin as RESOURCE_FORBIDDEN/BAD_PARAMS instead of
// being dropped as an unhandled rejection while this returns {deleted: true} anyway.
// Awaited so a refusal actually reaches the plugin as RESOURCE_FORBIDDEN/BAD_PARAMS
// instead of being dropped as an unhandled rejection while this returns
// {deleted: true} anyway.
await this.mapCollectionError(() => this.collections.deletePlace(userId, placeId, undefined));
return { deleted: true };
}
@@ -108,9 +108,8 @@ export class CollectionsRpc {
/**
* The service's status-tagged errors, mapped onto the RPC error taxonomy.
*
* Async-aware: `deletePlace` is async (it deletes the underlying storage object),
* while `create`/`update`/`savePlace`/`copyToTrip` stay sync. Awaiting inside always
* works for both — a sync throw from `fn()` is caught by this function's own
* Async-aware: every service method it wraps is async. Awaiting inside works for
* a sync callback too — a sync throw from `fn()` is caught by this function's own
* try/catch same as an awaited rejection — so every caller goes through one path.
*/
private async mapCollectionError<T>(fn: () => T | Promise<T>): Promise<T> {
File diff suppressed because it is too large Load Diff
+3 -3
View File
@@ -142,7 +142,7 @@ export class MapsController {
@CurrentUser() user: User,
@Body() body: MapsAutocompleteDto,
): Promise<MapsAutocompleteResult | { suggestions: never[]; source: string }> {
if (this.maps.autocompleteDisabled()) {
if (await this.maps.autocompleteDisabled()) {
return { suggestions: [], source: 'disabled' };
}
try {
@@ -165,7 +165,7 @@ export class MapsController {
// breaking the lookup.
@Query('sessionToken') sessionToken?: string,
): Promise<MapsPlaceDetailsResult> {
if (this.maps.detailsDisabled()) {
if (await this.maps.detailsDisabled()) {
return { place: null, disabled: true };
}
try {
@@ -187,7 +187,7 @@ export class MapsController {
@Query('name') name?: string,
): Promise<MapsPlacePhotoResult | { photoUrl: null }> {
// Kill-switch only applies to Google Places fetches — Wikimedia (coords:) stays allowed.
if (!placeId.startsWith('coords:') && this.maps.photosDisabled()) {
if (!placeId.startsWith('coords:') && (await this.maps.photosDisabled())) {
return { photoUrl: null };
}
// A place with no photo resolves to the same { photoUrl: null } body. It is an
+1 -1
View File
@@ -36,7 +36,7 @@ export class MapsMcp {
// assistant reaching the provider anyway would bill them from the one
// surface the switch does not cover. REST answers { place: null, disabled }
// rather than an error, so this does too, with a line the model can act on.
if (this.maps.detailsDisabled()) {
if (await this.maps.detailsDisabled()) {
return ok({
details: null,
disabled: true,
+6 -6
View File
@@ -696,7 +696,7 @@ export class MapsService {
* oldest entry is the one evicted when it fills up. */
private readonly brandLogoCache = new Map<string, { at: number; logo: BrandLogo | null }>();
private isSettingDisabled(key: string): boolean {
private async isSettingDisabled(key: string): Promise<boolean> {
const row = this.database.get<{ value: string }>(
'SELECT value FROM app_settings WHERE key = ?',
key,
@@ -747,15 +747,15 @@ export class MapsService {
}
}
autocompleteDisabled(): boolean {
autocompleteDisabled(): Promise<boolean> {
return this.isSettingDisabled('places_autocomplete_enabled');
}
detailsDisabled(): boolean {
detailsDisabled(): Promise<boolean> {
return this.isSettingDisabled('places_details_enabled');
}
photosDisabled(): boolean {
photosDisabled(): Promise<boolean> {
return this.isSettingDisabled('places_photos_enabled');
}
@@ -1023,7 +1023,7 @@ export class MapsService {
* is read on the hot path of every search, and a hand-edited settings row must
* not take place search down.
*/
placesProviderChoice(): PlacesProviderChoice {
async placesProviderChoice(): Promise<PlacesProviderChoice> {
const row = this.database.get<{ value: string }>(
'SELECT value FROM app_settings WHERE key = ?',
PLACES_PROVIDER_SETTING,
@@ -1047,7 +1047,7 @@ export class MapsService {
* the database reads it always did.
*/
async keyedProvider(userId: number): Promise<KeyedProvider | null> {
const choice = this.placesProviderChoice();
const choice = await this.placesProviderChoice();
if (choice === 'openstreetmap') return null;
if (choice !== 'amap') {
@@ -449,7 +449,7 @@ export class PlaceEnrichmentService {
details: Record<string, unknown> | null,
): Promise<PlacePhotoCandidate[]> {
const apiKey = await this.maps.getMapsKey(userId);
const wantsGoogle = !!apiKey && !this.maps.photosDisabled() && isGooglePlaceId(placeId);
const wantsGoogle = !!apiKey && !(await this.maps.photosDisabled()) && isGooglePlaceId(placeId);
const { wikidata, wikipedia } = identity;
@@ -694,7 +694,7 @@ export class PlaceEnrichmentService {
if (fromSite) return fromSite;
const apiKey = await this.maps.getMapsKey(userId);
if (apiKey && !this.maps.detailsDisabled() && isGooglePlaceId(placeId)) {
if (apiKey && !(await this.maps.detailsDisabled()) && isGooglePlaceId(placeId)) {
const summary = await this.maps.fetchEditorialSummary(placeId, apiKey, req.lang);
if (summary) {
return {
@@ -80,7 +80,7 @@ export class TripReadModelService {
};
const reservations = this.reservations.list(tripId);
const collab_notes = this.collab.listNotes(tripId);
const collab_notes = await this.collab.listNotes(tripId);
return {
trip,
+2 -2
View File
@@ -284,8 +284,8 @@ export class TripsMcp {
let pollCount = 0;
let messageCount = 0;
if (canReadCollab) {
if (collabFeatures?.polls) pollCount = this.collab.listPolls(tripId).length;
if (collabFeatures?.chat) messageCount = this.collab.countMessages(tripId);
if (collabFeatures?.polls) pollCount = (await this.collab.listPolls(tripId)).length;
if (collabFeatures?.chat) messageCount = await this.collab.countMessages(tripId);
}
const notice = ctx.getDeprecationNotice ? ctx.getDeprecationNotice() : null;
// The core bucket (trip metadata, members WITH email, days with place