nx workspace + nest.js + drizzle

This commit is contained in:
2025-01-17 12:12:58 +00:00
parent 303ba7c4b2
commit ab17db9078
25 changed files with 11468 additions and 281 deletions

2
api/.env Normal file
View File

@@ -0,0 +1,2 @@
DB_FILE_NAME=file:local.db
PORT=3000

5
api/drizzle.config.ts Normal file
View File

@@ -0,0 +1,5 @@
import { defineConfig } from "drizzle-kit";
export default defineConfig({
dialect: 'sqlite', // 'mysql' | 'sqlite' | 'turso'
schema: './src/db/schema'
})

38
api/project.json Normal file
View File

@@ -0,0 +1,38 @@
{
"name": "api",
"$schema": "../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "api/src",
"projectType": "application",
"targets": {
"build": {
"executor": "nx:run-commands",
"options": {
"command": "webpack-cli build",
"args": ["node-env=production"]
},
"configurations": {
"development": {
"args": ["node-env=development"]
}
}
},
"serve": {
"executor": "@nx/js:node",
"defaultConfiguration": "development",
"dependsOn": ["build"],
"options": {
"buildTarget": "api:build",
"runBuildTargetDependencies": false
},
"configurations": {
"development": {
"buildTarget": "api:build:development"
},
"production": {
"buildTarget": "api:build:production"
}
}
}
},
"tags": []
}

10
api/src/app/app.module.ts Normal file
View File

@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { DecksController } from './decks.controller';
import { DrizzleService } from './drizzle.service';
@Module({
imports: [],
controllers: [DecksController],
providers: [DrizzleService],
})
export class AppModule {}

View File

@@ -0,0 +1,165 @@
// decks.controller.ts
import {
Controller,
Get,
Post,
Delete,
Body,
Param,
Query,
Put,
HttpException,
HttpStatus,
} from '@nestjs/common';
import { DrizzleService } from './drizzle.service';
@Controller('decks')
export class DecksController {
constructor(private readonly drizzleService: DrizzleService) {}
@Get()
async getDecks() {
const entries = await this.drizzleService.getDecks();
const decks = {};
for (const entry of entries) {
const deckname = entry.deckname!!;
if (!decks[deckname]) {
decks[deckname] = {
name: deckname,
images: [],
};
}
if (entry.bildname && entry.bildid) {
decks[deckname].images.push({
name: entry.bildname,
id: entry.bildid,
iconindex: entry.iconindex,
boxid: entry.id,
x1: entry.x1,
x2: entry.x2,
y1: entry.y1,
y2: entry.y2,
due: entry.due,
ivl: entry.ivl,
factor: entry.factor,
reps: entry.reps,
lapses: entry.lapses,
isGraduated: Boolean(entry.isGraduated),
});
}
}
return Object.values(decks);
}
@Post()
async createDeck(@Body() data: { deckname: string }) {
if (!data.deckname) {
throw new HttpException('No deckname provided', HttpStatus.BAD_REQUEST);
}
return this.drizzleService.createDeck(data.deckname);
}
@Get(':deckname')
async getDeck(@Param('deckname') deckname: string) {
const entries = await this.drizzleService.getDeckByName(deckname);
if (entries.length === 0) {
throw new HttpException('Deck not found', HttpStatus.NOT_FOUND);
}
const deck = {
name: deckname,
images: [],
};
for (const entry of entries) {
if (entry.bildname && entry.bildid) {
deck.images.push({
name: entry.bildname,
id: entry.bildid,
iconindex: entry.iconindex,
boxid: entry.id,
x1: entry.x1,
x2: entry.x2,
y1: entry.y1,
y2: entry.y2,
due: entry.due,
ivl: entry.ivl,
factor: entry.factor,
reps: entry.reps,
lapses: entry.lapses,
isGraduated: Boolean(entry.isGraduated),
});
}
}
return deck;
}
@Delete(':deckname')
async deleteDeck(@Param('deckname') deckname: string) {
return this.drizzleService.deleteDeck(deckname);
}
@Put(':oldDeckname/rename')
async renameDeck(
@Param('oldDeckname') oldDeckname: string,
@Body() data: { newDeckName: string },
) {
if (!data.newDeckName) {
throw new HttpException('New deck name is required', HttpStatus.BAD_REQUEST);
}
return this.drizzleService.renameDeck(oldDeckname, data.newDeckName);
}
@Post('image')
async updateImage(@Body() data: any) {
if (!data) {
throw new HttpException('No data provided', HttpStatus.BAD_REQUEST);
}
const requiredFields = ['deckname', 'bildname', 'bildid', 'boxes'];
if (!requiredFields.every((field) => field in data)) {
throw new HttpException('Missing fields in data', HttpStatus.BAD_REQUEST);
}
if (!Array.isArray(data.boxes) || data.boxes.length === 0) {
throw new HttpException(
"'boxes' must be a non-empty list",
HttpStatus.BAD_REQUEST,
);
}
return this.drizzleService.updateImage(data);
}
@Delete('image/:bildid')
async deleteImagesByBildId(@Param('bildid') bildid: string) {
return this.drizzleService.deleteImagesByBildId(bildid);
}
@Post('images/:bildid/move')
async moveImage(
@Param('bildid') bildid: string,
@Body() data: { targetDeckId: string },
) {
if (!data.targetDeckId) {
throw new HttpException('No targetDeckId provided', HttpStatus.BAD_REQUEST);
}
return this.drizzleService.moveImage(bildid, data.targetDeckId);
}
@Put('boxes/:boxId')
async updateBox(
@Param('boxId') boxId: number,
@Body()
data: {
due?: number;
ivl?: number;
factor?: number;
reps?: number;
lapses?: number;
isGraduated?: boolean;
},
) {
return this.drizzleService.updateBox(boxId, data);
}
}

