feat: add database and orm
This commit is contained in:
+17
-5
@@ -1,11 +1,18 @@
|
|||||||
# syntax=docker/dockerfile:1
|
# syntax=docker/dockerfile:1
|
||||||
|
|
||||||
FROM node:20.17.0-slim AS deps
|
FROM node:20.17.0-slim AS base
|
||||||
|
RUN apt-get update \
|
||||||
|
&& apt-get install -y --no-install-recommends openssl \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
|
FROM base AS deps
|
||||||
COPY package.json package-lock.json ./
|
COPY package.json package-lock.json ./
|
||||||
RUN npm ci
|
RUN npm ci
|
||||||
|
|
||||||
FROM deps AS build
|
FROM deps AS build
|
||||||
|
COPY prisma ./prisma
|
||||||
|
RUN npx prisma generate
|
||||||
COPY tsconfig.json tsconfig.build.json nest-cli.json ./
|
COPY tsconfig.json tsconfig.build.json nest-cli.json ./
|
||||||
COPY src ./src
|
COPY src ./src
|
||||||
RUN npm run build
|
RUN npm run build
|
||||||
@@ -14,11 +21,16 @@ FROM build AS test
|
|||||||
COPY test ./test
|
COPY test ./test
|
||||||
CMD ["npm", "test"]
|
CMD ["npm", "test"]
|
||||||
|
|
||||||
FROM node:20.17.0-slim AS runtime
|
FROM build AS migrate
|
||||||
WORKDIR /app
|
CMD ["sh", "-c", "DATABASE_URL=\"$(cat \"$DATABASE_URL_FILE\")\" exec npx prisma migrate deploy"]
|
||||||
|
|
||||||
|
FROM build AS prod-deps
|
||||||
|
RUN npm prune --omit=dev
|
||||||
|
|
||||||
|
FROM base AS runtime
|
||||||
ENV NODE_ENV=production
|
ENV NODE_ENV=production
|
||||||
COPY package.json package-lock.json ./
|
COPY package.json ./
|
||||||
RUN npm ci --omit=dev && npm cache clean --force
|
COPY --from=prod-deps /app/node_modules ./node_modules
|
||||||
COPY --from=build /app/dist ./dist
|
COPY --from=build /app/dist ./dist
|
||||||
|
|
||||||
USER node
|
USER node
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
name: messenger-lab2-test
|
||||||
|
|
||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres:17.2-alpine
|
||||||
|
environment:
|
||||||
|
POSTGRES_USER: test
|
||||||
|
POSTGRES_PASSWORD: test
|
||||||
|
POSTGRES_DB: messenger_test
|
||||||
|
tmpfs:
|
||||||
|
- /var/lib/postgresql/data
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "pg_isready", "-U", "test", "-d", "messenger_test"]
|
||||||
|
interval: 2s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 15
|
||||||
|
|
||||||
|
tests:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
target: test
|
||||||
|
image: mtusi-messenger-lab2-test:dev
|
||||||
|
environment:
|
||||||
|
DATABASE_URL: postgresql://test:test@postgres:5432/messenger_test?connection_limit=20
|
||||||
|
depends_on:
|
||||||
|
postgres:
|
||||||
|
condition: service_healthy
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
name: messenger-lab2
|
||||||
|
|
||||||
|
services:
|
||||||
|
secrets-init:
|
||||||
|
image: alpine:3.20.3
|
||||||
|
volumes:
|
||||||
|
- secrets:/secrets
|
||||||
|
command:
|
||||||
|
- sh
|
||||||
|
- -ec
|
||||||
|
- |
|
||||||
|
cd /secrets
|
||||||
|
[ -s pg_password ] || head -c 24 /dev/urandom | od -An -tx1 | tr -d ' \n' > pg_password
|
||||||
|
printf 'postgresql://messenger:%s@postgres:5432/messenger?connection_limit=10&pool_timeout=5&connect_timeout=5&socket_timeout=10&application_name=api&options=-c%%20statement_timeout%%3D5000' "$$(cat pg_password)" > database_url
|
||||||
|
chmod 0444 pg_password database_url
|
||||||
|
|
||||||
|
postgres:
|
||||||
|
image: postgres:17.2-alpine
|
||||||
|
environment:
|
||||||
|
POSTGRES_USER: messenger
|
||||||
|
POSTGRES_DB: messenger
|
||||||
|
POSTGRES_PASSWORD_FILE: /run/secrets/pg_password
|
||||||
|
volumes:
|
||||||
|
- pgdata:/var/lib/postgresql/data
|
||||||
|
- secrets:/run/secrets:ro
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "pg_isready", "-U", "messenger", "-d", "messenger"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 10
|
||||||
|
depends_on:
|
||||||
|
secrets-init:
|
||||||
|
condition: service_completed_successfully
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
migrate:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
target: migrate
|
||||||
|
image: mtusi-messenger-lab2-migrate:dev
|
||||||
|
environment:
|
||||||
|
DATABASE_URL_FILE: /run/secrets/database_url
|
||||||
|
volumes:
|
||||||
|
- secrets:/run/secrets:ro
|
||||||
|
depends_on:
|
||||||
|
postgres:
|
||||||
|
condition: service_healthy
|
||||||
|
|
||||||
|
api:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
target: runtime
|
||||||
|
image: mtusi-messenger-lab2-api:dev
|
||||||
|
environment:
|
||||||
|
APP_HOST: 0.0.0.0
|
||||||
|
APP_PORT: 8080
|
||||||
|
APP_ENV: ${APP_ENV:-lab}
|
||||||
|
DATABASE_URL_FILE: /run/secrets/database_url
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:${APP_PORT:-8080}:8080"
|
||||||
|
volumes:
|
||||||
|
- secrets:/run/secrets:ro
|
||||||
|
depends_on:
|
||||||
|
migrate:
|
||||||
|
condition: service_completed_successfully
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
pgdata:
|
||||||
|
secrets:
|
||||||
Generated
+90
@@ -12,6 +12,7 @@
|
|||||||
"@nestjs/common": "^10.4.15",
|
"@nestjs/common": "^10.4.15",
|
||||||
"@nestjs/core": "^10.4.15",
|
"@nestjs/core": "^10.4.15",
|
||||||
"@nestjs/platform-fastify": "^10.4.15",
|
"@nestjs/platform-fastify": "^10.4.15",
|
||||||
|
"@prisma/client": "6.1.0",
|
||||||
"class-transformer": "^0.5.1",
|
"class-transformer": "^0.5.1",
|
||||||
"class-validator": "^0.14.1",
|
"class-validator": "^0.14.1",
|
||||||
"reflect-metadata": "^0.2.2",
|
"reflect-metadata": "^0.2.2",
|
||||||
@@ -28,6 +29,7 @@
|
|||||||
"@typescript-eslint/parser": "^8.18.1",
|
"@typescript-eslint/parser": "^8.18.1",
|
||||||
"eslint": "^8.57.1",
|
"eslint": "^8.57.1",
|
||||||
"jest": "^29.7.0",
|
"jest": "^29.7.0",
|
||||||
|
"prisma": "6.1.0",
|
||||||
"source-map-support": "^0.5.21",
|
"source-map-support": "^0.5.21",
|
||||||
"supertest": "^7.0.0",
|
"supertest": "^7.0.0",
|
||||||
"ts-jest": "^29.2.5",
|
"ts-jest": "^29.2.5",
|
||||||
@@ -2063,6 +2065,74 @@
|
|||||||
"node": ">=14"
|
"node": ">=14"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@prisma/client": {
|
||||||
|
"version": "6.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@prisma/client/-/client-6.1.0.tgz",
|
||||||
|
"integrity": "sha512-AbQYc5+EJKm1Ydfq3KxwcGiy7wIbm4/QbjCKWWoNROtvy7d6a3gmAGkKjK0iUCzh+rHV8xDhD5Cge8ke/kiy5Q==",
|
||||||
|
"hasInstallScript": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18.18"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"prisma": "*"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"prisma": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@prisma/debug": {
|
||||||
|
"version": "6.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@prisma/debug/-/debug-6.1.0.tgz",
|
||||||
|
"integrity": "sha512-0himsvcM4DGBTtvXkd2Tggv6sl2JyUYLzEGXXleFY+7Kp6rZeSS3hiTW9mwtUlXrwYbJP6pwlVNB7jYElrjWUg==",
|
||||||
|
"devOptional": true,
|
||||||
|
"license": "Apache-2.0"
|
||||||
|
},
|
||||||
|
"node_modules/@prisma/engines": {
|
||||||
|
"version": "6.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@prisma/engines/-/engines-6.1.0.tgz",
|
||||||
|
"integrity": "sha512-GnYJbCiep3Vyr1P/415ReYrgJUjP79fBNc1wCo7NP6Eia0CzL2Ot9vK7Infczv3oK7JLrCcawOSAxFxNFsAERQ==",
|
||||||
|
"devOptional": true,
|
||||||
|
"hasInstallScript": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"@prisma/debug": "6.1.0",
|
||||||
|
"@prisma/engines-version": "6.1.0-21.11f085a2012c0f4778414c8db2651556ee0ef959",
|
||||||
|
"@prisma/fetch-engine": "6.1.0",
|
||||||
|
"@prisma/get-platform": "6.1.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@prisma/engines-version": {
|
||||||
|
"version": "6.1.0-21.11f085a2012c0f4778414c8db2651556ee0ef959",
|
||||||
|
"resolved": "https://registry.npmjs.org/@prisma/engines-version/-/engines-version-6.1.0-21.11f085a2012c0f4778414c8db2651556ee0ef959.tgz",
|
||||||
|
"integrity": "sha512-PdJqmYM2Fd8K0weOOtQThWylwjsDlTig+8Pcg47/jszMuLL9iLIaygC3cjWJLda69siRW4STlCTMSgOjZzvKPQ==",
|
||||||
|
"devOptional": true,
|
||||||
|
"license": "Apache-2.0"
|
||||||
|
},
|
||||||
|
"node_modules/@prisma/fetch-engine": {
|
||||||
|
"version": "6.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@prisma/fetch-engine/-/fetch-engine-6.1.0.tgz",
|
||||||
|
"integrity": "sha512-asdFi7TvPlEZ8CzSZ/+Du5wZ27q6OJbRSXh+S8ISZguu+S9KtS/gP7NeXceZyb1Jv1SM1S5YfiCv+STDsG6rrg==",
|
||||||
|
"devOptional": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"@prisma/debug": "6.1.0",
|
||||||
|
"@prisma/engines-version": "6.1.0-21.11f085a2012c0f4778414c8db2651556ee0ef959",
|
||||||
|
"@prisma/get-platform": "6.1.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@prisma/get-platform": {
|
||||||
|
"version": "6.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@prisma/get-platform/-/get-platform-6.1.0.tgz",
|
||||||
|
"integrity": "sha512-ia8bNjboBoHkmKGGaWtqtlgQOhCi7+f85aOkPJKgNwWvYrT6l78KgojLekE8zMhVk0R9lWcifV0Pf8l3/15V0Q==",
|
||||||
|
"devOptional": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"@prisma/debug": "6.1.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@sinclair/typebox": {
|
"node_modules/@sinclair/typebox": {
|
||||||
"version": "0.27.12",
|
"version": "0.27.12",
|
||||||
"resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.12.tgz",
|
"resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.12.tgz",
|
||||||
@@ -7591,6 +7661,26 @@
|
|||||||
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
|
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/prisma": {
|
||||||
|
"version": "6.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/prisma/-/prisma-6.1.0.tgz",
|
||||||
|
"integrity": "sha512-aFI3Yi+ApUxkwCJJwyQSwpyzUX7YX3ihzuHNHOyv4GJg3X5tQsmRaJEnZ+ZyfHpMtnyahhmXVfbTZ+lS8ZtfKw==",
|
||||||
|
"devOptional": true,
|
||||||
|
"hasInstallScript": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"@prisma/engines": "6.1.0"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"prisma": "build/index.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18.18"
|
||||||
|
},
|
||||||
|
"optionalDependencies": {
|
||||||
|
"fsevents": "2.3.3"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/process-warning": {
|
"node_modules/process-warning": {
|
||||||
"version": "3.0.0",
|
"version": "3.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/process-warning/-/process-warning-3.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/process-warning/-/process-warning-3.0.0.tgz",
|
||||||
|
|||||||
@@ -16,6 +16,7 @@
|
|||||||
"@nestjs/common": "^10.4.15",
|
"@nestjs/common": "^10.4.15",
|
||||||
"@nestjs/core": "^10.4.15",
|
"@nestjs/core": "^10.4.15",
|
||||||
"@nestjs/platform-fastify": "^10.4.15",
|
"@nestjs/platform-fastify": "^10.4.15",
|
||||||
|
"@prisma/client": "6.1.0",
|
||||||
"class-transformer": "^0.5.1",
|
"class-transformer": "^0.5.1",
|
||||||
"class-validator": "^0.14.1",
|
"class-validator": "^0.14.1",
|
||||||
"reflect-metadata": "^0.2.2",
|
"reflect-metadata": "^0.2.2",
|
||||||
@@ -32,6 +33,7 @@
|
|||||||
"@typescript-eslint/parser": "^8.18.1",
|
"@typescript-eslint/parser": "^8.18.1",
|
||||||
"eslint": "^8.57.1",
|
"eslint": "^8.57.1",
|
||||||
"jest": "^29.7.0",
|
"jest": "^29.7.0",
|
||||||
|
"prisma": "6.1.0",
|
||||||
"source-map-support": "^0.5.21",
|
"source-map-support": "^0.5.21",
|
||||||
"supertest": "^7.0.0",
|
"supertest": "^7.0.0",
|
||||||
"ts-jest": "^29.2.5",
|
"ts-jest": "^29.2.5",
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
CREATE TABLE "users" (
|
||||||
|
"id" UUID NOT NULL,
|
||||||
|
"username" VARCHAR(32) NOT NULL,
|
||||||
|
"display_name" VARCHAR(100) NOT NULL,
|
||||||
|
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "users_pkey" PRIMARY KEY ("id"),
|
||||||
|
CONSTRAINT "users_username_format" CHECK ("username" ~ '^[a-z0-9_]{3,32}$'),
|
||||||
|
CONSTRAINT "users_display_name_not_blank" CHECK (btrim("display_name") <> '')
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE "chats" (
|
||||||
|
"id" UUID NOT NULL,
|
||||||
|
"title" VARCHAR(100) NOT NULL,
|
||||||
|
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "chats_pkey" PRIMARY KEY ("id"),
|
||||||
|
CONSTRAINT "chats_title_not_blank" CHECK (btrim("title") <> '')
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE "chat_members" (
|
||||||
|
"chat_id" UUID NOT NULL,
|
||||||
|
"user_id" UUID NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "chat_members_pkey" PRIMARY KEY ("chat_id","user_id")
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE "messages" (
|
||||||
|
"id" UUID NOT NULL,
|
||||||
|
"chat_id" UUID NOT NULL,
|
||||||
|
"sender_id" UUID NOT NULL,
|
||||||
|
"text" VARCHAR(4000) NOT NULL,
|
||||||
|
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "messages_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX "users_username_key" ON "users"("username");
|
||||||
|
|
||||||
|
CREATE INDEX "chat_members_user_id_idx" ON "chat_members"("user_id");
|
||||||
|
|
||||||
|
CREATE INDEX "messages_chat_id_created_at_id_idx" ON "messages"("chat_id", "created_at", "id");
|
||||||
|
|
||||||
|
ALTER TABLE "chat_members" ADD CONSTRAINT "chat_members_chat_id_fkey" FOREIGN KEY ("chat_id") REFERENCES "chats"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
ALTER TABLE "chat_members" ADD CONSTRAINT "chat_members_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
ALTER TABLE "messages" ADD CONSTRAINT "messages_chat_id_fkey" FOREIGN KEY ("chat_id") REFERENCES "chats"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
ALTER TABLE "messages" ADD CONSTRAINT "messages_sender_id_fkey" FOREIGN KEY ("sender_id") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
# Please do not edit this file manually
|
||||||
|
# It should be added in your version-control system (i.e. Git)
|
||||||
|
provider = "postgresql"
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
generator client {
|
||||||
|
provider = "prisma-client-js"
|
||||||
|
}
|
||||||
|
|
||||||
|
datasource db {
|
||||||
|
provider = "postgresql"
|
||||||
|
url = env("DATABASE_URL")
|
||||||
|
}
|
||||||
|
|
||||||
|
model User {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
username String @unique @db.VarChar(32)
|
||||||
|
displayName String @map("display_name") @db.VarChar(100)
|
||||||
|
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
|
||||||
|
memberships ChatMember[]
|
||||||
|
messages Message[]
|
||||||
|
|
||||||
|
@@map("users")
|
||||||
|
}
|
||||||
|
|
||||||
|
model Chat {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
title String @db.VarChar(100)
|
||||||
|
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
|
||||||
|
members ChatMember[]
|
||||||
|
messages Message[]
|
||||||
|
|
||||||
|
@@map("chats")
|
||||||
|
}
|
||||||
|
|
||||||
|
model ChatMember {
|
||||||
|
chatId String @map("chat_id") @db.Uuid
|
||||||
|
userId String @map("user_id") @db.Uuid
|
||||||
|
chat Chat @relation(fields: [chatId], references: [id], onDelete: Cascade)
|
||||||
|
user User @relation(fields: [userId], references: [id], onDelete: Restrict)
|
||||||
|
|
||||||
|
@@id([chatId, userId])
|
||||||
|
@@index([userId])
|
||||||
|
@@map("chat_members")
|
||||||
|
}
|
||||||
|
|
||||||
|
model Message {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
chatId String @map("chat_id") @db.Uuid
|
||||||
|
senderId String @map("sender_id") @db.Uuid
|
||||||
|
text String @db.VarChar(4000)
|
||||||
|
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
|
||||||
|
chat Chat @relation(fields: [chatId], references: [id], onDelete: Cascade)
|
||||||
|
sender User @relation(fields: [senderId], references: [id], onDelete: Restrict)
|
||||||
|
|
||||||
|
@@index([chatId, createdAt, id])
|
||||||
|
@@map("messages")
|
||||||
|
}
|
||||||
@@ -1,12 +1,14 @@
|
|||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
import { ChatsModule } from './chats/chats.module';
|
import { ChatsModule } from './chats/chats.module';
|
||||||
import { CommonModule } from './common/common.module';
|
import { CommonModule } from './common/common.module';
|
||||||
|
import { DbModule } from './db/db.module';
|
||||||
import { HealthModule } from './health/health.module';
|
import { HealthModule } from './health/health.module';
|
||||||
import { MessagesModule } from './messages/messages.module';
|
import { MessagesModule } from './messages/messages.module';
|
||||||
import { UsersModule } from './users/users.module';
|
import { UsersModule } from './users/users.module';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
|
DbModule,
|
||||||
CommonModule,
|
CommonModule,
|
||||||
HealthModule,
|
HealthModule,
|
||||||
UsersModule,
|
UsersModule,
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import {
|
|||||||
import { AuthGuard } from '../common/auth/auth.guard';
|
import { AuthGuard } from '../common/auth/auth.guard';
|
||||||
import { CurrentUser } from '../common/auth/current-user.decorator';
|
import { CurrentUser } from '../common/auth/current-user.decorator';
|
||||||
import { parseLimit, rawCursorParam } from '../common/dto/pagination-query.dto';
|
import { parseLimit, rawCursorParam } from '../common/dto/pagination-query.dto';
|
||||||
import { User } from '../common/store/domain';
|
import { User } from '../common/domain';
|
||||||
import { ChatsService } from './chats.service';
|
import { ChatsService } from './chats.service';
|
||||||
import {
|
import {
|
||||||
ChatPageResponse,
|
ChatPageResponse,
|
||||||
@@ -27,31 +27,31 @@ export class ChatsController {
|
|||||||
|
|
||||||
@Post()
|
@Post()
|
||||||
@HttpCode(201)
|
@HttpCode(201)
|
||||||
create(
|
async create(
|
||||||
@Body() dto: CreateChatDto,
|
@Body() dto: CreateChatDto,
|
||||||
@CurrentUser() user: User,
|
@CurrentUser() user: User,
|
||||||
): ChatResponse {
|
): Promise<ChatResponse> {
|
||||||
const chat = this.chats.create(dto.title, dto.member_ids, user.id);
|
const chat = await this.chats.create(dto.title, dto.member_ids, user.id);
|
||||||
return toChatResponse(chat);
|
return toChatResponse(chat);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get()
|
@Get()
|
||||||
list(
|
async list(
|
||||||
@CurrentUser() user: User,
|
@CurrentUser() user: User,
|
||||||
@Query('limit') limitRaw: unknown,
|
@Query('limit') limitRaw: unknown,
|
||||||
@Query('cursor') cursorRaw: unknown,
|
@Query('cursor') cursorRaw: unknown,
|
||||||
): ChatPageResponse {
|
): Promise<ChatPageResponse> {
|
||||||
const limit = parseLimit(limitRaw);
|
const limit = parseLimit(limitRaw);
|
||||||
const cursor = rawCursorParam(cursorRaw);
|
const cursor = rawCursorParam(cursorRaw);
|
||||||
return this.chats.listForMember(user.id, limit, cursor);
|
return this.chats.listForMember(user.id, limit, cursor);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get(':chatId')
|
@Get(':chatId')
|
||||||
getOne(
|
async getOne(
|
||||||
@Param('chatId') chatId: string,
|
@Param('chatId') chatId: string,
|
||||||
@CurrentUser() user: User,
|
@CurrentUser() user: User,
|
||||||
): ChatResponse {
|
): Promise<ChatResponse> {
|
||||||
const chat = this.chats.getForMember(chatId, user.id);
|
const chat = await this.chats.getForMember(chatId, user.id);
|
||||||
return toChatResponse(chat);
|
return toChatResponse(chat);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+86
-29
@@ -1,67 +1,124 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { Prisma } from '@prisma/client';
|
||||||
|
import { decodeChatCursor, encodeChatCursor } from '../common/cursor';
|
||||||
|
import { Chat } from '../common/domain';
|
||||||
import { ApiError } from '../common/filters/api-error';
|
import { ApiError } from '../common/filters/api-error';
|
||||||
import {
|
|
||||||
decodeChatCursor,
|
|
||||||
encodeChatCursor,
|
|
||||||
} from '../common/store/store.service';
|
|
||||||
import { Chat } from '../common/store/domain';
|
|
||||||
import { StoreService } from '../common/store/store.service';
|
|
||||||
import { validate as isUuid } from '../common/uuid';
|
import { validate as isUuid } from '../common/uuid';
|
||||||
|
import { PrismaService, isForeignKeyViolation } from '../db/prisma.service';
|
||||||
import { ChatPageResponse, toChatResponse } from './dto/chat.response';
|
import { ChatPageResponse, toChatResponse } from './dto/chat.response';
|
||||||
|
|
||||||
|
interface ChatRow {
|
||||||
|
id: string;
|
||||||
|
title: string;
|
||||||
|
createdAt: Date;
|
||||||
|
memberIds: string[];
|
||||||
|
}
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class ChatsService {
|
export class ChatsService {
|
||||||
constructor(private readonly store: StoreService) {}
|
constructor(private readonly prisma: PrismaService) {}
|
||||||
|
|
||||||
create(title: string, memberIds: string[], callerId: string): Chat {
|
async create(
|
||||||
|
title: string,
|
||||||
|
memberIds: string[],
|
||||||
|
callerId: string,
|
||||||
|
): Promise<Chat> {
|
||||||
if (!memberIds.includes(callerId)) {
|
if (!memberIds.includes(callerId)) {
|
||||||
throw new ApiError(
|
throw new ApiError(
|
||||||
'invalid_request',
|
'invalid_request',
|
||||||
'member_ids must include the caller',
|
'member_ids must include the caller',
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
for (const id of memberIds) {
|
const invalid = memberIds.find((id) => !isUuid(id));
|
||||||
if (!isUuid(id) || !this.store.getUserById(id)) {
|
if (invalid) {
|
||||||
|
throw new ApiError('invalid_request', `unknown member_id: ${invalid}`);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const chat = await this.prisma.$transaction(async (tx) => {
|
||||||
|
const created = await tx.chat.create({
|
||||||
|
data: { title: title.trim() },
|
||||||
|
});
|
||||||
|
await tx.chatMember.createMany({
|
||||||
|
data: memberIds.map((userId) => ({
|
||||||
|
chatId: created.id,
|
||||||
|
userId,
|
||||||
|
})),
|
||||||
|
});
|
||||||
|
return created;
|
||||||
|
});
|
||||||
|
return toChat({ ...chat, memberIds });
|
||||||
|
} catch (error) {
|
||||||
|
if (isForeignKeyViolation(error)) {
|
||||||
throw new ApiError(
|
throw new ApiError(
|
||||||
'invalid_request',
|
'invalid_request',
|
||||||
`unknown member_id: ${id}`,
|
'member_ids contain an unknown user',
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
throw error;
|
||||||
}
|
}
|
||||||
return this.store.createChat(title.trim(), memberIds);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
getForMember(chatId: string, callerId: string): Chat {
|
async getForMember(chatId: string, callerId: string): Promise<Chat> {
|
||||||
if (!isUuid(chatId)) {
|
if (!isUuid(chatId)) {
|
||||||
throw new ApiError('invalid_request', 'chatId must be a valid UUID');
|
throw new ApiError('invalid_request', 'chatId must be a valid UUID');
|
||||||
}
|
}
|
||||||
const chat = this.store.getChatById(chatId);
|
const chat = await this.prisma.chat.findFirst({
|
||||||
if (!chat || !chat.memberIds.includes(callerId)) {
|
where: { id: chatId, members: { some: { userId: callerId } } },
|
||||||
|
include: { members: { select: { userId: true } } },
|
||||||
|
});
|
||||||
|
if (!chat) {
|
||||||
throw new ApiError('not_found', 'chat not found');
|
throw new ApiError('not_found', 'chat not found');
|
||||||
}
|
}
|
||||||
return chat;
|
return toChat({
|
||||||
|
...chat,
|
||||||
|
memberIds: chat.members.map((m) => m.userId),
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
listForMember(
|
async listForMember(
|
||||||
callerId: string,
|
callerId: string,
|
||||||
limit: number,
|
limit: number,
|
||||||
rawCursor: string | null,
|
rawCursor: string | null,
|
||||||
): ChatPageResponse {
|
): Promise<ChatPageResponse> {
|
||||||
const cursor = rawCursor === null ? null : decodeChatCursor(rawCursor);
|
let after = Prisma.empty;
|
||||||
if (rawCursor !== null && cursor === null) {
|
if (rawCursor !== null) {
|
||||||
throw new ApiError('invalid_request', 'invalid cursor');
|
const cursor = decodeChatCursor(rawCursor);
|
||||||
|
const member = cursor
|
||||||
|
? await this.prisma.chatMember.findUnique({
|
||||||
|
where: {
|
||||||
|
chatId_userId: { chatId: cursor.id, userId: callerId },
|
||||||
|
},
|
||||||
|
include: { chat: { select: { createdAt: true } } },
|
||||||
|
})
|
||||||
|
: null;
|
||||||
|
if (!member) {
|
||||||
|
throw new ApiError('invalid_request', 'invalid cursor');
|
||||||
|
}
|
||||||
|
after = Prisma.sql`AND (c.created_at, c.id) > (${member.chat.createdAt}::timestamptz, ${member.chatId}::uuid)`;
|
||||||
}
|
}
|
||||||
if (cursor && !this.store.chatCursorExists(callerId, cursor.id)) {
|
const rows = await this.prisma.$queryRaw<ChatRow[]>`
|
||||||
throw new ApiError('invalid_request', 'invalid cursor');
|
SELECT c.id, c.title, c.created_at AS "createdAt",
|
||||||
}
|
ARRAY(SELECT m.user_id::text FROM chat_members m WHERE m.chat_id = c.id) AS "memberIds"
|
||||||
const items = this.store.listChatsForMember(callerId, cursor, limit);
|
FROM chat_members cm
|
||||||
|
JOIN chats c ON c.id = cm.chat_id
|
||||||
|
WHERE cm.user_id = ${callerId}::uuid ${after}
|
||||||
|
ORDER BY c.created_at, c.id
|
||||||
|
LIMIT ${limit + 1}`;
|
||||||
|
const items = rows.slice(0, limit).map(toChat);
|
||||||
const last = items[items.length - 1];
|
const last = items[items.length - 1];
|
||||||
const hasMore = last
|
|
||||||
? this.store.hasMoreChatsAfter(callerId, last.id)
|
|
||||||
: false;
|
|
||||||
return {
|
return {
|
||||||
items: items.map(toChatResponse),
|
items: items.map(toChatResponse),
|
||||||
next_cursor: hasMore ? encodeChatCursor({ id: last.id }) : null,
|
next_cursor:
|
||||||
|
rows.length > limit ? encodeChatCursor({ id: last.id }) : null,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function toChat(row: ChatRow): Chat {
|
||||||
|
return {
|
||||||
|
id: row.id,
|
||||||
|
title: row.title,
|
||||||
|
memberIds: row.memberIds,
|
||||||
|
createdAt: row.createdAt.toISOString(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { Chat } from '../../common/store/domain';
|
import { Chat } from '../../common/domain';
|
||||||
|
|
||||||
export interface ChatResponse {
|
export interface ChatResponse {
|
||||||
id: string;
|
id: string;
|
||||||
|
|||||||
@@ -1,25 +1,26 @@
|
|||||||
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
|
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
|
||||||
import { validate as isUuid } from '../uuid';
|
|
||||||
import { FastifyRequest } from 'fastify';
|
import { FastifyRequest } from 'fastify';
|
||||||
|
import { PrismaService } from '../../db/prisma.service';
|
||||||
|
import { toUser } from '../../users/users.service';
|
||||||
import { ApiError } from '../filters/api-error';
|
import { ApiError } from '../filters/api-error';
|
||||||
import { StoreService } from '../store/store.service';
|
import { validate as isUuid } from '../uuid';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class AuthGuard implements CanActivate {
|
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 request = context.switchToHttp().getRequest<FastifyRequest>();
|
||||||
const header = request.headers['x-user-id'];
|
const header = request.headers['x-user-id'];
|
||||||
const userId = Array.isArray(header) ? header[0] : header;
|
const userId = Array.isArray(header) ? header[0] : header;
|
||||||
if (!userId || !isUuid(userId)) {
|
if (!userId || !isUuid(userId)) {
|
||||||
throw new ApiError('unauthorized', 'Missing or invalid X-User-Id');
|
throw new ApiError('unauthorized', 'Missing or invalid X-User-Id');
|
||||||
}
|
}
|
||||||
const user = this.store.getUserById(userId);
|
const row = await this.prisma.user.findUnique({ where: { id: userId } });
|
||||||
if (!user) {
|
if (!row) {
|
||||||
throw new ApiError('unauthorized', 'Missing or invalid X-User-Id');
|
throw new ApiError('unauthorized', 'Missing or invalid X-User-Id');
|
||||||
}
|
}
|
||||||
request.currentUser = user;
|
request.currentUser = toUser(row);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
|
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
|
||||||
import { FastifyRequest } from 'fastify';
|
import { FastifyRequest } from 'fastify';
|
||||||
import { User } from '../store/domain';
|
import { User } from '../domain';
|
||||||
|
|
||||||
declare module 'fastify' {
|
declare module 'fastify' {
|
||||||
interface FastifyRequest {
|
interface FastifyRequest {
|
||||||
|
|||||||
@@ -1,10 +1,9 @@
|
|||||||
import { Global, Module } from '@nestjs/common';
|
import { Global, Module } from '@nestjs/common';
|
||||||
import { AuthGuard } from './auth/auth.guard';
|
import { AuthGuard } from './auth/auth.guard';
|
||||||
import { StoreService } from './store/store.service';
|
|
||||||
|
|
||||||
@Global()
|
@Global()
|
||||||
@Module({
|
@Module({
|
||||||
providers: [StoreService, AuthGuard],
|
providers: [AuthGuard],
|
||||||
exports: [StoreService, AuthGuard],
|
exports: [AuthGuard],
|
||||||
})
|
})
|
||||||
export class CommonModule {}
|
export class CommonModule {}
|
||||||
|
|||||||
@@ -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,
|
Logger,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { FastifyReply, FastifyRequest } from 'fastify';
|
import { FastifyReply, FastifyRequest } from 'fastify';
|
||||||
|
import { isDatabaseUnavailable } from '../../db/prisma.service';
|
||||||
import { ApiError, ErrorCode } from './api-error';
|
import { ApiError, ErrorCode } from './api-error';
|
||||||
|
|
||||||
const CODE_BY_STATUS: Partial<Record<number, ErrorCode>> = {
|
const CODE_BY_STATUS: Partial<Record<number, ErrorCode>> = {
|
||||||
@@ -75,6 +76,13 @@ export class HttpExceptionFilter implements ExceptionFilter {
|
|||||||
message,
|
message,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
if (isDatabaseUnavailable(exception)) {
|
||||||
|
return {
|
||||||
|
status: 503,
|
||||||
|
code: 'unavailable',
|
||||||
|
message: 'database unavailable',
|
||||||
|
};
|
||||||
|
}
|
||||||
return {
|
return {
|
||||||
status: 500,
|
status: 500,
|
||||||
code: 'internal_error',
|
code: 'internal_error',
|
||||||
|
|||||||
@@ -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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { Global, Module } from '@nestjs/common';
|
||||||
|
import { PrismaService } from './prisma.service';
|
||||||
|
|
||||||
|
@Global()
|
||||||
|
@Module({
|
||||||
|
providers: [PrismaService],
|
||||||
|
exports: [PrismaService],
|
||||||
|
})
|
||||||
|
export class DbModule {}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import { Injectable, OnModuleDestroy } from '@nestjs/common';
|
||||||
|
import { Prisma, PrismaClient } from '@prisma/client';
|
||||||
|
import { readFileSync } from 'fs';
|
||||||
|
|
||||||
|
const UNAVAILABLE_CODES = new Set(['P1001', 'P1002', 'P1008', 'P1017', 'P2024']);
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class PrismaService extends PrismaClient implements OnModuleDestroy {
|
||||||
|
constructor() {
|
||||||
|
super({ datasourceUrl: readDatabaseUrl() });
|
||||||
|
}
|
||||||
|
|
||||||
|
async onModuleDestroy(): Promise<void> {
|
||||||
|
await this.$disconnect();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function readDatabaseUrl(): string {
|
||||||
|
const file = process.env.DATABASE_URL_FILE;
|
||||||
|
const url = file ? readFileSync(file, 'utf8').trim() : process.env.DATABASE_URL;
|
||||||
|
if (!url) {
|
||||||
|
throw new Error('DATABASE_URL_FILE or DATABASE_URL must be set');
|
||||||
|
}
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isUniqueViolation(error: unknown): boolean {
|
||||||
|
return (
|
||||||
|
error instanceof Prisma.PrismaClientKnownRequestError &&
|
||||||
|
error.code === 'P2002'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isForeignKeyViolation(error: unknown): boolean {
|
||||||
|
return (
|
||||||
|
error instanceof Prisma.PrismaClientKnownRequestError &&
|
||||||
|
error.code === 'P2003'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isDatabaseUnavailable(error: unknown): boolean {
|
||||||
|
if (error instanceof Prisma.PrismaClientInitializationError) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
error instanceof Prisma.PrismaClientKnownRequestError &&
|
||||||
|
UNAVAILABLE_CODES.has(error.code)
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,14 +1,23 @@
|
|||||||
import { Controller, Get } from '@nestjs/common';
|
import { Controller, Get } from '@nestjs/common';
|
||||||
|
import { ApiError } from '../common/filters/api-error';
|
||||||
|
import { PrismaService } from '../db/prisma.service';
|
||||||
|
|
||||||
@Controller('health')
|
@Controller('health')
|
||||||
export class HealthController {
|
export class HealthController {
|
||||||
|
constructor(private readonly prisma: PrismaService) {}
|
||||||
|
|
||||||
@Get('live')
|
@Get('live')
|
||||||
live(): { status: 'ok' } {
|
live(): { status: 'ok' } {
|
||||||
return { status: 'ok' };
|
return { status: 'ok' };
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get('ready')
|
@Get('ready')
|
||||||
ready(): { status: 'ok' } {
|
async ready(): Promise<{ status: 'ok' }> {
|
||||||
|
try {
|
||||||
|
await this.prisma.$queryRaw`SELECT 1`;
|
||||||
|
} catch {
|
||||||
|
throw new ApiError('unavailable', 'database unavailable');
|
||||||
|
}
|
||||||
return { status: 'ok' };
|
return { status: 'ok' };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { Message } from '../../common/store/domain';
|
import { Message } from '../../common/domain';
|
||||||
|
|
||||||
export interface MessageResponse {
|
export interface MessageResponse {
|
||||||
id: string;
|
id: string;
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import {
|
|||||||
import { AuthGuard } from '../common/auth/auth.guard';
|
import { AuthGuard } from '../common/auth/auth.guard';
|
||||||
import { CurrentUser } from '../common/auth/current-user.decorator';
|
import { CurrentUser } from '../common/auth/current-user.decorator';
|
||||||
import { parseLimit, rawCursorParam } from '../common/dto/pagination-query.dto';
|
import { parseLimit, rawCursorParam } from '../common/dto/pagination-query.dto';
|
||||||
import { User } from '../common/store/domain';
|
import { User } from '../common/domain';
|
||||||
import { CreateMessageDto } from './dto/create-message.dto';
|
import { CreateMessageDto } from './dto/create-message.dto';
|
||||||
import {
|
import {
|
||||||
MessagePageResponse,
|
MessagePageResponse,
|
||||||
@@ -27,22 +27,22 @@ export class MessagesController {
|
|||||||
|
|
||||||
@Post()
|
@Post()
|
||||||
@HttpCode(201)
|
@HttpCode(201)
|
||||||
create(
|
async create(
|
||||||
@Param('chatId') chatId: string,
|
@Param('chatId') chatId: string,
|
||||||
@Body() dto: CreateMessageDto,
|
@Body() dto: CreateMessageDto,
|
||||||
@CurrentUser() user: User,
|
@CurrentUser() user: User,
|
||||||
): MessageResponse {
|
): Promise<MessageResponse> {
|
||||||
const message = this.messages.create(chatId, user.id, dto.text);
|
const message = await this.messages.create(chatId, user.id, dto.text);
|
||||||
return toMessageResponse(message);
|
return toMessageResponse(message);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get()
|
@Get()
|
||||||
list(
|
async list(
|
||||||
@Param('chatId') chatId: string,
|
@Param('chatId') chatId: string,
|
||||||
@CurrentUser() user: User,
|
@CurrentUser() user: User,
|
||||||
@Query('limit') limitRaw: unknown,
|
@Query('limit') limitRaw: unknown,
|
||||||
@Query('cursor') cursorRaw: unknown,
|
@Query('cursor') cursorRaw: unknown,
|
||||||
): MessagePageResponse {
|
): Promise<MessagePageResponse> {
|
||||||
const limit = parseLimit(limitRaw);
|
const limit = parseLimit(limitRaw);
|
||||||
const cursor = rawCursorParam(cursorRaw);
|
const cursor = rawCursorParam(cursorRaw);
|
||||||
return this.messages.list(chatId, user.id, limit, cursor);
|
return this.messages.list(chatId, user.id, limit, cursor);
|
||||||
|
|||||||
@@ -1,73 +1,106 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
import { Injectable } from '@nestjs/common';
|
||||||
import { ApiError } from '../common/filters/api-error';
|
import { Prisma } from '@prisma/client';
|
||||||
import { codePointLength } from '../common/dto/code-point-length.validator';
|
import { codePointLength } from '../common/dto/code-point-length.validator';
|
||||||
import { Message } from '../common/store/domain';
|
import { decodeMessageCursor, encodeMessageCursor } from '../common/cursor';
|
||||||
import {
|
import { Message } from '../common/domain';
|
||||||
decodeMessageCursor,
|
import { ApiError } from '../common/filters/api-error';
|
||||||
encodeMessageCursor,
|
|
||||||
StoreService,
|
|
||||||
} from '../common/store/store.service';
|
|
||||||
import { validate as isUuid } from '../common/uuid';
|
import { validate as isUuid } from '../common/uuid';
|
||||||
|
import { PrismaService } from '../db/prisma.service';
|
||||||
import { MessagePageResponse, toMessageResponse } from './dto/message.response';
|
import { MessagePageResponse, toMessageResponse } from './dto/message.response';
|
||||||
|
|
||||||
|
interface MessageRow {
|
||||||
|
id: string;
|
||||||
|
chatId: string;
|
||||||
|
senderId: string;
|
||||||
|
text: string;
|
||||||
|
createdAt: Date;
|
||||||
|
}
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class MessagesService {
|
export class MessagesService {
|
||||||
constructor(private readonly store: StoreService) {}
|
constructor(private readonly prisma: PrismaService) {}
|
||||||
|
|
||||||
create(chatId: string, callerId: string, text: string): Message {
|
async create(
|
||||||
this.assertMember(chatId, callerId);
|
chatId: string,
|
||||||
|
callerId: string,
|
||||||
|
text: string,
|
||||||
|
): Promise<Message> {
|
||||||
|
await this.assertMember(chatId, callerId);
|
||||||
if (codePointLength(text.trim()) === 0) {
|
if (codePointLength(text.trim()) === 0) {
|
||||||
throw new ApiError(
|
throw new ApiError(
|
||||||
'invalid_request',
|
'invalid_request',
|
||||||
'text must not be empty or whitespace-only',
|
'text must not be empty or whitespace-only',
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return this.store.createMessage(chatId, callerId, text);
|
const row = await this.prisma.message.create({
|
||||||
|
data: { chatId, senderId: callerId, text },
|
||||||
|
});
|
||||||
|
return toMessage(row);
|
||||||
}
|
}
|
||||||
|
|
||||||
list(
|
async list(
|
||||||
chatId: string,
|
chatId: string,
|
||||||
callerId: string,
|
callerId: string,
|
||||||
limit: number,
|
limit: number,
|
||||||
rawCursor: string | null,
|
rawCursor: string | null,
|
||||||
): MessagePageResponse {
|
): Promise<MessagePageResponse> {
|
||||||
this.assertMember(chatId, callerId);
|
await this.assertMember(chatId, callerId);
|
||||||
const cursor =
|
let after = Prisma.empty;
|
||||||
rawCursor === null ? null : decodeMessageCursor(rawCursor);
|
if (rawCursor !== null) {
|
||||||
if (rawCursor !== null && cursor === null) {
|
const cursor = decodeMessageCursor(rawCursor);
|
||||||
throw new ApiError('invalid_request', 'invalid cursor');
|
if (cursor && cursor.chatId !== chatId) {
|
||||||
|
throw new ApiError(
|
||||||
|
'invalid_request',
|
||||||
|
'cursor belongs to a different chat',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const anchor = cursor
|
||||||
|
? await this.prisma.message.findFirst({
|
||||||
|
where: { id: cursor.id, chatId },
|
||||||
|
select: { id: true, createdAt: true },
|
||||||
|
})
|
||||||
|
: null;
|
||||||
|
if (!anchor) {
|
||||||
|
throw new ApiError('invalid_request', 'invalid cursor');
|
||||||
|
}
|
||||||
|
after = Prisma.sql`AND (created_at, id) > (${anchor.createdAt}::timestamptz, ${anchor.id}::uuid)`;
|
||||||
}
|
}
|
||||||
if (cursor && cursor.chatId !== chatId) {
|
const rows = await this.prisma.$queryRaw<MessageRow[]>`
|
||||||
throw new ApiError(
|
SELECT id, chat_id AS "chatId", sender_id AS "senderId", text, created_at AS "createdAt"
|
||||||
'invalid_request',
|
FROM messages
|
||||||
'cursor belongs to a different chat',
|
WHERE chat_id = ${chatId}::uuid ${after}
|
||||||
);
|
ORDER BY created_at, id
|
||||||
}
|
LIMIT ${limit + 1}`;
|
||||||
if (cursor && !this.store.messageCursorExists(chatId, cursor.id)) {
|
const items = rows.slice(0, limit).map(toMessage);
|
||||||
throw new ApiError('invalid_request', 'invalid cursor');
|
|
||||||
}
|
|
||||||
const items = this.store.listMessages(chatId, cursor, limit);
|
|
||||||
const last = items[items.length - 1];
|
const last = items[items.length - 1];
|
||||||
const hasMore = last
|
|
||||||
? this.store.hasMoreMessagesAfter(chatId, last.id)
|
|
||||||
: false;
|
|
||||||
return {
|
return {
|
||||||
items: items.map(toMessageResponse),
|
items: items.map(toMessageResponse),
|
||||||
next_cursor: hasMore
|
next_cursor:
|
||||||
? encodeMessageCursor({ chatId, id: last.id })
|
rows.length > limit
|
||||||
: null,
|
? encodeMessageCursor({ chatId, id: last.id })
|
||||||
|
: null,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private assertMember(chatId: string, callerId: string): void {
|
private async assertMember(chatId: string, callerId: string): Promise<void> {
|
||||||
if (!isUuid(chatId)) {
|
if (!isUuid(chatId)) {
|
||||||
throw new ApiError('invalid_request', 'chatId must be a valid UUID');
|
throw new ApiError('invalid_request', 'chatId must be a valid UUID');
|
||||||
}
|
}
|
||||||
if (
|
const member = await this.prisma.chatMember.findUnique({
|
||||||
!this.store.getChatById(chatId) ||
|
where: { chatId_userId: { chatId, userId: callerId } },
|
||||||
!this.store.isMember(chatId, callerId)
|
});
|
||||||
) {
|
if (!member) {
|
||||||
throw new ApiError('not_found', 'chat not found');
|
throw new ApiError('not_found', 'chat not found');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function toMessage(row: MessageRow): Message {
|
||||||
|
return {
|
||||||
|
id: row.id,
|
||||||
|
chatId: row.chatId,
|
||||||
|
senderId: row.senderId,
|
||||||
|
text: row.text,
|
||||||
|
createdAt: row.createdAt.toISOString(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { User } from '../../common/store/domain';
|
import { User } from '../../common/domain';
|
||||||
|
|
||||||
export interface UserResponse {
|
export interface UserResponse {
|
||||||
id: string;
|
id: string;
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import {
|
|||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { AuthGuard } from '../common/auth/auth.guard';
|
import { AuthGuard } from '../common/auth/auth.guard';
|
||||||
import { CurrentUser } from '../common/auth/current-user.decorator';
|
import { CurrentUser } from '../common/auth/current-user.decorator';
|
||||||
import { User } from '../common/store/domain';
|
import { User } from '../common/domain';
|
||||||
import { CreateUserDto } from './dto/create-user.dto';
|
import { CreateUserDto } from './dto/create-user.dto';
|
||||||
import { toUserResponse, UserResponse } from './dto/user.response';
|
import { toUserResponse, UserResponse } from './dto/user.response';
|
||||||
import { UsersService } from './users.service';
|
import { UsersService } from './users.service';
|
||||||
@@ -19,8 +19,8 @@ export class UsersController {
|
|||||||
|
|
||||||
@Post()
|
@Post()
|
||||||
@HttpCode(201)
|
@HttpCode(201)
|
||||||
create(@Body() dto: CreateUserDto): UserResponse {
|
async create(@Body() dto: CreateUserDto): Promise<UserResponse> {
|
||||||
const user = this.users.register(dto.username, dto.display_name);
|
const user = await this.users.register(dto.username, dto.display_name);
|
||||||
return toUserResponse(user);
|
return toUserResponse(user);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,17 +1,42 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
import { Injectable } from '@nestjs/common';
|
||||||
import { ApiError } from '../common/filters/api-error';
|
import { ApiError } from '../common/filters/api-error';
|
||||||
import { User } from '../common/store/domain';
|
import { User } from '../common/domain';
|
||||||
import { StoreService } from '../common/store/store.service';
|
import { PrismaService, isUniqueViolation } from '../db/prisma.service';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class UsersService {
|
export class UsersService {
|
||||||
constructor(private readonly store: StoreService) {}
|
constructor(private readonly prisma: PrismaService) {}
|
||||||
|
|
||||||
register(username: string, displayName: string): User {
|
async register(username: string, displayName: string): Promise<User> {
|
||||||
const user = this.store.createUser(username, displayName.trim());
|
try {
|
||||||
if (!user) {
|
const row = await this.prisma.user.create({
|
||||||
throw new ApiError('conflict', 'username is already taken');
|
data: { username, displayName: displayName.trim() },
|
||||||
|
});
|
||||||
|
return toUser(row);
|
||||||
|
} catch (error) {
|
||||||
|
if (isUniqueViolation(error)) {
|
||||||
|
throw new ApiError('conflict', 'username is already taken');
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
}
|
}
|
||||||
return user;
|
}
|
||||||
|
|
||||||
|
async findById(id: string): Promise<User | null> {
|
||||||
|
const row = await this.prisma.user.findUnique({ where: { id } });
|
||||||
|
return row ? toUser(row) : null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function toUser(row: {
|
||||||
|
id: string;
|
||||||
|
username: string;
|
||||||
|
displayName: string;
|
||||||
|
createdAt: Date;
|
||||||
|
}): User {
|
||||||
|
return {
|
||||||
|
id: row.id,
|
||||||
|
username: row.username,
|
||||||
|
displayName: row.displayName,
|
||||||
|
createdAt: row.createdAt.toISOString(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import { execSync } from 'child_process';
|
||||||
|
|
||||||
|
export default function globalSetup(): void {
|
||||||
|
execSync('npx prisma migrate deploy', { stdio: 'inherit' });
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@
|
|||||||
"rootDir": ".",
|
"rootDir": ".",
|
||||||
"testEnvironment": "node",
|
"testEnvironment": "node",
|
||||||
"testRegex": ".e2e-spec.ts$",
|
"testRegex": ".e2e-spec.ts$",
|
||||||
|
"globalSetup": "<rootDir>/global-setup.ts",
|
||||||
"transform": {
|
"transform": {
|
||||||
"^.+\\.(t|j)s$": "ts-jest"
|
"^.+\\.(t|j)s$": "ts-jest"
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user