-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathout.txt
More file actions
1620 lines (1346 loc) · 48.3 KB
/
out.txt
File metadata and controls
1620 lines (1346 loc) · 48.3 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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
===== friends/dto/create-friend-request.dto.ts =====
import { IsInt } from 'class-validator';
export class CreateFriendRequestDto {
@IsInt()
recipientId!: number;
}
===== friends/dto/handle-request.dto.ts =====
import { IsEnum } from 'class-validator';
export class HandleRequestDto {
@IsEnum(['accepted', 'declined'])
status!: 'accepted' | 'declined';
}
===== friends/friends.module.ts =====
import { Module } from '@nestjs/common';
import { FriendsService } from './friends.service';
import { FriendsController } from './friends.controller';
import { UsersModule } from '../users/users.module';
import { ReadingModule } from '../reading/reading.module';
@Module({
imports: [UsersModule, ReadingModule],
controllers: [FriendsController],
providers: [FriendsService],
})
export class FriendsModule {}
===== friends/friends.service.ts =====
import { Injectable, BadRequestException, NotFoundException, ForbiddenException } from '@nestjs/common';
import { DatabaseService } from '../database/database.service';
import { UsersService } from '../users/users.service';
import { ReadingService } from '../reading/reading.service';
@Injectable()
export class FriendsService {
constructor(
private readonly db: DatabaseService,
private readonly users: UsersService,
private readonly reading: ReadingService,
) {}
requestFriend(senderId: number, recipientId: number) {
if (senderId === recipientId) {
throw new BadRequestException('Cannot send a friend request to yourself.');
}
this.users.findOne(senderId);
this.users.findOne(recipientId);
const requests = this.db.getFriendRequests();
const alreadyPending = requests.some(
(r) => r.senderId === senderId && r.recipientId === recipientId && r.status === 'pending',
);
if (alreadyPending) {
throw new BadRequestException('A pending request already exists.');
}
const id = (requests.length ? Math.max(...requests.map((r) => r.id)) : 0) + 1;
const newReq = { id, senderId, recipientId, status: 'pending' as const };
requests.push(newReq);
return newReq;
}
getIncomingRequests(userId: number) {
return this.db
.getFriendRequests()
.filter((r) => r.recipientId === userId && r.status === 'pending');
}
handleRequest(actingUserId: number, requestId: number, status: 'accepted' | 'declined') {
const req = this.db.getFriendRequests().find((r) => r.id === requestId);
if (!req) throw new NotFoundException('Friend request not found.');
if (req.status !== 'pending') throw new BadRequestException('Request already handled.');
if (req.recipientId !== actingUserId)
throw new ForbiddenException('Only the recipient can act on this request.');
req.status = status;
if (status === 'accepted') {
const sender = this.users.findOne(req.senderId);
const recipient = this.users.findOne(req.recipientId);
if (!sender.friendIds.includes(recipient.id)) sender.friendIds.push(recipient.id);
if (!recipient.friendIds.includes(sender.id)) recipient.friendIds.push(sender.id);
}
return req;
}
getFriendProgress(requesterId: number, friendId: number) {
const requester = this.users.findOne(requesterId);
if (!requester.friendIds.includes(friendId)) {
throw new ForbiddenException('You can only view progress of your friends.');
}
return this.reading.findAllForUser(friendId);
}
}
===== friends/friends.controller.ts =====
import { Controller, Post, Body, Get, Patch, Param, ParseIntPipe } from '@nestjs/common';
import { FriendsService } from './friends.service';
import { CreateFriendRequestDto } from './dto/create-friend-request.dto';
import { HandleRequestDto } from './dto/handle-request.dto';
import { CurrentUser, TokenUser } from '../common/decorators/current-user.decorator';
@Controller('friends')
export class FriendsController {
constructor(private readonly friends: FriendsService) {}
@Post('request')
requestFriend(@CurrentUser() user: TokenUser, @Body() dto: CreateFriendRequestDto) {
return this.friends.requestFriend(user.userId, dto.recipientId);
}
@Get('requests')
getIncoming(@CurrentUser() user: TokenUser) {
return this.friends.getIncomingRequests(user.userId);
}
@Patch('requests/:requestId')
handle(
@CurrentUser() user: TokenUser,
@Param('requestId', ParseIntPipe) requestId: number,
@Body() dto: HandleRequestDto,
) {
return this.friends.handleRequest(user.userId, requestId, dto.status);
}
@Get(':friendId/progress')
getFriendProgress(
@CurrentUser() user: TokenUser,
@Param('friendId', ParseIntPipe) friendId: number,
) {
return this.friends.getFriendProgress(user.userId, friendId);
}
}
===== users/dto/create-user.dto.ts =====
import { IsString, IsNotEmpty } from 'class-validator';
export class CreateUserDto {
@IsString()
@IsNotEmpty()
name!: string;
}
===== users/dto/update-user.dto.ts =====
import { IsOptional, IsString } from 'class-validator';
export class UpdateUserDto {
@IsOptional()
@IsString()
name?: string;
@IsOptional()
@IsString()
username?: string;
}
===== users/users.module.ts =====
import { Module } from '@nestjs/common';
import { UsersService } from './users.service';
import { UsersController } from './users.controller';
import { ReadingModule } from '../reading/reading.module';
@Module({
imports: [ReadingModule],
controllers: [UsersController],
providers: [UsersService],
exports: [UsersService],
})
export class UsersModule {}
===== users/users.controller.ts =====
import { Controller, Get, Post, Body, Patch, Param, Delete, ParseIntPipe, UseGuards } from '@nestjs/common';
import { UsersService } from './users.service';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { Roles } from '../common/decorators/roles.decorator';
import { RolesGuard } from '../common/guards/roles.guard';
import { Public } from '../common/decorators/public.decorator';
@Controller('users')
export class UsersController {
constructor(private readonly usersService: UsersService) {}
@Get()
@Public()
// Return a list of all users
findAll() {
return this.usersService.findAll();
}
@Get(':id')
@Public()
// Retrieve a single user by ID
findOne(@Param('id', ParseIntPipe) id: number) {
return this.usersService.findOne(id);
}
@Post()
// Create a new user
create(@Body() createUserDto: CreateUserDto) {
return this.usersService.create(createUserDto);
}
@Patch(':id')
// Update an existing user
@UseGuards(RolesGuard)
@Roles('admin')
update(@Param('id', ParseIntPipe) id: number, @Body() updateUserDto: UpdateUserDto) {
return this.usersService.update(id, updateUserDto);
}
@Delete(':id')
// Remove a user
@UseGuards(RolesGuard)
@Roles('admin')
remove(@Param('id', ParseIntPipe) id: number) {
return this.usersService.remove(id);
}
// NEW: list a user's friends
@Get(':id/friends')
findFriends(@Param('id', ParseIntPipe) id: number) {
return this.usersService.findFriends(id);
}
// NEW: user stats (auth required by default global guard)
@Get(':id/stats')
getStats(@Param('id', ParseIntPipe) id: number) {
return this.usersService.getStats(id);
}
}
===== users/users.service.ts =====
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { DatabaseService } from '../database/database.service';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { hashPassword } from '../utils/auth.utils';
import { ReadingService } from '../reading/reading.service';
@Injectable()
export class UsersService {
constructor(private readonly db: DatabaseService, private readonly reading: ReadingService) {}
/**
* Retrieve all users.
*/
findAll() {
return this.db.getUsers();
}
/**
* Find a user by ID.
* @throws NotFoundException if user does not exist.
*/
findOne(id: number) {
const user = this.db.findUserById(id);
if (!user) {
throw new NotFoundException(`User with ID ${id} not found.`);
}
return user;
}
/**
* Create a new user with provided data.
*/
create(createUserDto: CreateUserDto) {
const users = this.db.getUsers();
const id = Math.max(0, ...users.map(u => u.id)) + 1;
let base = (createUserDto.name || `user${id}`).toLowerCase().replace(/\s+/g, '');
if (!base) base = `user${id}`;
let username = base;
let suffix = 1;
const usernames = new Set(users.map(u => u.username));
while (usernames.has(username)) {
username = `${base}${suffix++}`;
}
const newUser = {
id,
name: createUserDto.name,
username,
passwordHash: hashPassword('changeme'),
role: 'user' as const,
friendIds: [] as number[],
};
users.push(newUser);
return newUser;
}
/**
* Update an existing user.
*/
update(id: number, updateUserDto: UpdateUserDto) {
const user = this.findOne(id);
if (updateUserDto.username && updateUserDto.username !== user.username) {
const exists = this.db.getUsers().some(u => u.username === updateUserDto.username && u.id !== id);
if (exists) {
throw new BadRequestException('Username already exists');
}
user.username = updateUserDto.username;
}
if (typeof updateUserDto.name === 'string' && updateUserDto.name.length) {
user.name = updateUserDto.name;
}
return user;
}
/**
* Remove a user by ID.
*/
remove(id: number) {
const users = this.db.getUsers();
const index = users.findIndex((u) => u.id === id);
if (index === -1) {
throw new NotFoundException(`User with ID ${id} not found.`);
}
const [removedUser] = users.splice(index, 1);
return removedUser;
}
/**
* Get a list of a user's friends (as full user objects).
*/
findFriends(userId: number) {
const user = this.findOne(userId);
return user.friendIds.map(fid => this.findOne(fid));
}
getStats(userId: number) {
this.findOne(userId);
const sessions = this.reading.findAllForUser(userId);
const books = this.db.getBooks() as any[];
const totalPagesRead = sessions.reduce((sum: number, s: any) => sum + s.currentPage, 0);
let booksCompleted = 0;
let denom = 0;
for (const s of sessions as any[]) {
const b = books.find((bb: any) => bb.id === s.bookId);
if (!b || !b.totalPages) continue;
denom += b.totalPages;
if (s.currentPage >= b.totalPages) booksCompleted += 1;
}
const avgProgressPct = denom > 0 ? totalPagesRead / denom : 0;
return {
userId,
totalPagesRead,
booksInShelf: sessions.length,
booksCompleted,
avgProgressPct,
};
}
}
===== common/decorators/public.decorator.ts =====
import { SetMetadata } from '@nestjs/common';
export const IS_PUBLIC_KEY = 'isPublic';
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);
===== common/decorators/roles.decorator.ts =====
import { SetMetadata } from '@nestjs/common';
export const ROLES_KEY = 'roles';
export type Role = 'user' | 'admin';
export const Roles = (...roles: Role[]) => SetMetadata(ROLES_KEY, roles);
===== common/decorators/current-user.decorator.ts =====
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
export interface TokenUser {
userId: number;
role: 'user' | 'admin';
}
export const CurrentUser = createParamDecorator(
(_data: unknown, ctx: ExecutionContext): TokenUser | undefined => {
const req = ctx.switchToHttp().getRequest() as any;
return req.user as TokenUser | undefined;
},
);
===== common/logs/logs.service.ts =====
import { Injectable } from '@nestjs/common';
export interface RequestLog {
method: string;
url: string;
status: number;
ms: number;
at: string;
}
@Injectable()
export class LogsService {
private buffer: RequestLog[] = [];
private readonly max = 100;
add(entry: RequestLog) {
this.buffer.push(entry);
if (this.buffer.length > this.max) this.buffer.shift();
}
list(limit = 20) {
return this.buffer.slice(-limit).reverse();
}
}
===== common/guards/owner-or-admin.guard.ts =====
import { CanActivate, ExecutionContext, ForbiddenException, Injectable } from '@nestjs/common';
@Injectable()
export class OwnerOrAdminGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
const req = context.switchToHttp().getRequest() as any;
const user = req.user as { userId: number; role: 'user' | 'admin' } | undefined;
if (!user) return false; // Global JWT guard should set this
if (user.role === 'admin') return true;
const bodyUserId = Number(req.body?.userId);
if (user.userId !== bodyUserId) {
throw new ForbiddenException('You can only modify your own progress');
}
return true;
}
}
===== common/guards/jwt-auth.guard.ts =====
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { verifyJwt } from '../../auth/jwt.util';
@Injectable()
export class JwtAuthGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean | Promise<boolean> {
const req = context.switchToHttp().getRequest() as any;
const auth = req.headers['authorization'] as string | undefined;
if (!auth || !auth.startsWith('Bearer ')) {
throw new UnauthorizedException('Missing token');
}
const token = auth.substring('Bearer '.length);
const payload = verifyJwt(token);
if (!payload) {
throw new UnauthorizedException('Invalid token');
}
req.user = { userId: payload.sub, role: payload.role };
return true;
}
}
===== common/guards/global-jwt-auth.guard.ts =====
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { IS_PUBLIC_KEY } from '../decorators/public.decorator';
import { verifyJwt } from '../../auth/jwt.util';
@Injectable()
export class GlobalJwtAuthGuard implements CanActivate {
constructor(private readonly reflector: Reflector) {}
canActivate(ctx: ExecutionContext): boolean {
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
ctx.getHandler(),
ctx.getClass(),
]);
if (isPublic) return true;
const req = ctx.switchToHttp().getRequest() as any;
const auth = req.headers['authorization'] as string | undefined;
if (!auth?.startsWith('Bearer ')) {
throw new UnauthorizedException('Missing token');
}
const token = auth.slice(7);
const payload = verifyJwt(token);
if (!payload) throw new UnauthorizedException('Invalid token');
req.user = { userId: payload.sub, role: payload.role };
return true;
}
}
===== common/guards/roles.guard.ts =====
import { CanActivate, ExecutionContext, ForbiddenException, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { ROLES_KEY, Role } from '../decorators/roles.decorator';
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private readonly reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const required = this.reflector.getAllAndOverride<Role[]>(ROLES_KEY, [
context.getHandler(),
context.getClass(),
]);
if (!required || required.length === 0) return true;
const req = context.switchToHttp().getRequest() as any;
const role = req.user?.role as Role | undefined;
if (!role || !required.includes(role)) {
throw new ForbiddenException('Insufficient role');
}
return true;
}
}
===== common/interceptors/transform.interceptor.ts =====
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
interface Envelope<T> {
data: T;
meta?: { count?: number; timestamp?: string };
}
@Injectable()
export class TransformInterceptor<T> implements NestInterceptor<T, Envelope<T>> {
intercept(_context: ExecutionContext, next: CallHandler): Observable<Envelope<T>> {
return next.handle().pipe(
map((payload: any) => {
const meta: Envelope<T>['meta'] = { timestamp: new Date().toISOString() };
if (Array.isArray(payload)) meta.count = payload.length;
return { data: payload, meta };
}),
);
}
}
===== common/interceptors/logging.interceptor.ts =====
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { Response } from 'express';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { LogsService } from '../logs/logs.service';
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
constructor(private readonly logs: LogsService) {}
intercept(ctx: ExecutionContext, next: CallHandler): Observable<any> {
const http = ctx.switchToHttp();
const req = http.getRequest<Request>();
const res = http.getResponse<Response>();
const method = (req as any).method;
const url = (req as any).originalUrl || (req as any).url;
const start = Date.now();
return next.handle().pipe(
tap(() => {
this.logs.add({
method,
url,
status: (res as any).statusCode,
ms: Date.now() - start,
at: new Date().toISOString(),
});
}),
);
}
}
===== common/filters/http-exception.filter.ts =====
import { ArgumentsHost, Catch, ExceptionFilter, HttpException } from '@nestjs/common';
import { Request, Response } from 'express';
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const res = ctx.getResponse<Response>();
const req = ctx.getRequest<Request>();
const status = exception.getStatus();
const raw = exception.getResponse();
const message = typeof raw === 'string' ? raw : (raw as any)?.message;
res.status(status).json({
error: {
statusCode: status,
message: Array.isArray(message) ? message.join(', ') : message,
path: req.url,
timestamp: new Date().toISOString(),
},
});
}
}
===== books/dto/create-book.dto.ts =====
import { IsString, IsNotEmpty, IsInt, Min, IsOptional, IsISO8601 } from 'class-validator';
export class CreateBookDto {
@IsString()
@IsNotEmpty()
title!: string;
@IsString()
@IsNotEmpty()
author!: string;
@IsInt()
@Min(1)
totalPages!: number;
@IsOptional()
@IsISO8601()
publishDate?: string;
}
===== books/dto/update-book.dto.ts =====
import { PartialType } from '@nestjs/mapped-types';
import { CreateBookDto } from './create-book.dto';
export class UpdateBookDto extends PartialType(CreateBookDto) {}
===== books/dto/find-all-books.dto.ts =====
import { IsEnum, IsInt, IsOptional, IsString, Min, Max } from 'class-validator';
export class FindAllBooksDto {
@IsOptional()
@IsString()
q?: string; // case-insensitive title/author search
@IsOptional()
@IsEnum(['title', 'author', 'publishDate', 'uploadedAt', 'avgProgress'])
sortBy?: 'title' | 'author' | 'publishDate' | 'uploadedAt' | 'avgProgress';
@IsOptional()
@IsEnum(['asc', 'desc'])
order?: 'asc' | 'desc';
@IsOptional()
@IsInt()
@Min(1)
page?: number;
@IsOptional()
@IsInt()
@Min(1)
@Max(100)
pageSize?: number;
}
===== books/books.module.ts =====
import { Module } from '@nestjs/common';
import { BooksService } from './books.service';
import { BooksController } from './books.controller';
import { RolesGuard } from '../common/guards/roles.guard';
import { JwtAuthGuard } from '../common/guards/jwt-auth.guard';
@Module({
controllers: [BooksController],
providers: [BooksService, RolesGuard, JwtAuthGuard],
exports: [BooksService],
})
export class BooksModule {}
===== books/books.service.ts =====
import { Injectable, NotFoundException } from '@nestjs/common';
import { DatabaseService } from '../database/database.service';
import { CreateBookDto } from './dto/create-book.dto';
import { UpdateBookDto } from './dto/update-book.dto';
@Injectable()
export class BooksService {
constructor(private readonly db: DatabaseService) {}
/**
* Create and store a new book.
*/
create(createBookDto: CreateBookDto) {
const books = this.db.getBooks();
const newBook = {
id: books.length + 1,
...createBookDto,
uploadedAt: new Date().toISOString(),
};
books.push(newBook);
return newBook;
}
/**
* Get books with optional search/sort/pagination.
*/
findAll(query: any) {
const { q, sortBy, order = 'asc', page = 1, pageSize = 20 } = query;
let items = [...this.db.getBooks()];
if (q && String(q).trim().length) {
const needle = String(q).trim().toLowerCase();
items = items.filter(
(b: any) => b.title.toLowerCase().includes(needle) || b.author.toLowerCase().includes(needle),
);
}
// Pre-compute average progress per book for sorting if requested
let avgByBookId = new Map<number, number>();
if (sortBy === 'avgProgress') {
const sessions = this.db.getReadingSessions();
const totals = new Map<number, { readers: number; current: number; totalPages: number }>();
for (const b of items as any[]) totals.set(b.id, { readers: 0, current: 0, totalPages: (b as any).totalPages || 0 });
for (const s of sessions as any[]) {
const agg = totals.get((s as any).bookId);
if (!agg || !agg.totalPages) continue;
agg.readers += 1;
agg.current += (s as any).currentPage;
}
avgByBookId = new Map(
[...totals.entries()].map(([bookId, t]) => [bookId, t.readers ? t.current / (t.totalPages * t.readers) : 0]),
);
}
if (sortBy) {
const dir = order === 'asc' ? 1 : -1;
items.sort((a: any, b: any) => {
const A = sortBy === 'avgProgress' ? (avgByBookId.get(a.id) as any) : String(a[sortBy] ?? '').toLowerCase();
const B = sortBy === 'avgProgress' ? (avgByBookId.get(b.id) as any) : String(b[sortBy] ?? '').toLowerCase();
if (typeof A === 'number' && typeof B === 'number') return A < B ? -1 * dir : A > B ? 1 * dir : 0;
return String(A).localeCompare(String(B)) * dir;
});
}
const total = items.length;
const start = (page - 1) * pageSize;
const paged = items.slice(start, start + pageSize);
return { items: paged, page, pageSize, total };
}
/**
* Get a single book by ID.
* @throws NotFoundException if book is not found.
*/
findOne(id: number) {
const book = this.db.getBooks().find((b: any) => b.id === id);
if (!book) {
throw new NotFoundException(`Book with ID ${id} not found.`);
}
return book;
}
/**
* Update an existing book's information.
*/
update(id: number, updateBookDto: UpdateBookDto) {
const book = this.findOne(id);
Object.assign(book, updateBookDto);
return book;
}
/**
* Remove a book by ID.
*/
remove(id: number) {
const books = this.db.getBooks();
const index = books.findIndex((b: any) => b.id === id);
if (index === -1) {
throw new NotFoundException(`Book with ID ${id} not found.`);
}
const [removedBook] = books.splice(index, 1);
return removedBook;
}
getStats(bookId: number) {
const book: any = this.findOne(bookId);
const sessions = this.db.getReadingSessions().filter((s: any) => s.bookId === bookId);
const readers = sessions.length;
const totalCurrent = sessions.reduce((acc: number, s: any) => acc + s.currentPage, 0);
const avgCurrentPage = readers ? totalCurrent / readers : 0;
const completed = sessions.filter((s: any) => book.totalPages && s.currentPage >= book.totalPages).length;
const completionRate = readers ? completed / readers : 0;
const avgProgressPct = readers && book.totalPages ? totalCurrent / (book.totalPages * readers) : 0;
return { bookId, readers, avgCurrentPage, completionRate, avgProgressPct };
}
}
===== books/books.controller.ts =====
import { Controller, Get, Post, Body, Patch, Param, Delete, ParseIntPipe, UseGuards, Query } from '@nestjs/common';
import { BooksService } from './books.service';
import { CreateBookDto } from './dto/create-book.dto';
import { UpdateBookDto } from './dto/update-book.dto';
import { Roles } from '../common/decorators/roles.decorator';
import { RolesGuard } from '../common/guards/roles.guard';
import { Public } from '../common/decorators/public.decorator';
import { FindAllBooksDto } from './dto/find-all-books.dto';
@Controller('books')
export class BooksController {
constructor(private readonly booksService: BooksService) {}
@Post()
@UseGuards(RolesGuard)
@Roles('admin')
// Create a new book entry (admin only)
create(@Body() createBookDto: CreateBookDto) {
return this.booksService.create(createBookDto);
}
@Get()
@Public()
// Retrieve books with search/sort/pagination
findAll(@Query() query: FindAllBooksDto) {
return this.booksService.findAll(query);
}
@Get(':id')
@Public()
// Retrieve a specific book by ID
findOne(@Param('id', ParseIntPipe) id: number) {
return this.booksService.findOne(id);
}
@Get(':id/stats')
@Public()
// Get aggregated stats for a book
getStats(@Param('id', ParseIntPipe) id: number) {
return this.booksService.getStats(id);
}
@Patch(':id')
@UseGuards(RolesGuard)
@Roles('admin')
// Update a book's data (admin only)
update(
@Param('id', ParseIntPipe) id: number,
@Body() updateBookDto: UpdateBookDto,
) {
return this.booksService.update(id, updateBookDto);
}
@Delete(':id')
@UseGuards(RolesGuard)
@Roles('admin')
// Remove a book by ID (admin only)
remove(@Param('id', ParseIntPipe) id: number) {
return this.booksService.remove(id);
}
}
===== reading/dto/update-progress.dto.ts =====
import { IsInt, Min, IsOptional, IsEnum } from 'class-validator';
export class UpdateProgressDto {
@IsInt()
userId!: number;
@IsInt()
bookId!: number;
@IsInt()
@Min(0)
currentPage!: number;
@IsOptional()
@IsEnum(['not-started', 'in-progress', 'completed', 'want-to-read'])
status?: 'not-started' | 'in-progress' | 'completed' | 'want-to-read';
}
===== reading/dto/find-shelf.dto.ts =====
import { IsEnum, IsOptional } from 'class-validator';
export class FindShelfDto {
@IsOptional()
@IsEnum(['not-started', 'in-progress', 'completed', 'want-to-read'])
status?: 'not-started' | 'in-progress' | 'completed' | 'want-to-read';
@IsOptional()
@IsEnum(['title', 'author', 'updatedAt', 'progress'])
sortBy?: 'title' | 'author' | 'updatedAt' | 'progress';
@IsOptional()
@IsEnum(['asc', 'desc'])
order?: 'asc' | 'desc';
}
===== reading/reading.module.ts =====
import { Module } from '@nestjs/common';
import { ReadingService } from './reading.service';
import { ReadingController } from './reading.controller';
import { BooksModule } from '../books/books.module';
import { OwnerOrAdminGuard } from '../common/guards/owner-or-admin.guard';
@Module({
imports: [BooksModule],
controllers: [ReadingController],
providers: [ReadingService, OwnerOrAdminGuard],
exports: [ReadingService],
})
export class ReadingModule {}
===== reading/reading.controller.ts =====
import { Controller, Patch, Body, Get, Param, ParseIntPipe, UseGuards, Query } from '@nestjs/common';
import { ReadingService } from './reading.service';
import { UpdateProgressDto } from './dto/update-progress.dto';
import { OwnerOrAdminGuard } from '../common/guards/owner-or-admin.guard';
import { CurrentUser, TokenUser } from '../common/decorators/current-user.decorator';
import { Public } from '../common/decorators/public.decorator';
import { FindShelfDto } from './dto/find-shelf.dto';
@Controller('reading')
export class ReadingController {
constructor(private readonly readingService: ReadingService) {}
@Patch('progress')
@UseGuards(OwnerOrAdminGuard)
// Update reading progress for a user and book (auth required)
updateProgress(@CurrentUser() user: TokenUser, @Body() updateProgressDto: UpdateProgressDto) {
// For non-admins, force userId to the token's subject.
// Admins may update any user's progress (userId comes from body).
if (user.role !== 'admin') {
updateProgressDto.userId = user.userId;
}
return this.readingService.updateProgress(updateProgressDto);
}
@Get('progress/:bookId')
@Public()
// Get reading progress for a specific book across all users
getProgress(@Param('bookId', ParseIntPipe) bookId: number) {
return this.readingService.getProgressByBook(bookId);
}
@Get('shelf')
// Get the authenticated user's shelf with optional filters/sorting
getShelf(@CurrentUser() user: TokenUser, @Query() query: FindShelfDto) {
return this.readingService.getShelf(user.userId, query);
}
}
===== reading/reading.service.ts =====
import { Injectable, NotFoundException } from '@nestjs/common';
import { DatabaseService } from '../database/database.service';
import { BooksService } from '../books/books.service';
import { UpdateProgressDto } from './dto/update-progress.dto';
import { FindShelfDto } from './dto/find-shelf.dto';
@Injectable()
export class ReadingService {
constructor(
private readonly db: DatabaseService,
private readonly booksService: BooksService,
) {}
private deriveStatus(currentPage: number, totalPages: number): 'not-started' | 'in-progress' | 'completed' {
if (currentPage <= 0) return 'not-started';
if (totalPages > 0 && currentPage >= totalPages) return 'completed';
return 'in-progress';
}
/**
* Update or create a reading session for a user and book.
*/