Standardize code formatting for consistency

Update all NestJS imports to use double quotes instead of single quotes across multiple files. Adjusted indentation in various files to ensure uniform code style. These changes improve code readability and maintainability.
This commit is contained in:
Mathis H (Avnyr) 2024-09-30 08:46:45 +02:00
parent 2aa132e511
commit fd8ad47cf7
Signed by: Mathis
GPG Key ID: DD9E0666A747D126
41 changed files with 898 additions and 862 deletions

View File

@ -1,8 +1,8 @@
import { Test, TestingModule } from '@nestjs/testing'; import { Test, TestingModule } from "@nestjs/testing";
import { AdminController } from './admin.controller'; import { AdminController } from "./admin.controller";
import { AdminService } from './admin.service'; import { AdminService } from "./admin.service";
describe('AdminController', () => { describe("AdminController", () => {
let controller: AdminController; let controller: AdminController;
beforeEach(async () => { beforeEach(async () => {
@ -14,7 +14,7 @@ describe('AdminController', () => {
controller = module.get<AdminController>(AdminController); controller = module.get<AdminController>(AdminController);
}); });
it('should be defined', () => { it("should be defined", () => {
expect(controller).toBeDefined(); expect(controller).toBeDefined();
}); });
}); });

View File

@ -1,7 +1,7 @@
import { Controller } from '@nestjs/common'; import { Controller } from "@nestjs/common";
import { AdminService } from './admin.service'; import { AdminService } from "./admin.service";
@Controller('admin') @Controller("admin")
export class AdminController { export class AdminController {
constructor(private readonly adminService: AdminService) {} constructor(private readonly adminService: AdminService) {}
} }

View File

@ -1,6 +1,6 @@
import { Module } from '@nestjs/common'; import { Module } from "@nestjs/common";
import { AdminService } from './admin.service'; import { AdminController } from "./admin.controller";
import { AdminController } from './admin.controller'; import { AdminService } from "./admin.service";
@Module({ @Module({
controllers: [AdminController], controllers: [AdminController],

View File

@ -1,7 +1,7 @@
import { Test, TestingModule } from '@nestjs/testing'; import { Test, TestingModule } from "@nestjs/testing";
import { AdminService } from './admin.service'; import { AdminService } from "./admin.service";
describe('AdminService', () => { describe("AdminService", () => {
let service: AdminService; let service: AdminService;
beforeEach(async () => { beforeEach(async () => {
@ -12,7 +12,7 @@ describe('AdminService', () => {
service = module.get<AdminService>(AdminService); service = module.get<AdminService>(AdminService);
}); });
it('should be defined', () => { it("should be defined", () => {
expect(service).toBeDefined(); expect(service).toBeDefined();
}); });
}); });

View File

@ -1,4 +1,4 @@
import { Injectable } from '@nestjs/common'; import { Injectable } from "@nestjs/common";
@Injectable() @Injectable()
export class AdminService {} export class AdminService {}

View File

@ -1,17 +1,17 @@
import { Module } from '@nestjs/common'; import { Module } from "@nestjs/common";
import { AppController } from './app.controller'; import { ConfigModule } from "@nestjs/config";
import { AppService } from './app.service'; import { ThrottlerModule } from "@nestjs/throttler";
import { DbModule } from './db/db.module'; import { AuthorsModule } from "apps/backend/src/app/authors/authors.module";
import { ThrottlerModule } from '@nestjs/throttler'; import { AdminModule } from "./admin/admin.module";
import { ConfigModule } from '@nestjs/config'; import { AppController } from "./app.controller";
import { AuthModule } from './auth/auth.module'; import { AppService } from "./app.service";
import { CredentialsModule } from './credentials/credentials.module'; import { AuthModule } from "./auth/auth.module";
import { FilesModule } from './files/files.module'; import { CredentialsModule } from "./credentials/credentials.module";
import { AdminModule } from './admin/admin.module'; import { DbModule } from "./db/db.module";
import { GroupsModule } from './groups/groups.module'; import { FilesModule } from "./files/files.module";
import { MachinesModule } from './machines/machines.module'; import { GroupsModule } from "./groups/groups.module";
import { AuthorsModule } from 'apps/backend/src/app/authors/authors.module'; import { MachinesModule } from "./machines/machines.module";
@Module({ @Module({
imports: [ imports: [

View File

@ -4,14 +4,15 @@ import {
Delete, Delete,
Get, Get,
HttpCode, HttpCode,
HttpStatus, Patch, HttpStatus,
Patch,
Post, Post,
UnauthorizedException, UnauthorizedException,
UseGuards UseGuards,
} from "@nestjs/common"; } from "@nestjs/common";
import { SignInDto, SignUpDto } from "apps/backend/src/app/auth/auth.dto";
import { AuthService } from "apps/backend/src/app/auth/auth.service";
import { UserGuard } from "./auth.guard"; import { UserGuard } from "./auth.guard";
import { AuthService } from 'apps/backend/src/app/auth/auth.service';
import { SignInDto, SignUpDto } from 'apps/backend/src/app/auth/auth.dto';
@Controller("auth") @Controller("auth")
export class AuthController { export class AuthController {
@ -39,8 +40,8 @@ export class AuthController {
@UseGuards(UserGuard) @UseGuards(UserGuard)
async getMe(@Body() body: object) { async getMe(@Body() body: object) {
// @ts-ignore // @ts-ignore
const targetId = body.sourceUserId const targetId = body.sourceUserId;
const userData = await this.authService.fetchUserById(targetId) const userData = await this.authService.fetchUserById(targetId);
if (!userData) { if (!userData) {
throw new UnauthorizedException(); throw new UnauthorizedException();
} }
@ -52,9 +53,9 @@ export class AuthController {
@UseGuards(UserGuard) @UseGuards(UserGuard)
async deleteMe(@Body() body: object) { async deleteMe(@Body() body: object) {
// @ts-ignore // @ts-ignore
const targetId = body.sourceUserId const targetId = body.sourceUserId;
try { try {
await this.authService.deleteUser(targetId) await this.authService.deleteUser(targetId);
} catch (err) { } catch (err) {
throw new UnauthorizedException(); throw new UnauthorizedException();
} }

View File

@ -1,23 +1,26 @@
import { Injectable, CanActivate, ExecutionContext, UnauthorizedException, Inject } from "@nestjs/common"; import {
import type { Request } from "express"; CanActivate,
import { eq } from "drizzle-orm"; ExecutionContext,
Inject,
Injectable,
UnauthorizedException,
} from "@nestjs/common";
import { Reflector } from "@nestjs/core"; import { Reflector } from "@nestjs/core";
import { DbService } from 'apps/backend/src/app/db/db.service'; import { CredentialsService } from "apps/backend/src/app/credentials/credentials.service";
import { UsersTable } from 'apps/backend/src/app/db/schema'; import { DbService } from "apps/backend/src/app/db/db.service";
import { CredentialsService } from 'apps/backend/src/app/credentials/credentials.service'; import { UsersTable } from "apps/backend/src/app/db/schema";
import { eq } from "drizzle-orm";
import type { Request } from "express";
@Injectable() @Injectable()
export class UserGuard implements CanActivate { export class UserGuard implements CanActivate {
constructor( constructor(
@Inject(CredentialsService) private readonly credentialService: CredentialsService, @Inject(CredentialsService)
private readonly credentialService: CredentialsService,
@Inject(DbService) private readonly databaseService: DbService, @Inject(DbService) private readonly databaseService: DbService,
) { ) {}
}
async canActivate( async canActivate(context: ExecutionContext): Promise<boolean> {
context: ExecutionContext
): Promise<boolean> {
const request: Request = context.switchToHttp().getRequest(); const request: Request = context.switchToHttp().getRequest();
const authHeader = request.headers.authorization; const authHeader = request.headers.authorization;
@ -27,7 +30,8 @@ export class UserGuard implements CanActivate {
const token = authHeader.split(" ")[1]; const token = authHeader.split(" ")[1];
const vToken = await this.credentialService.verifyAuthToken(token); const vToken = await this.credentialService.verifyAuthToken(token);
const user = await this.databaseService.use() const user = await this.databaseService
.use()
.select() .select()
.from(UsersTable) .from(UsersTable)
.where(eq(UsersTable.uuid, vToken.payload.sub)); .where(eq(UsersTable.uuid, vToken.payload.sub));
@ -49,25 +53,23 @@ export class UserGuard implements CanActivate {
@Injectable() @Injectable()
export class AdminGuard implements CanActivate { export class AdminGuard implements CanActivate {
constructor( constructor(
@Inject(CredentialsService) private readonly credentialService: CredentialsService, @Inject(CredentialsService)
private readonly credentialService: CredentialsService,
@Inject(DbService) private readonly databaseService: DbService, @Inject(DbService) private readonly databaseService: DbService,
) {} ) {}
async canActivate( async canActivate(context: ExecutionContext): Promise<boolean> {
context: ExecutionContext
): Promise<boolean> {
const request: Request = context.switchToHttp().getRequest(); const request: Request = context.switchToHttp().getRequest();
const authHeader = request.headers.authorization; const authHeader = request.headers.authorization;
if (!authHeader) { if (!authHeader) {
throw new UnauthorizedException("No authorization header found."); throw new UnauthorizedException("No authorization header found.");
} }
const token = authHeader.split(" ")[1]; const token = authHeader.split(" ")[1];
const vToken = await this.credentialService.verifyAuthToken(token); const vToken = await this.credentialService.verifyAuthToken(token);
const user = await this.databaseService.use() const user = await this.databaseService
.use()
.select() .select()
.from(UsersTable) .from(UsersTable)
.where(eq(UsersTable.uuid, vToken.payload.sub)); .where(eq(UsersTable.uuid, vToken.payload.sub));

View File

@ -1,10 +1,10 @@
import { Module } from "@nestjs/common"; import { Module } from "@nestjs/common";
import { AdminGuard, UserGuard } from "apps/backend/src/app/auth/auth.guard";
import { CredentialsModule } from "apps/backend/src/app/credentials/credentials.module";
import { CredentialsService } from "apps/backend/src/app/credentials/credentials.service";
import { DbModule } from "apps/backend/src/app/db/db.module";
import { AuthController } from "./auth.controller"; import { AuthController } from "./auth.controller";
import { AuthService } from "./auth.service"; import { AuthService } from "./auth.service";
import { DbModule } from 'apps/backend/src/app/db/db.module';
import { CredentialsModule } from 'apps/backend/src/app/credentials/credentials.module';
import { CredentialsService } from 'apps/backend/src/app/credentials/credentials.service';
import { AdminGuard, UserGuard } from 'apps/backend/src/app/auth/auth.guard';
@Module({ @Module({
imports: [DbModule, CredentialsModule], imports: [DbModule, CredentialsModule],

View File

@ -3,11 +3,11 @@ import {
OnModuleInit, OnModuleInit,
UnauthorizedException, UnauthorizedException,
} from "@nestjs/common"; } from "@nestjs/common";
import { SignInDto, SignUpDto } from "apps/backend/src/app/auth/auth.dto";
import { CredentialsService } from "apps/backend/src/app/credentials/credentials.service";
import { DbService } from "apps/backend/src/app/db/db.service";
import { UsersTable } from "apps/backend/src/app/db/schema";
import { eq } from "drizzle-orm"; import { eq } from "drizzle-orm";
import { DbService } from 'apps/backend/src/app/db/db.service';
import { CredentialsService } from 'apps/backend/src/app/credentials/credentials.service';
import { UsersTable } from 'apps/backend/src/app/db/schema';
import { SignInDto, SignUpDto } from 'apps/backend/src/app/auth/auth.dto';
@Injectable() @Injectable()
export class AuthService implements OnModuleInit { export class AuthService implements OnModuleInit {
@ -156,4 +156,3 @@ export class AuthService implements OnModuleInit {
}, 2000); }, 2000);
} }
} }

View File

@ -1,8 +1,8 @@
import { Test, TestingModule } from '@nestjs/testing'; import { Test, TestingModule } from "@nestjs/testing";
import { AuthorsController } from 'apps/backend/src/app/authors/authors.controller'; import { AuthorsController } from "apps/backend/src/app/authors/authors.controller";
import { AuthorsService } from 'apps/backend/src/app/authors/authors.service'; import { AuthorsService } from "apps/backend/src/app/authors/authors.service";
describe('AuthorsController', () => { describe("AuthorsController", () => {
let controller: AuthorsController; let controller: AuthorsController;
beforeEach(async () => { beforeEach(async () => {
@ -14,7 +14,7 @@ describe('AuthorsController', () => {
controller = module.get<AuthorsController>(AuthorsController); controller = module.get<AuthorsController>(AuthorsController);
}); });
it('should be defined', () => { it("should be defined", () => {
expect(controller).toBeDefined(); expect(controller).toBeDefined();
}); });
}); });

View File

@ -1,7 +1,16 @@
import { Controller, DefaultValuePipe, Delete, Get, Param, ParseIntPipe, Post, Query } from '@nestjs/common'; import {
import { AuthorsService } from 'apps/backend/src/app/authors/authors.service'; Controller,
DefaultValuePipe,
Delete,
Get,
Param,
ParseIntPipe,
Post,
Query,
} from "@nestjs/common";
import { AuthorsService } from "apps/backend/src/app/authors/authors.service";
@Controller('authors') @Controller("authors")
export class AuthorsController { export class AuthorsController {
constructor(private readonly authorService: AuthorsService) {} constructor(private readonly authorService: AuthorsService) {}
@ -9,23 +18,18 @@ export class AuthorsController {
async findMany( async findMany(
@Query("limit", new DefaultValuePipe(20), ParseIntPipe) limit: number, @Query("limit", new DefaultValuePipe(20), ParseIntPipe) limit: number,
@Query("offset", new DefaultValuePipe(0), ParseIntPipe) offset: number, @Query("offset", new DefaultValuePipe(0), ParseIntPipe) offset: number,
@Query("search", new DefaultValuePipe("")) search: string @Query("search", new DefaultValuePipe("")) search: string,
) { ) {
const query = {limit, offset, search} const query = { limit, offset, search };
} }
//POST a new group //POST a new group
@Post("new") @Post("new")
async newAuthor() { async newAuthor() {}
}
//DELETE a group //DELETE a group
@Delete(":authorId") @Delete(":authorId")
async deleteAuthor(@Param('authorId') authorId: string) { async deleteAuthor(@Param("authorId") authorId: string) {}
}
//GET files associated to authors with limit and offset //GET files associated to authors with limit and offset
@Get(":authorId") @Get(":authorId")
@ -33,9 +37,8 @@ export class AuthorsController {
@Query("limit", new DefaultValuePipe(20), ParseIntPipe) limit: number, @Query("limit", new DefaultValuePipe(20), ParseIntPipe) limit: number,
@Query("offset", new DefaultValuePipe(0), ParseIntPipe) offset: number, @Query("offset", new DefaultValuePipe(0), ParseIntPipe) offset: number,
@Query("search", new DefaultValuePipe("")) search: string, @Query("search", new DefaultValuePipe("")) search: string,
@Param('authorId') authorId: string @Param("authorId") authorId: string,
) { ) {
const query = {limit, offset, search} const query = { limit, offset, search };
} }
} }

View File

@ -1,6 +1,6 @@
import { Module } from '@nestjs/common'; import { Module } from "@nestjs/common";
import { AuthorsService } from 'apps/backend/src/app/authors/authors.service'; import { AuthorsController } from "apps/backend/src/app/authors/authors.controller";
import { AuthorsController } from 'apps/backend/src/app/authors/authors.controller'; import { AuthorsService } from "apps/backend/src/app/authors/authors.service";
@Module({ @Module({
controllers: [AuthorsController], controllers: [AuthorsController],

View File

@ -1,7 +1,7 @@
import { Test, TestingModule } from '@nestjs/testing'; import { Test, TestingModule } from "@nestjs/testing";
import { AuthorsService } from 'apps/backend/src/app/authors/authors.service'; import { AuthorsService } from "apps/backend/src/app/authors/authors.service";
describe('AuthorsService', () => { describe("AuthorsService", () => {
let service: AuthorsService; let service: AuthorsService;
beforeEach(async () => { beforeEach(async () => {
@ -12,7 +12,7 @@ describe('AuthorsService', () => {
service = module.get<AuthorsService>(AuthorsService); service = module.get<AuthorsService>(AuthorsService);
}); });
it('should be defined', () => { it("should be defined", () => {
expect(service).toBeDefined(); expect(service).toBeDefined();
}); });
}); });

View File

@ -1,4 +1,4 @@
import { Injectable } from '@nestjs/common'; import { Injectable } from "@nestjs/common";
@Injectable() @Injectable()
export class AuthorsService {} export class AuthorsService {}

View File

@ -36,7 +36,7 @@ export class CredentialsService {
console.log(result); console.log(result);
return result; return result;
} catch (error) { } catch (error) {
console.log(error) console.log(error);
throw new BadRequestException("Invalid token"); throw new BadRequestException("Invalid token");
} }
} }

View File

@ -61,9 +61,11 @@ export const FilesTable = pgTable("files", {
}) })
.notNull(), .notNull(),
checksum: p.varchar("checksum", { checksum: p
length: 64 .varchar("checksum", {
}).notNull(), length: 64,
})
.notNull(),
uploader: p uploader: p
.varchar("uploader", { .varchar("uploader", {
@ -71,9 +73,7 @@ export const FilesTable = pgTable("files", {
}) })
.notNull(), .notNull(),
groupId: p groupId: p.uuid("group_id").references(() => FilesGroupTable.uuid),
.uuid("group_id")
.references(()=> FilesGroupTable.uuid),
fileSize: p.integer("file_size").notNull(), fileSize: p.integer("file_size").notNull(),
@ -109,7 +109,7 @@ export const FilesGroupTable = pgTable("f_groups", {
}) })
.unique() .unique()
.notNull(), .notNull(),
}) });
//TODO Files types //TODO Files types
export const FilesTypesTable = pgTable("f_types", { export const FilesTypesTable = pgTable("f_types", {

View File

@ -1,8 +1,8 @@
import { Test, TestingModule } from '@nestjs/testing'; import { Test, TestingModule } from "@nestjs/testing";
import { FilesController } from './files.controller'; import { FilesController } from "./files.controller";
import { FilesService } from './files.service'; import { FilesService } from "./files.service";
describe('FilesController', () => { describe("FilesController", () => {
let controller: FilesController; let controller: FilesController;
beforeEach(async () => { beforeEach(async () => {
@ -14,7 +14,7 @@ describe('FilesController', () => {
controller = module.get<FilesController>(FilesController); controller = module.get<FilesController>(FilesController);
}); });
it('should be defined', () => { it("should be defined", () => {
expect(controller).toBeDefined(); expect(controller).toBeDefined();
}); });
}); });

View File

@ -1,7 +1,7 @@
import { Controller } from '@nestjs/common'; import { Controller } from "@nestjs/common";
import { FilesService } from './files.service'; import { FilesService } from "./files.service";
@Controller('files') @Controller("files")
export class FilesController { export class FilesController {
constructor(private readonly filesService: FilesService) {} constructor(private readonly filesService: FilesService) {}
} }

View File

@ -1,6 +1,6 @@
import { Module } from '@nestjs/common'; import { Module } from "@nestjs/common";
import { FilesService } from './files.service'; import { FilesController } from "./files.controller";
import { FilesController } from './files.controller'; import { FilesService } from "./files.service";
@Module({ @Module({
controllers: [FilesController], controllers: [FilesController],

View File

@ -1,7 +1,7 @@
import { Test, TestingModule } from '@nestjs/testing'; import { Test, TestingModule } from "@nestjs/testing";
import { FilesService } from './files.service'; import { FilesService } from "./files.service";
describe('FilesService', () => { describe("FilesService", () => {
let service: FilesService; let service: FilesService;
beforeEach(async () => { beforeEach(async () => {
@ -12,7 +12,7 @@ describe('FilesService', () => {
service = module.get<FilesService>(FilesService); service = module.get<FilesService>(FilesService);
}); });
it('should be defined', () => { it("should be defined", () => {
expect(service).toBeDefined(); expect(service).toBeDefined();
}); });
}); });

View File

@ -1,4 +1,4 @@
import { Injectable } from '@nestjs/common'; import { Injectable } from "@nestjs/common";
@Injectable() @Injectable()
export class FilesService {} export class FilesService {}

View File

View File

@ -1,8 +1,8 @@
import { Test, TestingModule } from '@nestjs/testing'; import { Test, TestingModule } from "@nestjs/testing";
import { GroupsController } from './groups.controller'; import { GroupsController } from "./groups.controller";
import { GroupsService } from './groups.service'; import { GroupsService } from "./groups.service";
describe('GroupsController', () => { describe("GroupsController", () => {
let controller: GroupsController; let controller: GroupsController;
beforeEach(async () => { beforeEach(async () => {
@ -14,7 +14,7 @@ describe('GroupsController', () => {
controller = module.get<GroupsController>(GroupsController); controller = module.get<GroupsController>(GroupsController);
}); });
it('should be defined', () => { it("should be defined", () => {
expect(controller).toBeDefined(); expect(controller).toBeDefined();
}); });
}); });

View File

@ -1,8 +1,17 @@
import { Controller, DefaultValuePipe, Delete, Get, Param, ParseIntPipe, Post, Query } from '@nestjs/common'; import {
import { GroupsService } from './groups.service'; Controller,
import { ISearchQuery } from 'apps/backend/src/app/groups/groups.types'; DefaultValuePipe,
Delete,
Get,
Param,
ParseIntPipe,
Post,
Query,
} from "@nestjs/common";
import { ISearchQuery } from "apps/backend/src/app/groups/groups.types";
import { GroupsService } from "./groups.service";
@Controller('groups') @Controller("groups")
export class GroupsController { export class GroupsController {
constructor(private readonly groupsService: GroupsService) {} constructor(private readonly groupsService: GroupsService) {}
@ -11,23 +20,18 @@ export class GroupsController {
async findMany( async findMany(
@Query("limit", new DefaultValuePipe(20), ParseIntPipe) limit: number, @Query("limit", new DefaultValuePipe(20), ParseIntPipe) limit: number,
@Query("offset", new DefaultValuePipe(0), ParseIntPipe) offset: number, @Query("offset", new DefaultValuePipe(0), ParseIntPipe) offset: number,
@Query("search", new DefaultValuePipe("")) search: string @Query("search", new DefaultValuePipe("")) search: string,
) { ) {
const query = {limit, offset, search} const query = { limit, offset, search };
} }
//POST a new group //POST a new group
@Post("new") @Post("new")
async newGroup() { async newGroup() {}
}
//DELETE a group //DELETE a group
@Delete(":groupId") @Delete(":groupId")
async deleteGroup(@Param('groupId') groupId: string) { async deleteGroup(@Param("groupId") groupId: string) {}
}
//GET files associated to group with limit and offset //GET files associated to group with limit and offset
@Get(":groupId") @Get(":groupId")
@ -35,9 +39,8 @@ export class GroupsController {
@Query("limit", new DefaultValuePipe(20), ParseIntPipe) limit: number, @Query("limit", new DefaultValuePipe(20), ParseIntPipe) limit: number,
@Query("offset", new DefaultValuePipe(0), ParseIntPipe) offset: number, @Query("offset", new DefaultValuePipe(0), ParseIntPipe) offset: number,
@Query("search", new DefaultValuePipe("")) search: string, @Query("search", new DefaultValuePipe("")) search: string,
@Param('groupId') groupId: string @Param("groupId") groupId: string,
) { ) {
const query = {limit, offset, search} const query = { limit, offset, search };
} }
} }

View File

@ -1,6 +1,6 @@
import { Module } from '@nestjs/common'; import { Module } from "@nestjs/common";
import { GroupsService } from './groups.service'; import { GroupsController } from "./groups.controller";
import { GroupsController } from './groups.controller'; import { GroupsService } from "./groups.service";
@Module({ @Module({
controllers: [GroupsController], controllers: [GroupsController],

View File

@ -1,7 +1,7 @@
import { Test, TestingModule } from '@nestjs/testing'; import { Test, TestingModule } from "@nestjs/testing";
import { GroupsService } from './groups.service'; import { GroupsService } from "./groups.service";
describe('GroupsService', () => { describe("GroupsService", () => {
let service: GroupsService; let service: GroupsService;
beforeEach(async () => { beforeEach(async () => {
@ -12,7 +12,7 @@ describe('GroupsService', () => {
service = module.get<GroupsService>(GroupsService); service = module.get<GroupsService>(GroupsService);
}); });
it('should be defined', () => { it("should be defined", () => {
expect(service).toBeDefined(); expect(service).toBeDefined();
}); });
}); });

View File

@ -1,4 +1,4 @@
import { Injectable } from '@nestjs/common'; import { Injectable } from "@nestjs/common";
@Injectable() @Injectable()
export class GroupsService {} export class GroupsService {}

View File

@ -1,8 +1,8 @@
import { Test, TestingModule } from '@nestjs/testing'; import { Test, TestingModule } from "@nestjs/testing";
import { MachinesController } from 'apps/backend/src/app/machines/machines.controller'; import { MachinesController } from "apps/backend/src/app/machines/machines.controller";
import { MachinesService } from 'apps/backend/src/app/machines/machines.service'; import { MachinesService } from "apps/backend/src/app/machines/machines.service";
describe('MachineController', () => { describe("MachineController", () => {
let controller: MachinesController; let controller: MachinesController;
beforeEach(async () => { beforeEach(async () => {
@ -14,7 +14,7 @@ describe('MachineController', () => {
controller = module.get<MachinesController>(MachinesController); controller = module.get<MachinesController>(MachinesController);
}); });
it('should be defined', () => { it("should be defined", () => {
expect(controller).toBeDefined(); expect(controller).toBeDefined();
}); });
}); });

View File

@ -1,7 +1,16 @@
import { Controller, DefaultValuePipe, Delete, Get, Param, ParseIntPipe, Post, Query } from '@nestjs/common'; import {
import { MachinesService } from 'apps/backend/src/app/machines/machines.service'; Controller,
DefaultValuePipe,
Delete,
Get,
Param,
ParseIntPipe,
Post,
Query,
} from "@nestjs/common";
import { MachinesService } from "apps/backend/src/app/machines/machines.service";
@Controller('machines') @Controller("machines")
export class MachinesController { export class MachinesController {
constructor(private readonly machineService: MachinesService) {} constructor(private readonly machineService: MachinesService) {}
@ -9,30 +18,24 @@ export class MachinesController {
async findMany( async findMany(
@Query("limit", new DefaultValuePipe(20), ParseIntPipe) limit: number, @Query("limit", new DefaultValuePipe(20), ParseIntPipe) limit: number,
@Query("offset", new DefaultValuePipe(0), ParseIntPipe) offset: number, @Query("offset", new DefaultValuePipe(0), ParseIntPipe) offset: number,
@Query("search", new DefaultValuePipe("")) search: string @Query("search", new DefaultValuePipe("")) search: string,
) { ) {
const query = {limit, offset, search} const query = { limit, offset, search };
} }
@Post("new") @Post("new")
async newMachine() { async newMachine() {}
}
@Delete(":machineId") @Delete(":machineId")
async deleteGroup(@Param('machineId') machineId: string) { async deleteGroup(@Param("machineId") machineId: string) {}
}
@Get(":groupId") @Get(":groupId")
async getForGroup( async getForGroup(
@Query("limit", new DefaultValuePipe(20), ParseIntPipe) limit: number, @Query("limit", new DefaultValuePipe(20), ParseIntPipe) limit: number,
@Query("offset", new DefaultValuePipe(0), ParseIntPipe) offset: number, @Query("offset", new DefaultValuePipe(0), ParseIntPipe) offset: number,
@Query("search", new DefaultValuePipe("")) search: string, @Query("search", new DefaultValuePipe("")) search: string,
@Param('machineId') machineId: string @Param("machineId") machineId: string,
) { ) {
const query = {limit, offset, search} const query = { limit, offset, search };
} }
} }

View File

@ -1,6 +1,6 @@
import { Module } from '@nestjs/common'; import { Module } from "@nestjs/common";
import { MachinesService } from 'apps/backend/src/app/machines/machines.service'; import { MachinesController } from "apps/backend/src/app/machines/machines.controller";
import { MachinesController } from 'apps/backend/src/app/machines/machines.controller'; import { MachinesService } from "apps/backend/src/app/machines/machines.service";
@Module({ @Module({
controllers: [MachinesController], controllers: [MachinesController],

View File

@ -1,7 +1,7 @@
import { Test, TestingModule } from '@nestjs/testing'; import { Test, TestingModule } from "@nestjs/testing";
import { MachinesService } from 'apps/backend/src/app/machines/machines.service'; import { MachinesService } from "apps/backend/src/app/machines/machines.service";
describe('MachinesService', () => { describe("MachinesService", () => {
let service: MachinesService; let service: MachinesService;
beforeEach(async () => { beforeEach(async () => {
@ -12,7 +12,7 @@ describe('MachinesService', () => {
service = module.get<MachinesService>(MachinesService); service = module.get<MachinesService>(MachinesService);
}); });
it('should be defined', () => { it("should be defined", () => {
expect(service).toBeDefined(); expect(service).toBeDefined();
}); });
}); });

View File

@ -1,4 +1,4 @@
import { Injectable } from '@nestjs/common'; import { Injectable } from "@nestjs/common";
@Injectable() @Injectable()
export class MachinesService {} export class MachinesService {}

View File

@ -1,6 +1,6 @@
import { Module } from "@nestjs/common"; import { Module } from "@nestjs/common";
import { DbModule } from "apps/backend/src/app/db/db.module";
import { StorageService } from "apps/backend/src/app/storage/storage.service"; import { StorageService } from "apps/backend/src/app/storage/storage.service";
import { DbModule } from 'apps/backend/src/app/db/db.module';
@Module({ @Module({
imports: [DbModule], imports: [DbModule],

View File

@ -8,11 +8,14 @@ import {
InternalServerErrorException, InternalServerErrorException,
NotFoundException, NotFoundException,
} from "@nestjs/common"; } from "@nestjs/common";
import { DbService } from "apps/backend/src/app/db/db.service";
import {
FilesTypeForMachine,
FilesTypesTable,
} from "apps/backend/src/app/db/schema";
import { IFileInformation } from "apps/backend/src/app/storage/storage.types";
import { eq } from "drizzle-orm";
import FileType from "file-type"; import FileType from "file-type";
import { DbService } from 'apps/backend/src/app/db/db.service';
import { IFileInformation } from 'apps/backend/src/app/storage/storage.types';
import { FilesTypeForMachine, FilesTypesTable } from 'apps/backend/src/app/db/schema';
import { eq } from 'drizzle-orm';
@Injectable() @Injectable()
export class StorageService { export class StorageService {
@ -20,7 +23,6 @@ export class StorageService {
private maxFileSize = 256; // MiB unit private maxFileSize = 256; // MiB unit
constructor(private readonly dbService: DbService) {} constructor(private readonly dbService: DbService) {}
/** /**
* Save a file to the specified directory. * Save a file to the specified directory.
* *
@ -44,8 +46,10 @@ export class StorageService {
* @param {Buffer} file - The file to check. * @param {Buffer} file - The file to check.
* @return {Promise<boolean>} - A Promise that resolves to true if the conditions are met, false otherwise. * @return {Promise<boolean>} - A Promise that resolves to true if the conditions are met, false otherwise.
*/ */
private async checkConditions(machineIds: Array<string>,file: Buffer): Promise<boolean> { private async checkConditions(
machineIds: Array<string>,
file: Buffer,
): Promise<boolean> {
/** /**
* Checks if the current MIME type is allowed based on the given set of allowed MIME types. * Checks if the current MIME type is allowed based on the given set of allowed MIME types.
* @param {Set<string>} allowedMime - The set of allowed MIME types. * @param {Set<string>} allowedMime - The set of allowed MIME types.
@ -60,53 +64,55 @@ export class StorageService {
const fileType = await FileType.fileTypeFromBuffer(file); const fileType = await FileType.fileTypeFromBuffer(file);
// Array of MIMEs with possible duplicate field // Array of MIMEs with possible duplicate field
const _mimes: Array<string> = [] const _mimes: Array<string> = [];
// Fetching MIMEs for the associated machines // Fetching MIMEs for the associated machines
for (const machineId of machineIds) { for (const machineId of machineIds) {
console.debug(`Fetching mimeTypes for machine : ${machineId}`) console.debug(`Fetching mimeTypes for machine : ${machineId}`);
// Get MIMEs associated to a machine // Get MIMEs associated to a machine
const allowedMimeId = this.dbService.use() const allowedMimeId = this.dbService
.use()
.select() .select()
.from(FilesTypeForMachine) .from(FilesTypeForMachine)
.where(eq(FilesTypeForMachine.machineId, machineId)).as("allowedMimeId"); .where(eq(FilesTypeForMachine.machineId, machineId))
const _allowedMime = await this.dbService.use() .as("allowedMimeId");
const _allowedMime = await this.dbService
.use()
.select({ .select({
slug: FilesTypesTable.mime, slug: FilesTypesTable.mime,
name: FilesTypesTable.typeName name: FilesTypesTable.typeName,
}) })
.from(FilesTypesTable) .from(FilesTypesTable)
.leftJoin(allowedMimeId, eq(FilesTypesTable.id, allowedMimeId.fileTypeId)) .leftJoin(
console.debug(`Total : ${_allowedMime.length}`) allowedMimeId,
eq(FilesTypesTable.id, allowedMimeId.fileTypeId),
);
console.debug(`Total : ${_allowedMime.length}`);
// Append each MIME of a machine // Append each MIME of a machine
for (const allowedMimeElement of _allowedMime) { for (const allowedMimeElement of _allowedMime) {
_mimes.push(allowedMimeElement.slug) _mimes.push(allowedMimeElement.slug);
} }
} }
//Store the MIMEs without duplicate //Store the MIMEs without duplicate
const mimeSet = new Set(_mimes) const mimeSet = new Set(_mimes);
console.debug(`Indexed ${mimeSet.size} unique mimeTypes`) console.debug(`Indexed ${mimeSet.size} unique mimeTypes`);
//check file size is less than 2mb //check file size is less than 2mb
const fileSize = file.byteLength; const fileSize = file.byteLength;
if (fileSize > this.maxFileSize * (1024 * 1024)) { if (fileSize > this.maxFileSize * (1024 * 1024)) {
throw new BadRequestException( throw new BadRequestException("File size to high.", {
"File size to high.",
{
cause: "File size", cause: "File size",
description: `File size exceeds the limit. Maximum file size allowed is ${this.maxFileSize}MiB.` description: `File size exceeds the limit. Maximum file size allowed is ${this.maxFileSize}MiB.`,
} });
);
} }
if (!checkMime(mimeSet, fileType.mime)) throw new BadRequestException( if (!checkMime(mimeSet, fileType.mime))
{ throw new BadRequestException({
cause: "MIME type", cause: "MIME type",
description: `Invalid MIME type. Allowed MIME types are: ${[...mimeSet].join(", ")}.` description: `Invalid MIME type. Allowed MIME types are: ${[...mimeSet].join(", ")}.`,
} });
)
return true return true;
} }
/** /**
@ -133,12 +139,16 @@ export class StorageService {
public async getChecksum(file: Buffer): Promise<string> { public async getChecksum(file: Buffer): Promise<string> {
return new Promise((resolve) => { return new Promise((resolve) => {
try { try {
const checksum = crypto.createHash("sha256").update(file).digest("hex").toLowerCase(); const checksum = crypto
resolve(checksum) .createHash("sha256")
.update(file)
.digest("hex")
.toLowerCase();
resolve(checksum);
} catch (err) { } catch (err) {
throw new InternalServerErrorException(err) throw new InternalServerErrorException(err);
} }
}) });
} }
/** /**
@ -149,9 +159,13 @@ export class StorageService {
* @param {boolean} [isDocumentation] - Optional flag to indicate if the file is a documentation file. * @param {boolean} [isDocumentation] - Optional flag to indicate if the file is a documentation file.
* @returns {Promise<IFileInformation>} - A Promise that resolves to the generated file information. * @returns {Promise<IFileInformation>} - A Promise that resolves to the generated file information.
*/ */
public async generateInformation(file: Buffer, fileDisplayName: string, isDocumentation?: boolean): Promise<IFileInformation> { public async generateInformation(
file: Buffer,
fileDisplayName: string,
isDocumentation?: boolean,
): Promise<IFileInformation> {
const fileType = await FileType.fileTypeFromBuffer(file); const fileType = await FileType.fileTypeFromBuffer(file);
const checksum = await this.getChecksum(file) const checksum = await this.getChecksum(file);
const fileName = `${isDocumentation ? "doc" : "file"}-${checksum}.${fileType.ext.toLowerCase()}`; const fileName = `${isDocumentation ? "doc" : "file"}-${checksum}.${fileType.ext.toLowerCase()}`;
return { return {
fileName: fileName, fileName: fileName,
@ -159,24 +173,39 @@ export class StorageService {
fileSize: file.byteLength, fileSize: file.byteLength,
fileChecksum: checksum, fileChecksum: checksum,
fileType: fileType, fileType: fileType,
isDocumentation: isDocumentation || false isDocumentation: isDocumentation || false,
} };
} }
public async new(fileDisplayName: string, file: Buffer, isDocumentation?: boolean) { public async new(
fileDisplayName: string,
file: Buffer,
isDocumentation?: boolean,
) {
try { try {
const info = await this.generateInformation(file, fileDisplayName, isDocumentation); const info = await this.generateInformation(
console.log(`Trying to append a new file : "${info.fileDisplayName}"...\n > Checksum SHA-256 : ${info.fileChecksum}\n > Size : ${info.fileSize / (1024*1024)}Mio\n > File format : ${info.fileType.mime}\n`) file,
const condition = await this.checkConditions([/* TODO import autorized file format */], file) fileDisplayName,
isDocumentation,
);
console.log(
`Trying to append a new file : "${info.fileDisplayName}"...\n > Checksum SHA-256 : ${info.fileChecksum}\n > Size : ${info.fileSize / (1024 * 1024)}Mio\n > File format : ${info.fileType.mime}\n`,
);
const condition = await this.checkConditions(
[
/* TODO import autorized file format */
],
file,
);
if (!condition) { if (!condition) {
console.warn(`File "${info.fileDisplayName}" did not pass the files requirement.\n${info.fileChecksum}`) console.warn(
`File "${info.fileDisplayName}" did not pass the files requirement.\n${info.fileChecksum}`,
);
} }
//TODO Append in DB and save to storage //TODO Append in DB and save to storage
} catch (err) { } catch (err) {
throw new BadRequestException(err) throw new BadRequestException(err);
} }
} }
} }

View File

@ -1,5 +1,4 @@
import FileType from 'file-type'; import FileType from "file-type";
export interface IFileInformation { export interface IFileInformation {
fileDisplayName: string; fileDisplayName: string;
@ -13,5 +12,5 @@ export interface IFileInformation {
export interface IFileWithInformation<AdditionalData> { export interface IFileWithInformation<AdditionalData> {
buffer: Buffer; buffer: Buffer;
info: IFileInformation; info: IFileInformation;
additionalData?: AdditionalData additionalData?: AdditionalData;
} }

View File

@ -1,78 +1,75 @@
"use client" "use client";
// Inspired by react-hot-toast library // Inspired by react-hot-toast library
import * as React from "react" import * as React from "react";
import type { import type { ToastActionElement, ToastProps } from "./toast";
ToastActionElement,
ToastProps,
} from "./toast"
const TOAST_LIMIT = 1 const TOAST_LIMIT = 1;
const TOAST_REMOVE_DELAY = 1000000 const TOAST_REMOVE_DELAY = 1000000;
type ToasterToast = ToastProps & { type ToasterToast = ToastProps & {
id: string id: string;
title?: React.ReactNode title?: React.ReactNode;
description?: React.ReactNode description?: React.ReactNode;
action?: ToastActionElement action?: ToastActionElement;
} };
const actionTypes = { const actionTypes = {
ADD_TOAST: "ADD_TOAST", ADD_TOAST: "ADD_TOAST",
UPDATE_TOAST: "UPDATE_TOAST", UPDATE_TOAST: "UPDATE_TOAST",
DISMISS_TOAST: "DISMISS_TOAST", DISMISS_TOAST: "DISMISS_TOAST",
REMOVE_TOAST: "REMOVE_TOAST", REMOVE_TOAST: "REMOVE_TOAST",
} as const } as const;
let count = 0 let count = 0;
function genId() { function genId() {
count = (count + 1) % Number.MAX_SAFE_INTEGER count = (count + 1) % Number.MAX_SAFE_INTEGER;
return count.toString() return count.toString();
} }
type ActionType = typeof actionTypes type ActionType = typeof actionTypes;
type Action = type Action =
| { | {
type: ActionType["ADD_TOAST"] type: ActionType["ADD_TOAST"];
toast: ToasterToast toast: ToasterToast;
} }
| { | {
type: ActionType["UPDATE_TOAST"] type: ActionType["UPDATE_TOAST"];
toast: Partial<ToasterToast> toast: Partial<ToasterToast>;
} }
| { | {
type: ActionType["DISMISS_TOAST"] type: ActionType["DISMISS_TOAST"];
toastId?: ToasterToast["id"] toastId?: ToasterToast["id"];
} }
| { | {
type: ActionType["REMOVE_TOAST"] type: ActionType["REMOVE_TOAST"];
toastId?: ToasterToast["id"] toastId?: ToasterToast["id"];
} };
interface State { interface State {
toasts: ToasterToast[] toasts: ToasterToast[];
} }
const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>() const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>();
const addToRemoveQueue = (toastId: string) => { const addToRemoveQueue = (toastId: string) => {
if (toastTimeouts.has(toastId)) { if (toastTimeouts.has(toastId)) {
return return;
} }
const timeout = setTimeout(() => { const timeout = setTimeout(() => {
toastTimeouts.delete(toastId) toastTimeouts.delete(toastId);
dispatch({ dispatch({
type: "REMOVE_TOAST", type: "REMOVE_TOAST",
toastId: toastId, toastId: toastId,
}) });
}, TOAST_REMOVE_DELAY) }, TOAST_REMOVE_DELAY);
toastTimeouts.set(toastId, timeout) toastTimeouts.set(toastId, timeout);
} };
export const reducer = (state: State, action: Action): State => { export const reducer = (state: State, action: Action): State => {
switch (action.type) { switch (action.type) {
@ -80,26 +77,26 @@ export const reducer = (state: State, action: Action): State => {
return { return {
...state, ...state,
toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT), toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT),
} };
case "UPDATE_TOAST": case "UPDATE_TOAST":
return { return {
...state, ...state,
toasts: state.toasts.map((t) => toasts: state.toasts.map((t) =>
t.id === action.toast.id ? { ...t, ...action.toast } : t t.id === action.toast.id ? { ...t, ...action.toast } : t,
), ),
} };
case "DISMISS_TOAST": { case "DISMISS_TOAST": {
const { toastId } = action const { toastId } = action;
// ! Side effects ! - This could be extracted into a dismissToast() action, // ! Side effects ! - This could be extracted into a dismissToast() action,
// but I'll keep it here for simplicity // but I'll keep it here for simplicity
if (toastId) { if (toastId) {
addToRemoveQueue(toastId) addToRemoveQueue(toastId);
} else { } else {
for (const toast1 of state.toasts) { for (const toast1 of state.toasts) {
addToRemoveQueue(toast1.id) addToRemoveQueue(toast1.id);
} }
} }
@ -111,46 +108,46 @@ export const reducer = (state: State, action: Action): State => {
...t, ...t,
open: false, open: false,
} }
: t : t,
), ),
} };
} }
case "REMOVE_TOAST": case "REMOVE_TOAST":
if (action.toastId === undefined) { if (action.toastId === undefined) {
return { return {
...state, ...state,
toasts: [], toasts: [],
} };
} }
return { return {
...state, ...state,
toasts: state.toasts.filter((t) => t.id !== action.toastId), toasts: state.toasts.filter((t) => t.id !== action.toastId),
};
} }
} };
}
const listeners: Array<(state: State) => void> = [] const listeners: Array<(state: State) => void> = [];
let memoryState: State = { toasts: [] } let memoryState: State = { toasts: [] };
function dispatch(action: Action) { function dispatch(action: Action) {
memoryState = reducer(memoryState, action) memoryState = reducer(memoryState, action);
for (const listener of listeners) { for (const listener of listeners) {
listener(memoryState) listener(memoryState);
} }
} }
type Toast = Omit<ToasterToast, "id"> type Toast = Omit<ToasterToast, "id">;
function toast({ ...props }: Toast) { function toast({ ...props }: Toast) {
const id = genId() const id = genId();
const update = (props: ToasterToast) => const update = (props: ToasterToast) =>
dispatch({ dispatch({
type: "UPDATE_TOAST", type: "UPDATE_TOAST",
toast: { ...props, id }, toast: { ...props, id },
}) });
const dismiss = () => dispatch({ type: "DISMISS_TOAST", toastId: id }) const dismiss = () => dispatch({ type: "DISMISS_TOAST", toastId: id });
dispatch({ dispatch({
type: "ADD_TOAST", type: "ADD_TOAST",
@ -159,37 +156,37 @@ function toast({ ...props }: Toast) {
id, id,
open: true, open: true,
onOpenChange: (open) => { onOpenChange: (open) => {
if (!open) dismiss() if (!open) dismiss();
}, },
}, },
}) });
return { return {
id: id, id: id,
dismiss, dismiss,
update, update,
} };
} }
function useToast() { function useToast() {
const [state, setState] = React.useState<State>(memoryState) const [state, setState] = React.useState<State>(memoryState);
// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation> // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
React.useEffect(() => { React.useEffect(() => {
listeners.push(setState) listeners.push(setState);
return () => { return () => {
const index = listeners.indexOf(setState) const index = listeners.indexOf(setState);
if (index > -1) { if (index > -1) {
listeners.splice(index, 1) listeners.splice(index, 1);
} }
} };
}, [state]) }, [state]);
return { return {
...state, ...state,
toast, toast,
dismiss: (toastId?: string) => dispatch({ type: "DISMISS_TOAST", toastId }), dismiss: (toastId?: string) => dispatch({ type: "DISMISS_TOAST", toastId }),
} };
} }
export { useToast, toast } export { useToast, toast };

View File

@ -1,6 +1,6 @@
import { type ClassValue, clsx } from "clsx" import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge" import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) { export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs)) return twMerge(clsx(inputs));
} }