View File

@@ -0,0 +1,188 @@
// drizzle.service.ts
import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { drizzle } from 'drizzle-orm/libsql';
import { Deck, InsertDeck } from '../db/schema';
import { eq, and } from 'drizzle-orm';
@Injectable()
export class DrizzleService {
private db = drizzle('file:local.db');
async getDecks() {
return this.db.select().from(Deck).all();
}
async createDeck(deckname: string) {
const result = await this.db.insert(Deck).values({ deckname }).returning();
return { status: 'success', deck: result };
}
async getDeckByName(deckname: string) {
return this.db.select().from(Deck).where(eq(Deck.deckname, deckname)).all();
}
async deleteDeck(deckname: string) {
const existingDeck = await this.getDeckByName(deckname);
if (existingDeck.length === 0) {
throw new HttpException('Deck not found', HttpStatus.NOT_FOUND);
}
await this.db.delete(Deck).where(eq(Deck.deckname, deckname));
return { status: 'success' };
}
async renameDeck(oldDeckname: string, newDeckname: string) {
const existingDeck = await this.getDeckByName(oldDeckname);
if (existingDeck.length === 0) {
throw new HttpException('Deck not found', HttpStatus.NOT_FOUND);
}
const existingNewDeck = await this.getDeckByName(newDeckname);
if (existingNewDeck.length > 0) {
throw new HttpException(
'Deck with the new name already exists',
HttpStatus.CONFLICT,
);
}
await this.db
.update(Deck)
.set({ deckname: newDeckname })
.where(eq(Deck.deckname, oldDeckname))
return { status: 'success', message: 'Deck renamed successfully' };
}
async updateImage(data: {
deckname: string;
bildname: string;
bildid: string;
boxes: Array<{ x1: number; x2: number; y1: number; y2: number }>;
}) {
const existingDeck = await this.getDeckByName(data.deckname);
if (existingDeck.length === 0) {
throw new HttpException('Deck not found', HttpStatus.NOT_FOUND);
}
await this.db
.delete(Deck)
.where(
and(eq(Deck.deckname, data.deckname), eq(Deck.bildid, data.bildid)),
)
const insertedImages:any = [];
for (let index = 0; index < data.boxes.length; index++) {
const box = data.boxes[index];
const result = await this.db
.insert(Deck)
.values({
deckname: data.deckname,
bildname: data.bildname,
bildid: data.bildid,
iconindex: index,
x1: box.x1,
x2: box.x2,
y1: box.y1,
y2: box.y2,
}).returning();
insertedImages.push(result);
}
return { status: 'success', inserted_images: insertedImages };
}
async deleteImagesByBildId(bildid: string) {
const affectedDecks = await this.db
.select({ deckname: Deck.deckname })
.from(Deck)
.where(eq(Deck.bildid, bildid))
.all();
if (affectedDecks.length === 0) {
throw new HttpException(
'No entries found for the given image ID',
HttpStatus.NOT_FOUND,
);
}
await this.db.delete(Deck).where(eq(Deck.bildid, bildid));
for (const deck of affectedDecks) {
const remainingImages = await this.db
.select()
.from(Deck)
.where(
and(eq(Deck.deckname, deck.deckname), eq(Deck.bildid, bildid)),
)
.all();
if (remainingImages.length === 0) {
const emptyDeckEntry = await this.db
.select()
.from(Deck)
.where(
and(eq(Deck.deckname, deck.deckname), eq(Deck.bildid, null)),
)
.all();
if (emptyDeckEntry.length === 0) {
await this.db.insert(Deck).values({ deckname: deck.deckname });
}
}
}
return {
status: 'success',
message: `All entries for image ID "${bildid}" have been deleted.`,
};
}
async moveImage(bildid: string, targetDeckId: string) {
const existingImages = await this.db
.select()
.from(Deck)
.where(eq(Deck.bildid, bildid))
.all();
if (existingImages.length === 0) {
throw new HttpException(
'No entries found for the given image ID',
HttpStatus.NOT_FOUND,
);
}
await this.db
.update(Deck)
.set({ deckname: targetDeckId })
.where(eq(Deck.bildid, bildid))
return { status: 'success', moved_entries: existingImages.length };
}
async updateBox(
boxId: number,
data: {
due?: number;
ivl?: number;
factor?: number;
reps?: number;
lapses?: number;
isGraduated?: boolean;
},
) {
const updateData: any = { ...data };
if (typeof data.isGraduated === 'boolean') {
updateData.isGraduated = Number(data.isGraduated);
}
const result = await this.db
.update(Deck)
.set(updateData)
.where(eq(Deck.id, boxId))
if (result.rowsAffected === 0) {
throw new HttpException('Box not found', HttpStatus.NOT_FOUND);
}
return { status: 'success' };
}
}

