nx workspace + nest.js + drizzle

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

2
.env Normal file
View File

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

5
.gitignore vendored
View File

@ -40,3 +40,8 @@ testem.log
# System files
.DS_Store
Thumbs.db
.nx/cache
.nx/workspace-data

5
.prettierignore Normal file
View File

@ -0,0 +1,5 @@
# Add files here to ignore them from prettier formatting
/dist
/coverage
/.nx/cache
/.nx/workspace-data

3
.prettierrc Normal file
View File

@ -0,0 +1,3 @@
{
"singleQuote": true
}

View File

@ -1,4 +1,7 @@
{
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=827846
"recommendations": ["angular.ng-template"]
"recommendations": [
"angular.ng-template",
"nrwl.angular-console",
"esbenp.prettier-vscode"
]
}

View File

@ -1,111 +0,0 @@
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"vokabeltraining": {
"projectType": "application",
"schematics": {
"@schematics/angular:component": {
"inlineTemplate": true,
"inlineStyle": true,
"style": "scss",
"skipTests": true
},
"@schematics/angular:class": {
"skipTests": true
},
"@schematics/angular:directive": {
"skipTests": true
},
"@schematics/angular:guard": {
"skipTests": true
},
"@schematics/angular:interceptor": {
"skipTests": true
},
"@schematics/angular:pipe": {
"skipTests": true
},
"@schematics/angular:resolver": {
"skipTests": true
},
"@schematics/angular:service": {
"skipTests": true
}
},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:application",
"options": {
"outputPath": "dist/vokabeltraining",
"index": "src/index.html",
"browser": "src/main.ts",
"polyfills": [
"zone.js"
],
"tsConfig": "tsconfig.app.json",
"inlineStyleLanguage": "scss",
"assets": [
{
"glob": "**/*",
"input": "public"
}
],
"styles": [
"src/styles.scss"
],
"scripts": []
},
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kB",
"maximumError": "1MB"
},
{
"type": "anyComponentStyle",
"maximumWarning": "2kB",
"maximumError": "4kB"
}
],
"outputHashing": "all"
},
"development": {
"optimization": false,
"extractLicenses": false,
"sourceMap": true
}
},
"defaultConfiguration": "production"
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"proxyConfig": "src/proxy.conf.json"
},
"configurations": {
"production": {
"buildTarget": "vokabeltraining:build:production"
},
"development": {
"buildTarget": "vokabeltraining:build:development"
}
},
"defaultConfiguration": "development"
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n"
}
}
}
},
"cli": {
"analytics": false
}
}

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,
}),
],
};

BIN
local.db Normal file

Binary file not shown.

26
nx.json Normal file
View File

@ -0,0 +1,26 @@
{
"$schema": "./node_modules/nx/schemas/nx-schema.json",
"targetDefaults": {
"build": {
"cache": true,
"dependsOn": ["^build"],
"inputs": ["production", "^production"]
}
},
"defaultBase": "master",
"namedInputs": {
"sharedGlobals": [],
"default": ["{projectRoot}/**/*", "sharedGlobals"],
"production": ["default"]
},
"plugins": [
{
"plugin": "@nx/webpack/plugin",
"options": {
"buildTargetName": "build",
"serveTargetName": "serve",
"previewTargetName": "preview"
}
}
]
}

