feat: add database and orm

This commit is contained in:
2026-10-21 10:14:50 +03:00
parent d8fb486709
commit ef2bc6f8b6
30 changed files with 668 additions and 354 deletions
+8 -7
View File
@@ -1,25 +1,26 @@
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { validate as isUuid } from '../uuid';
import { FastifyRequest } from 'fastify';
import { PrismaService } from '../../db/prisma.service';
import { toUser } from '../../users/users.service';
import { ApiError } from '../filters/api-error';
import { StoreService } from '../store/store.service';
import { validate as isUuid } from '../uuid';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private readonly store: StoreService) {}
constructor(private readonly prisma: PrismaService) {}
canActivate(context: ExecutionContext): boolean {
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<FastifyRequest>();
const header = request.headers['x-user-id'];
const userId = Array.isArray(header) ? header[0] : header;
if (!userId || !isUuid(userId)) {
throw new ApiError('unauthorized', 'Missing or invalid X-User-Id');
}
const user = this.store.getUserById(userId);
if (!user) {
const row = await this.prisma.user.findUnique({ where: { id: userId } });
if (!row) {
throw new ApiError('unauthorized', 'Missing or invalid X-User-Id');
}
request.currentUser = user;
request.currentUser = toUser(row);
return true;
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import { FastifyRequest } from 'fastify';
import { User } from '../store/domain';
import { User } from '../domain';
declare module 'fastify' {
interface FastifyRequest {
+2 -3
View File
@@ -1,10 +1,9 @@
import { Global, Module } from '@nestjs/common';
import { AuthGuard } from './auth/auth.guard';
import { StoreService } from './store/store.service';
@Global()
@Module({
providers: [StoreService, AuthGuard],
exports: [StoreService, AuthGuard],
providers: [AuthGuard],
exports: [AuthGuard],
})
export class CommonModule {}
+49
View File
@@ -0,0 +1,49 @@
import { validate as isUuid } from './uuid';
export interface ChatCursor {
id: string;
}
export interface MessageCursor {
chatId: string;
id: string;
}
export function encodeChatCursor(cursor: ChatCursor): string {
return encode(cursor);
}
export function decodeChatCursor(raw: string): ChatCursor | null {
const decoded = decode(raw);
return decoded && isUuidField(decoded.id) ? { id: decoded.id } : null;
}
export function encodeMessageCursor(cursor: MessageCursor): string {
return encode(cursor);
}
export function decodeMessageCursor(raw: string): MessageCursor | null {
const decoded = decode(raw);
return decoded && isUuidField(decoded.chatId) && isUuidField(decoded.id)
? { chatId: decoded.chatId, id: decoded.id }
: null;
}
function isUuidField(value: unknown): value is string {
return typeof value === 'string' && isUuid(value);
}
function encode(value: object): string {
return Buffer.from(JSON.stringify(value), 'utf8').toString('base64url');
}
function decode(raw: string): Record<string, unknown> | null {
try {
const parsed = JSON.parse(
Buffer.from(raw, 'base64url').toString('utf8'),
);
return typeof parsed === 'object' && parsed !== null ? parsed : null;
} catch {
return null;
}
}
@@ -7,6 +7,7 @@ import {
Logger,
} from '@nestjs/common';
import { FastifyReply, FastifyRequest } from 'fastify';
import { isDatabaseUnavailable } from '../../db/prisma.service';
import { ApiError, ErrorCode } from './api-error';
const CODE_BY_STATUS: Partial<Record<number, ErrorCode>> = {
@@ -75,6 +76,13 @@ export class HttpExceptionFilter implements ExceptionFilter {
message,
};
}
if (isDatabaseUnavailable(exception)) {
return {
status: 503,
code: 'unavailable',
message: 'database unavailable',
};
}
return {
status: 500,
code: 'internal_error',
-240
View File
@@ -1,240 +0,0 @@
import { Injectable } from '@nestjs/common';
import { randomUUID } from 'crypto';
import { Chat, Message, User } from './domain';
export interface ChatCursor {
id: string;
}
export interface MessageCursor {
chatId: string;
id: string;
}
interface Ordered {
id: string;
seq: number;
createdAt: string;
}
type StoredChat = Chat & Ordered;
type StoredMessage = Message & Ordered;
class OrderedList<T extends Ordered> {
private readonly items: T[] = [];
private readonly indexById = new Map<string, number>();
push(item: T): void {
this.items.push(item);
let index = this.items.length - 1;
while (
index > 0 &&
this.items[index - 1].createdAt === item.createdAt &&
this.items[index - 1].id > item.id
) {
this.items[index] = this.items[index - 1];
this.indexById.set(this.items[index].id, index);
index--;
}
this.items[index] = item;
this.indexById.set(item.id, index);
}
get length(): number {
return this.items.length;
}
toArray(): T[] {
return this.items;
}
page(afterId: string | null, limit: number): T[] {
if (afterId === null) {
return this.items.slice(0, limit);
}
const cursorIndex = this.indexById.get(afterId);
const startIndex =
cursorIndex === undefined ? this.items.length : cursorIndex + 1;
return this.items.slice(startIndex, startIndex + limit);
}
hasMoreAfter(lastId: string): boolean {
const cursorIndex = this.indexById.get(lastId);
return cursorIndex !== undefined && cursorIndex < this.items.length - 1;
}
hasId(id: string): boolean {
return this.indexById.has(id);
}
}
@Injectable()
export class StoreService {
private readonly usersById = new Map<string, User>();
private readonly userIdByUsername = new Map<string, string>();
private readonly chatsById = new Map<string, StoredChat>();
private readonly chatsByMember = new Map<string, OrderedList<StoredChat>>();
private readonly messagesByChatId = new Map<
string,
OrderedList<StoredMessage>
>();
private nextChatSeq = 0;
private nextMessageSeq = 0;
createUser(username: string, displayName: string): User | null {
if (this.userIdByUsername.has(username)) {
return null;
}
const user: User = {
id: randomUUID(),
username,
displayName,
createdAt: new Date().toISOString(),
};
this.usersById.set(user.id, user);
this.userIdByUsername.set(username, user.id);
return user;
}
getUserById(id: string): User | undefined {
return this.usersById.get(id);
}
createChat(title: string, memberIds: string[]): Chat {
const stored: StoredChat = {
id: randomUUID(),
title,
memberIds: [...memberIds],
createdAt: new Date().toISOString(),
seq: this.nextChatSeq++,
};
this.chatsById.set(stored.id, stored);
for (const memberId of memberIds) {
this.chatListFor(memberId).push(stored);
}
this.messagesByChatId.set(stored.id, new OrderedList<StoredMessage>());
return toPublicChat(stored);
}
getChatById(id: string): Chat | undefined {
const stored = this.chatsById.get(id);
return stored ? toPublicChat(stored) : undefined;
}
isMember(chatId: string, userId: string): boolean {
return !!this.chatsById.get(chatId)?.memberIds.includes(userId);
}
listChatsForMember(
userId: string,
afterCursor: ChatCursor | null,
limit: number,
): Chat[] {
return this.chatListFor(userId)
.page(afterCursor?.id ?? null, limit)
.map(toPublicChat);
}
hasMoreChatsAfter(userId: string, lastId: string): boolean {
return this.chatListFor(userId).hasMoreAfter(lastId);
}
chatCursorExists(userId: string, cursorId: string): boolean {
return this.chatListFor(userId).hasId(cursorId);
}
createMessage(chatId: string, senderId: string, text: string): Message {
const list = this.messagesByChatId.get(chatId);
if (!list) {
throw new Error('chat must exist before appending a message');
}
const stored: StoredMessage = {
id: randomUUID(),
chatId,
senderId,
text,
createdAt: new Date().toISOString(),
seq: this.nextMessageSeq++,
};
list.push(stored);
return toPublicMessage(stored);
}
listMessages(
chatId: string,
afterCursor: MessageCursor | null,
limit: number,
): Message[] {
const list = this.messagesByChatId.get(chatId);
if (!list) {
return [];
}
return list.page(afterCursor?.id ?? null, limit).map(toPublicMessage);
}
hasMoreMessagesAfter(chatId: string, lastId: string): boolean {
return this.messagesByChatId.get(chatId)?.hasMoreAfter(lastId) ?? false;
}
messageCursorExists(chatId: string, cursorId: string): boolean {
return this.messagesByChatId.get(chatId)?.hasId(cursorId) ?? false;
}
private chatListFor(memberId: string): OrderedList<StoredChat> {
let list = this.chatsByMember.get(memberId);
if (!list) {
list = new OrderedList<StoredChat>();
this.chatsByMember.set(memberId, list);
}
return list;
}
}
function toPublicChat(stored: StoredChat): Chat {
const { seq: _seq, ...chat } = stored;
return chat;
}
function toPublicMessage(stored: StoredMessage): Message {
const { seq: _seq, ...message } = stored;
return message;
}
export function encodeChatCursor(cursor: ChatCursor): string {
return encode(cursor);
}
export function decodeChatCursor(raw: string): ChatCursor | null {
const decoded = decode(raw);
return decoded && typeof decoded.id === 'string'
? { id: decoded.id }
: null;
}
export function encodeMessageCursor(cursor: MessageCursor): string {
return encode(cursor);
}
export function decodeMessageCursor(raw: string): MessageCursor | null {
const decoded = decode(raw);
return decoded &&
typeof decoded.chatId === 'string' &&
typeof decoded.id === 'string'
? { chatId: decoded.chatId, id: decoded.id }
: null;
}
function encode(value: object): string {
return Buffer.from(JSON.stringify(value), 'utf8').toString('base64url');
}
function decode(raw: string): Record<string, unknown> | null {
try {
const parsed = JSON.parse(
Buffer.from(raw, 'base64url').toString('utf8'),
);
return typeof parsed === 'object' && parsed !== null ? parsed : null;
} catch {
return null;
}
}