0
api/src/assets/.gitkeep Normal file
View File

30
api/src/db/schema.ts Normal file
View File

@@ -0,0 +1,30 @@
import { sqliteTable as table, text, integer, real } from 'drizzle-orm/sqlite-core';
import * as t from "drizzle-orm/sqlite-core";
export const Deck = table('Deck', {
id: integer('id').primaryKey({ autoIncrement: true }),
deckname: text('deckname'),
bildname: text('bildname'),
bildid: text('bildid'),
iconindex: integer('iconindex'),
x1: real('x1'),
x2: real('x2'),
y1: real('y1'),
y2: real('y2'),
due: integer('due'),
ivl: real('ivl'),
factor: real('factor'),
reps: integer('reps'),
lapses: integer('lapses'),
isGraduated: integer('isGraduated'),
},
(table) => {
return {
index: t.uniqueIndex("email_idx").on(table.id),
};
}
);
export type InsertDeck = typeof Deck.$inferInsert;
export type SelectDeck = typeof Deck.$inferSelect;

21
api/src/main.ts Normal file
View File

@@ -0,0 +1,21 @@
/**
* This is not a production server yet!
* This is only a minimal backend to get started.
*/
import { Logger } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app/app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const globalPrefix = 'api';
app.setGlobalPrefix(globalPrefix);
const port = process.env['PORT'] || 3000;
await app.listen(port);
Logger.log(
`🚀 Application is running on: http://localhost:${port}/${globalPrefix}`
);
}
bootstrap();

12
api/tsconfig.app.json Normal file
View File

@@ -0,0 +1,12 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../dist/out-tsc",
"module": "ES2020",
"types": ["node"],
"emitDecoratorMetadata": true,
"target": "es2021",
"strictNullChecks": true
},
"include": ["src/**/*.ts"]
}

13
api/tsconfig.json Normal file
View File

@@ -0,0 +1,13 @@
{
"extends": "../tsconfig.json",
"files": [],
"include": [],
"references": [
{
"path": "./tsconfig.app.json"
}
],
"compilerOptions": {
"esModuleInterop": true
}
}

20
api/webpack.config.js Normal file
View File

@@ -0,0 +1,20 @@
const { NxAppWebpackPlugin } = require('@nx/webpack/app-plugin');
const { join } = require('path');
module.exports = {
output: {
path: join(__dirname, '../dist/api'),
},
plugins: [
new NxAppWebpackPlugin({
target: 'node',
compiler: 'tsc',
main: './src/main.ts',
tsConfig: './tsconfig.app.json',
assets: ['./src/assets'],
optimization: false,
outputHashing: 'none',
generatePackageJson: true,
}),
],
};