10938
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -3,9 +3,9 @@
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"watch": "ng build --watch --configuration development"
"start": "nx serve",
"build": "nx build",
"watch": "nx build --watch --configuration development"
},
"private": true,
"dependencies": {
@ -17,18 +17,47 @@
"@angular/platform-browser": "^18.2.0",
"@angular/platform-browser-dynamic": "^18.2.0",
"@angular/router": "^18.2.0",
"@libsql/client": "^0.14.0",
"@nestjs/common": "^10.0.2",
"@nestjs/core": "^10.0.2",
"@nestjs/platform-express": "^10.0.2",
"axios": "^1.6.0",
"dotenv": "^16.4.7",
"fabric": "^5.4.1",
"flowbite": "^2.5.2",
"reflect-metadata": "^0.1.13",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.10"
},
"devDependencies": {
"@angular-devkit/build-angular": "^18.2.12",
"@angular-devkit/core": "^18.2.12",
"@angular-devkit/schematics": "^18.2.12",
"@angular/cli": "^18.2.12",
"@angular/compiler-cli": "^18.2.0",
"@nestjs/schematics": "^10.0.1",
"@nestjs/testing": "^10.0.2",
"@nx/angular": "20.3.1",
"@nx/js": "20.3.1",
"@nx/nest": "^20.3.1",
"@nx/node": "20.3.1",
"@nx/web": "20.3.1",
"@nx/webpack": "20.3.1",
"@nx/workspace": "20.3.1",
"@schematics/angular": "^18.2.12",
"@swc-node/register": "~1.9.1",
"@swc/core": "~1.5.7",
"@swc/helpers": "~0.5.11",
"@types/fabric": "^5.3.9",
"@types/node": "~18.16.9",
"drizzle-kit": "^0.30.2",
"drizzle-orm": "^0.38.4",
"nx": "20.3.1",
"prettier": "^2.6.2",
"tailwindcss": "^3.4.15",
"typescript": "~5.5.2"
"tsx": "^4.19.2",
"typescript": "~5.5.2",
"webpack-cli": "^5.1.4"
}
}

102
project.json Normal file
View File

@ -0,0 +1,102 @@
{
"$schema": "node_modules/nx/schemas/project-schema.json",
"name": "vokabeltraining",
"projectType": "application",
"generators": {
"@schematics/angular:component": {
"inlineTemplate": true,
"inlineStyle": true,
"style": "scss",
"skipTests": true
},
"@schematics/angular:class": {
"skipTests": true
},
"@schematics/angular:directive": {
"skipTests": true
},
"@schematics/angular:guard": {
"skipTests": true
},
"@schematics/angular:interceptor": {
"skipTests": true
},
"@schematics/angular:pipe": {
"skipTests": true
},
"@schematics/angular:resolver": {
"skipTests": true
},
"@schematics/angular:service": {
"skipTests": true
}
},
"sourceRoot": "src",
"prefix": "app",
"targets": {
"build": {
"executor": "@angular-devkit/build-angular:application",
"options": {
"outputPath": "dist/vokabeltraining",
"index": "src/index.html",
"browser": "src/main.ts",
"polyfills": [
"zone.js"
],
"tsConfig": "tsconfig.app.json",
"inlineStyleLanguage": "scss",
"assets": [
{
"glob": "**/*",
"input": "public"
}
],
"styles": [
"src/styles.scss"
],
"scripts": []
},
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kB",
"maximumError": "1MB"
},
{
"type": "anyComponentStyle",
"maximumWarning": "2kB",
"maximumError": "4kB"
}
],
"outputHashing": "all"
},
"development": {
"optimization": false,
"extractLicenses": false,
"sourceMap": true
}
},
"defaultConfiguration": "production"
},
"serve": {
"executor": "@angular-devkit/build-angular:dev-server",
"options": {
"proxyConfig": "src/proxy.conf.json"
},
"configurations": {
"production": {
"buildTarget": "vokabeltraining:build:production"
},
"development": {
"buildTarget": "vokabeltraining:build:development"
}
},
"defaultConfiguration": "development"
},
"extract-i18n": {
"executor": "@angular-devkit/build-angular:extract-i18n"
}
}
}

7
proxy.conf.json Normal file
View File

@ -0,0 +1,7 @@
{
"/api": {
"target": "http://localhost:3000",
"secure": false,
"changeOrigin": true
}
}

View File

@ -2,7 +2,7 @@
"compileOnSave": false,
"compilerOptions": {
"outDir": "./dist/out-tsc",
"strict": true,
"strict": false,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,