init equipment & change-status
This commit is contained in:
6
server/.env.example
Normal file
6
server/.env.example
Normal file
@@ -0,0 +1,6 @@
|
||||
PORT=3000
|
||||
DATABASE_URL="postgresql://postgres:postgres@localhost:5432/toir"
|
||||
CORS_ALLOWED_ORIGINS="http://localhost:5173,https://toir-frontend.greact.ru"
|
||||
KEYCLOAK_ISSUER_URL="https://sso.greact.ru/realms/toir"
|
||||
KEYCLOAK_AUDIENCE="toir-backend"
|
||||
KEYCLOAK_JWKS_URL=""
|
||||
5
server/.gitignore
vendored
Normal file
5
server/.gitignore
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
node_modules
|
||||
# Keep environment variables out of version control
|
||||
.env
|
||||
|
||||
/generated/prisma
|
||||
4
server/.prettierrc
Normal file
4
server/.prettierrc
Normal file
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"singleQuote": true,
|
||||
"trailingComma": "all"
|
||||
}
|
||||
98
server/README.md
Normal file
98
server/README.md
Normal file
@@ -0,0 +1,98 @@
|
||||
<p align="center">
|
||||
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="120" alt="Nest Logo" /></a>
|
||||
</p>
|
||||
|
||||
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
|
||||
[circleci-url]: https://circleci.com/gh/nestjs/nest
|
||||
|
||||
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
|
||||
<p align="center">
|
||||
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
|
||||
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
|
||||
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
|
||||
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
|
||||
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
|
||||
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
|
||||
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
|
||||
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg" alt="Donate us"/></a>
|
||||
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
|
||||
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow" alt="Follow us on Twitter"></a>
|
||||
</p>
|
||||
<!--[](https://opencollective.com/nest#backer)
|
||||
[](https://opencollective.com/nest#sponsor)-->
|
||||
|
||||
## Description
|
||||
|
||||
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
|
||||
|
||||
## Project setup
|
||||
|
||||
```bash
|
||||
$ npm install
|
||||
```
|
||||
|
||||
## Compile and run the project
|
||||
|
||||
```bash
|
||||
# development
|
||||
$ npm run start
|
||||
|
||||
# watch mode
|
||||
$ npm run start:dev
|
||||
|
||||
# production mode
|
||||
$ npm run start:prod
|
||||
```
|
||||
|
||||
## Run tests
|
||||
|
||||
```bash
|
||||
# unit tests
|
||||
$ npm run test
|
||||
|
||||
# e2e tests
|
||||
$ npm run test:e2e
|
||||
|
||||
# test coverage
|
||||
$ npm run test:cov
|
||||
```
|
||||
|
||||
## Deployment
|
||||
|
||||
When you're ready to deploy your NestJS application to production, there are some key steps you can take to ensure it runs as efficiently as possible. Check out the [deployment documentation](https://docs.nestjs.com/deployment) for more information.
|
||||
|
||||
If you are looking for a cloud-based platform to deploy your NestJS application, check out [Mau](https://mau.nestjs.com), our official platform for deploying NestJS applications on AWS. Mau makes deployment straightforward and fast, requiring just a few simple steps:
|
||||
|
||||
```bash
|
||||
$ npm install -g @nestjs/mau
|
||||
$ mau deploy
|
||||
```
|
||||
|
||||
With Mau, you can deploy your application in just a few clicks, allowing you to focus on building features rather than managing infrastructure.
|
||||
|
||||
## Resources
|
||||
|
||||
Check out a few resources that may come in handy when working with NestJS:
|
||||
|
||||
- Visit the [NestJS Documentation](https://docs.nestjs.com) to learn more about the framework.
|
||||
- For questions and support, please visit our [Discord channel](https://discord.gg/G7Qnnhy).
|
||||
- To dive deeper and get more hands-on experience, check out our official video [courses](https://courses.nestjs.com/).
|
||||
- Deploy your application to AWS with the help of [NestJS Mau](https://mau.nestjs.com) in just a few clicks.
|
||||
- Visualize your application graph and interact with the NestJS application in real-time using [NestJS Devtools](https://devtools.nestjs.com).
|
||||
- Need help with your project (part-time to full-time)? Check out our official [enterprise support](https://enterprise.nestjs.com).
|
||||
- To stay in the loop and get updates, follow us on [X](https://x.com/nestframework) and [LinkedIn](https://linkedin.com/company/nestjs).
|
||||
- Looking for a job, or have a job to offer? Check out our official [Jobs board](https://jobs.nestjs.com).
|
||||
|
||||
## Support
|
||||
|
||||
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
|
||||
|
||||
## Stay in touch
|
||||
|
||||
- Author - [Kamil Myśliwiec](https://twitter.com/kammysliwiec)
|
||||
- Website - [https://nestjs.com](https://nestjs.com/)
|
||||
- Twitter - [@nestframework](https://twitter.com/nestframework)
|
||||
|
||||
## License
|
||||
|
||||
Nest is [MIT licensed](https://github.com/nestjs/nest/blob/master/LICENSE).
|
||||
35
server/eslint.config.mjs
Normal file
35
server/eslint.config.mjs
Normal file
@@ -0,0 +1,35 @@
|
||||
// @ts-check
|
||||
import eslint from '@eslint/js';
|
||||
import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended';
|
||||
import globals from 'globals';
|
||||
import tseslint from 'typescript-eslint';
|
||||
|
||||
export default tseslint.config(
|
||||
{
|
||||
ignores: ['eslint.config.mjs'],
|
||||
},
|
||||
eslint.configs.recommended,
|
||||
...tseslint.configs.recommendedTypeChecked,
|
||||
eslintPluginPrettierRecommended,
|
||||
{
|
||||
languageOptions: {
|
||||
globals: {
|
||||
...globals.node,
|
||||
...globals.jest,
|
||||
},
|
||||
sourceType: 'commonjs',
|
||||
parserOptions: {
|
||||
projectService: true,
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
rules: {
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
'@typescript-eslint/no-floating-promises': 'warn',
|
||||
'@typescript-eslint/no-unsafe-argument': 'warn',
|
||||
"prettier/prettier": ["error", { endOfLine: "auto" }],
|
||||
},
|
||||
},
|
||||
);
|
||||
8
server/nest-cli.json
Normal file
8
server/nest-cli.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/nest-cli",
|
||||
"collection": "@nestjs/schematics",
|
||||
"sourceRoot": "src",
|
||||
"compilerOptions": {
|
||||
"deleteOutDir": true
|
||||
}
|
||||
}
|
||||
11286
server/package-lock.json
generated
Normal file
11286
server/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
81
server/package.json
Normal file
81
server/package.json
Normal file
@@ -0,0 +1,81 @@
|
||||
{
|
||||
"name": "server",
|
||||
"version": "0.0.1",
|
||||
"description": "",
|
||||
"author": "",
|
||||
"private": true,
|
||||
"license": "UNLICENSED",
|
||||
"scripts": {
|
||||
"build": "nest build",
|
||||
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||
"start": "nest start",
|
||||
"start:dev": "nest start --watch",
|
||||
"start:debug": "nest start --debug --watch",
|
||||
"start:prod": "node dist/main",
|
||||
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
||||
"test": "jest",
|
||||
"test:watch": "jest --watch",
|
||||
"test:cov": "jest --coverage",
|
||||
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
|
||||
"test:e2e": "jest --config ./test/jest-e2e.json"
|
||||
},
|
||||
"dependencies": {
|
||||
"@nestjs/common": "^11.0.1",
|
||||
"@nestjs/config": "^4.0.3",
|
||||
"@nestjs/core": "^11.0.1",
|
||||
"@nestjs/platform-express": "^11.0.1",
|
||||
"@prisma/adapter-pg": "^7.6.0",
|
||||
"@prisma/client": "^7.6.0",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.15.1",
|
||||
"dotenv": "^17.4.0",
|
||||
"jose": "^6.2.2",
|
||||
"pg": "^8.20.0",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"rxjs": "^7.8.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/eslintrc": "^3.2.0",
|
||||
"@eslint/js": "^9.18.0",
|
||||
"@nestjs/cli": "^11.0.0",
|
||||
"@nestjs/schematics": "^11.0.0",
|
||||
"@nestjs/testing": "^11.0.1",
|
||||
"@types/express": "^5.0.0",
|
||||
"@types/jest": "^30.0.0",
|
||||
"@types/node": "^24.0.0",
|
||||
"@types/pg": "^8.20.0",
|
||||
"@types/supertest": "^7.0.0",
|
||||
"eslint": "^9.18.0",
|
||||
"eslint-config-prettier": "^10.0.1",
|
||||
"eslint-plugin-prettier": "^5.2.2",
|
||||
"globals": "^17.0.0",
|
||||
"jest": "^30.0.0",
|
||||
"prettier": "^3.4.2",
|
||||
"prisma": "^7.6.0",
|
||||
"source-map-support": "^0.5.21",
|
||||
"supertest": "^7.0.0",
|
||||
"ts-jest": "^29.2.5",
|
||||
"ts-loader": "^9.5.2",
|
||||
"ts-node": "^10.9.2",
|
||||
"tsconfig-paths": "^4.2.0",
|
||||
"typescript": "^5.7.3",
|
||||
"typescript-eslint": "^8.20.0"
|
||||
},
|
||||
"jest": {
|
||||
"moduleFileExtensions": [
|
||||
"js",
|
||||
"json",
|
||||
"ts"
|
||||
],
|
||||
"rootDir": "src",
|
||||
"testRegex": ".*\\.spec\\.ts$",
|
||||
"transform": {
|
||||
"^.+\\.(t|j)s$": "ts-jest"
|
||||
},
|
||||
"collectCoverageFrom": [
|
||||
"**/*.(t|j)s"
|
||||
],
|
||||
"coverageDirectory": "../coverage",
|
||||
"testEnvironment": "node"
|
||||
}
|
||||
}
|
||||
14
server/prisma.config.ts
Normal file
14
server/prisma.config.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
// This file was generated by Prisma, and assumes you have installed the following:
|
||||
// npm install --save-dev prisma dotenv
|
||||
import "dotenv/config";
|
||||
import { defineConfig, env } from "prisma/config";
|
||||
|
||||
export default defineConfig({
|
||||
schema: "prisma/schema.prisma",
|
||||
migrations: {
|
||||
path: "prisma/migrations",
|
||||
},
|
||||
datasource: {
|
||||
url: env("DATABASE_URL"),
|
||||
},
|
||||
});
|
||||
34
server/prisma/schema.prisma
Normal file
34
server/prisma/schema.prisma
Normal file
@@ -0,0 +1,34 @@
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
}
|
||||
|
||||
datasource db {
|
||||
provider = "postgresql"
|
||||
}
|
||||
|
||||
enum EquipmentStatus {
|
||||
Active
|
||||
Repair
|
||||
Reserve
|
||||
WriteOff
|
||||
}
|
||||
|
||||
model Equipment {
|
||||
id String @id @default(uuid())
|
||||
name String
|
||||
serialNumber String
|
||||
dateOfInspection DateTime?
|
||||
commissionedAt DateTime?
|
||||
status EquipmentStatus @default(Active)
|
||||
changeEquipmentStatuses ChangeEquipmentStatus[]
|
||||
}
|
||||
|
||||
model ChangeEquipmentStatus {
|
||||
id String @id @default(uuid())
|
||||
equipmentId String?
|
||||
equipment Equipment? @relation(fields: [equipmentId], references: [id])
|
||||
newStatus EquipmentStatus
|
||||
number String?
|
||||
date DateTime
|
||||
responsible String?
|
||||
}
|
||||
22
server/src/app.controller.spec.ts
Normal file
22
server/src/app.controller.spec.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { AppController } from './app.controller';
|
||||
import { AppService } from './app.service';
|
||||
|
||||
describe('AppController', () => {
|
||||
let appController: AppController;
|
||||
|
||||
beforeEach(async () => {
|
||||
const app: TestingModule = await Test.createTestingModule({
|
||||
controllers: [AppController],
|
||||
providers: [AppService],
|
||||
}).compile();
|
||||
|
||||
appController = app.get<AppController>(AppController);
|
||||
});
|
||||
|
||||
describe('root', () => {
|
||||
it('should return "Hello World!"', () => {
|
||||
expect(appController.getHello()).toBe('Hello World!');
|
||||
});
|
||||
});
|
||||
});
|
||||
12
server/src/app.controller.ts
Normal file
12
server/src/app.controller.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
import { AppService } from './app.service';
|
||||
|
||||
@Controller()
|
||||
export class AppController {
|
||||
constructor(private readonly appService: AppService) {}
|
||||
|
||||
@Get()
|
||||
getHello(): string {
|
||||
return this.appService.getHello();
|
||||
}
|
||||
}
|
||||
19
server/src/app.module.ts
Normal file
19
server/src/app.module.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { AuthModule } from './auth/auth.module';
|
||||
import { HealthModule } from './health/health.module';
|
||||
import { EquipmentModule } from './modules/equipment/equipment.module';
|
||||
import { EquipmentStatusChangeModule } from './modules/equipment-status-change/equipment-status-change.module';
|
||||
import { PrismaModule } from './prisma/prisma.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot({ isGlobal: true }),
|
||||
PrismaModule,
|
||||
AuthModule,
|
||||
HealthModule,
|
||||
EquipmentModule,
|
||||
EquipmentStatusChangeModule,
|
||||
],
|
||||
})
|
||||
export class AppModule {}
|
||||
8
server/src/app.service.ts
Normal file
8
server/src/app.service.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
@Injectable()
|
||||
export class AppService {
|
||||
getHello(): string {
|
||||
return 'Hello World!';
|
||||
}
|
||||
}
|
||||
23
server/src/auth/auth.module.ts
Normal file
23
server/src/auth/auth.module.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { APP_GUARD } from '@nestjs/core';
|
||||
import { AuthService } from './auth.service';
|
||||
import { JwtAuthGuard } from './guards/jwt-auth.guard';
|
||||
import { RolesGuard } from './guards/roles.guard';
|
||||
|
||||
@Module({
|
||||
providers: [
|
||||
AuthService,
|
||||
JwtAuthGuard,
|
||||
RolesGuard,
|
||||
{
|
||||
provide: APP_GUARD,
|
||||
useClass: JwtAuthGuard,
|
||||
},
|
||||
{
|
||||
provide: APP_GUARD,
|
||||
useClass: RolesGuard,
|
||||
},
|
||||
],
|
||||
exports: [AuthService, JwtAuthGuard, RolesGuard],
|
||||
})
|
||||
export class AuthModule {}
|
||||
102
server/src/auth/auth.service.ts
Normal file
102
server/src/auth/auth.service.ts
Normal file
@@ -0,0 +1,102 @@
|
||||
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
||||
import { createRemoteJWKSet, jwtVerify, JWTPayload } from 'jose';
|
||||
|
||||
export type AuthenticatedUser = {
|
||||
sub: string;
|
||||
roles: string[];
|
||||
token: JWTPayload;
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
private jwksCache = new Map<string, ReturnType<typeof createRemoteJWKSet>>();
|
||||
|
||||
async verifyBearerToken(authorizationHeader?: string): Promise<AuthenticatedUser> {
|
||||
const token = this.extractBearerToken(authorizationHeader);
|
||||
if (!token) {
|
||||
throw new UnauthorizedException('Missing bearer token');
|
||||
}
|
||||
|
||||
const issuer = process.env.KEYCLOAK_ISSUER_URL;
|
||||
const audience = process.env.KEYCLOAK_AUDIENCE;
|
||||
|
||||
if (!issuer || !audience) {
|
||||
throw new UnauthorizedException('Keycloak issuer or audience is not configured');
|
||||
}
|
||||
|
||||
const jwks = await this.resolveJwks(issuer);
|
||||
const { payload } = await jwtVerify(token, jwks, {
|
||||
issuer,
|
||||
audience,
|
||||
});
|
||||
|
||||
const realmAccess = payload.realm_access as { roles?: string[] } | undefined;
|
||||
|
||||
return {
|
||||
sub: String(payload.sub ?? ''),
|
||||
roles: Array.isArray(realmAccess?.roles) ? realmAccess.roles : [],
|
||||
token: payload,
|
||||
};
|
||||
}
|
||||
|
||||
private extractBearerToken(authorizationHeader?: string) {
|
||||
if (!authorizationHeader) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const [scheme, token] = authorizationHeader.split(' ');
|
||||
if (scheme !== 'Bearer' || !token) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return token;
|
||||
}
|
||||
|
||||
private async resolveJwks(issuer: string) {
|
||||
const candidates = await this.buildJwksCandidates(issuer);
|
||||
|
||||
let lastError: unknown;
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
if (!this.jwksCache.has(candidate)) {
|
||||
this.jwksCache.set(candidate, createRemoteJWKSet(new URL(candidate)));
|
||||
}
|
||||
|
||||
return this.jwksCache.get(candidate)!;
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
}
|
||||
}
|
||||
|
||||
throw new UnauthorizedException(
|
||||
`Unable to resolve JWKS for issuer ${issuer}: ${lastError instanceof Error ? lastError.message : 'unknown error'}`,
|
||||
);
|
||||
}
|
||||
|
||||
private async buildJwksCandidates(issuer: string) {
|
||||
const urls: string[] = [];
|
||||
|
||||
if (process.env.KEYCLOAK_JWKS_URL) {
|
||||
urls.push(process.env.KEYCLOAK_JWKS_URL);
|
||||
}
|
||||
|
||||
const normalizedIssuer = issuer.replace(/\/$/, '');
|
||||
const discoveryUrl = `${normalizedIssuer}/.well-known/openid-configuration`;
|
||||
|
||||
try {
|
||||
const response = await fetch(discoveryUrl);
|
||||
if (response.ok) {
|
||||
const document = (await response.json()) as { jwks_uri?: string };
|
||||
if (document.jwks_uri) {
|
||||
urls.push(document.jwks_uri);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Try the Keycloak certs endpoint below if discovery fails.
|
||||
}
|
||||
|
||||
urls.push(`${normalizedIssuer}/protocol/openid-connect/certs`);
|
||||
|
||||
return [...new Set(urls)];
|
||||
}
|
||||
}
|
||||
4
server/src/auth/decorators/public.decorator.ts
Normal file
4
server/src/auth/decorators/public.decorator.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
|
||||
export const IS_PUBLIC_KEY = 'isPublic';
|
||||
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);
|
||||
4
server/src/auth/decorators/roles.decorator.ts
Normal file
4
server/src/auth/decorators/roles.decorator.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
|
||||
export const ROLES_KEY = 'roles';
|
||||
export const Roles = (...roles: string[]) => SetMetadata(ROLES_KEY, roles);
|
||||
39
server/src/auth/guards/jwt-auth.guard.ts
Normal file
39
server/src/auth/guards/jwt-auth.guard.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { Request } from 'express';
|
||||
import { AuthService } from '../auth.service';
|
||||
import { IS_PUBLIC_KEY } from '../decorators/public.decorator';
|
||||
|
||||
@Injectable()
|
||||
export class JwtAuthGuard implements CanActivate {
|
||||
constructor(
|
||||
private readonly reflector: Reflector,
|
||||
private readonly authService: AuthService,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext) {
|
||||
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
|
||||
context.getHandler(),
|
||||
context.getClass(),
|
||||
]);
|
||||
|
||||
if (isPublic) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const request = context.switchToHttp().getRequest<Request & { user?: unknown }>();
|
||||
const user = await this.authService.verifyBearerToken(request.headers.authorization);
|
||||
|
||||
if (!user.sub) {
|
||||
throw new UnauthorizedException('Token subject is missing');
|
||||
}
|
||||
|
||||
request.user = user;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
29
server/src/auth/guards/roles.guard.ts
Normal file
29
server/src/auth/guards/roles.guard.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { CanActivate, ExecutionContext, ForbiddenException, Injectable } from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { Request } from 'express';
|
||||
import { ROLES_KEY } from '../decorators/roles.decorator';
|
||||
|
||||
@Injectable()
|
||||
export class RolesGuard implements CanActivate {
|
||||
constructor(private readonly reflector: Reflector) {}
|
||||
|
||||
canActivate(context: ExecutionContext) {
|
||||
const requiredRoles = this.reflector.getAllAndOverride<string[]>(ROLES_KEY, [
|
||||
context.getHandler(),
|
||||
context.getClass(),
|
||||
]);
|
||||
|
||||
if (!requiredRoles || requiredRoles.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const request = context.switchToHttp().getRequest<Request & { user?: { roles?: string[] } }>();
|
||||
const userRoles = request.user?.roles ?? [];
|
||||
|
||||
if (requiredRoles.some((role) => userRoles.includes(role))) {
|
||||
return true;
|
||||
}
|
||||
|
||||
throw new ForbiddenException('Insufficient role');
|
||||
}
|
||||
}
|
||||
7
server/src/common/http.ts
Normal file
7
server/src/common/http.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import { Response } from 'express';
|
||||
|
||||
export function setListHeaders(response: Response, total: number, start: number, end: number) {
|
||||
const safeEnd = total === 0 ? start : Math.max(start, end - 1);
|
||||
response.setHeader('Content-Range', `items ${start}-${safeEnd}/${total}`);
|
||||
response.setHeader('Access-Control-Expose-Headers', 'Content-Range');
|
||||
}
|
||||
14
server/src/health/health.controller.ts
Normal file
14
server/src/health/health.controller.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
import { Public } from '../auth/decorators/public.decorator';
|
||||
|
||||
@Controller('health')
|
||||
export class HealthController {
|
||||
@Public()
|
||||
@Get()
|
||||
getHealth() {
|
||||
return {
|
||||
status: 'ok',
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
}
|
||||
7
server/src/health/health.module.ts
Normal file
7
server/src/health/health.module.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { HealthController } from './health.controller';
|
||||
|
||||
@Module({
|
||||
controllers: [HealthController],
|
||||
})
|
||||
export class HealthModule {}
|
||||
27
server/src/main.ts
Normal file
27
server/src/main.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { ValidationPipe } from '@nestjs/common';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { AppModule } from './app.module';
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule);
|
||||
const origins = (process.env.CORS_ALLOWED_ORIGINS ?? '')
|
||||
.split(',')
|
||||
.map((origin) => origin.trim())
|
||||
.filter(Boolean);
|
||||
|
||||
app.enableCors({
|
||||
origin: origins.length > 0 ? origins : true,
|
||||
exposedHeaders: ['Content-Range'],
|
||||
credentials: true,
|
||||
});
|
||||
app.useGlobalPipes(
|
||||
new ValidationPipe({
|
||||
whitelist: true,
|
||||
transform: true,
|
||||
}),
|
||||
);
|
||||
|
||||
await app.listen(process.env.PORT ?? 3000);
|
||||
}
|
||||
|
||||
void bootstrap();
|
||||
@@ -0,0 +1,55 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
Param,
|
||||
Patch,
|
||||
Post,
|
||||
Query,
|
||||
Res,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import type { Response } from 'express';
|
||||
import { Roles } from '../../auth/decorators/roles.decorator';
|
||||
import { JwtAuthGuard } from '../../auth/guards/jwt-auth.guard';
|
||||
import { RolesGuard } from '../../auth/guards/roles.guard';
|
||||
import { ChangeEquipmentStatusService } from './change-equipment-status.service';
|
||||
import { CreateChangeEquipmentStatusDto } from './dto/create-change-equipment-status.dto';
|
||||
import { UpdateChangeEquipmentStatusDto } from './dto/update-change-equipment-status.dto';
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Controller('change-equipment-statuses')
|
||||
export class ChangeEquipmentStatusController {
|
||||
constructor(private readonly changeEquipmentStatusService: ChangeEquipmentStatusService) {}
|
||||
|
||||
@Roles('viewer', 'editor', 'admin')
|
||||
@Get()
|
||||
findAll(@Query() query: Record<string, unknown>, @Res({ passthrough: true }) response: Response) {
|
||||
return this.changeEquipmentStatusService.findAll(query, response);
|
||||
}
|
||||
|
||||
@Roles('viewer', 'editor', 'admin')
|
||||
@Get(':id')
|
||||
findOne(@Param('id') id: string) {
|
||||
return this.changeEquipmentStatusService.findOne(id);
|
||||
}
|
||||
|
||||
@Roles('editor', 'admin')
|
||||
@Post()
|
||||
create(@Body() dto: CreateChangeEquipmentStatusDto) {
|
||||
return this.changeEquipmentStatusService.create(dto);
|
||||
}
|
||||
|
||||
@Roles('editor', 'admin')
|
||||
@Patch(':id')
|
||||
update(@Param('id') id: string, @Body() dto: UpdateChangeEquipmentStatusDto) {
|
||||
return this.changeEquipmentStatusService.update(id, dto);
|
||||
}
|
||||
|
||||
@Roles('admin')
|
||||
@Delete(':id')
|
||||
remove(@Param('id') id: string) {
|
||||
return this.changeEquipmentStatusService.remove(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ChangeEquipmentStatusController } from './change-equipment-status.controller';
|
||||
import { ChangeEquipmentStatusService } from './change-equipment-status.service';
|
||||
|
||||
@Module({
|
||||
controllers: [ChangeEquipmentStatusController],
|
||||
providers: [ChangeEquipmentStatusService],
|
||||
})
|
||||
export class ChangeEquipmentStatusModule {}
|
||||
@@ -0,0 +1,162 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { EquipmentStatus, Prisma } from '@prisma/client';
|
||||
import { Response } from 'express';
|
||||
import { setListHeaders } from '../../common/http';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import { CreateChangeEquipmentStatusDto } from './dto/create-change-equipment-status.dto';
|
||||
import { UpdateChangeEquipmentStatusDto } from './dto/update-change-equipment-status.dto';
|
||||
|
||||
@Injectable()
|
||||
export class ChangeEquipmentStatusService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async findAll(query: Record<string, unknown>, response: Response) {
|
||||
const start = Number(query._start ?? 0);
|
||||
const end = Number(query._end ?? start + 25);
|
||||
const take = Math.max(end - start, 0);
|
||||
const sortField = typeof query._sort === 'string' ? query._sort : 'date';
|
||||
const sortOrder = query._order === 'ASC' ? 'asc' : 'desc';
|
||||
const q = typeof query.q === 'string' ? query.q.trim() : '';
|
||||
const equipmentId = typeof query.equipmentId === 'string' ? query.equipmentId : undefined;
|
||||
const rawStatus = query.newStatus;
|
||||
const statuses = Array.isArray(rawStatus)
|
||||
? rawStatus.filter((value): value is EquipmentStatus => typeof value === 'string')
|
||||
: typeof rawStatus === 'string'
|
||||
? [rawStatus as EquipmentStatus]
|
||||
: [];
|
||||
|
||||
const where: Prisma.ChangeEquipmentStatusWhereInput = {};
|
||||
|
||||
if (q) {
|
||||
where.OR = [
|
||||
{ number: { contains: q, mode: 'insensitive' } },
|
||||
{ responsible: { contains: q, mode: 'insensitive' } },
|
||||
];
|
||||
}
|
||||
|
||||
if (equipmentId) {
|
||||
where.equipmentId = equipmentId;
|
||||
}
|
||||
|
||||
if (statuses.length === 1) {
|
||||
where.newStatus = statuses[0];
|
||||
} else if (statuses.length > 1) {
|
||||
where.newStatus = { in: statuses };
|
||||
}
|
||||
|
||||
const [total, items] = await this.prisma.$transaction([
|
||||
this.prisma.changeEquipmentStatus.count({ where }),
|
||||
this.prisma.changeEquipmentStatus.findMany({
|
||||
where,
|
||||
include: { equipment: true },
|
||||
skip: start,
|
||||
take,
|
||||
orderBy: { [sortField === 'id' ? 'id' : sortField]: sortOrder },
|
||||
}),
|
||||
]);
|
||||
|
||||
setListHeaders(response, total, start, end);
|
||||
return items.map((item) => this.toRecord(item));
|
||||
}
|
||||
|
||||
async findOne(id: string) {
|
||||
const item = await this.prisma.changeEquipmentStatus.findUnique({
|
||||
where: { id },
|
||||
include: { equipment: true },
|
||||
});
|
||||
|
||||
if (!item) {
|
||||
throw new NotFoundException(`ChangeEquipmentStatus ${id} not found`);
|
||||
}
|
||||
|
||||
return this.toRecord(item);
|
||||
}
|
||||
|
||||
async create(dto: CreateChangeEquipmentStatusDto) {
|
||||
const created = await this.prisma.$transaction(async (tx) => {
|
||||
const record = await tx.changeEquipmentStatus.create({
|
||||
data: {
|
||||
equipmentId: dto.equipmentId,
|
||||
newStatus: dto.newStatus,
|
||||
number: dto.number,
|
||||
date: new Date(dto.date),
|
||||
responsible: dto.responsible,
|
||||
},
|
||||
include: { equipment: true },
|
||||
});
|
||||
|
||||
if (dto.equipmentId) {
|
||||
await tx.equipment.update({
|
||||
where: { id: dto.equipmentId },
|
||||
data: { status: dto.newStatus },
|
||||
});
|
||||
}
|
||||
|
||||
return record;
|
||||
});
|
||||
|
||||
return this.toRecord(created);
|
||||
}
|
||||
|
||||
async update(id: string, dto: UpdateChangeEquipmentStatusDto) {
|
||||
await this.findOne(id);
|
||||
|
||||
const { id: _id, ...payload } = dto as UpdateChangeEquipmentStatusDto & { id?: string };
|
||||
const updated = await this.prisma.$transaction(async (tx) => {
|
||||
const record = await tx.changeEquipmentStatus.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...payload,
|
||||
date: dto.date ? new Date(dto.date) : undefined,
|
||||
},
|
||||
include: { equipment: true },
|
||||
});
|
||||
|
||||
if (record.equipmentId && dto.newStatus) {
|
||||
await tx.equipment.update({
|
||||
where: { id: record.equipmentId },
|
||||
data: { status: dto.newStatus },
|
||||
});
|
||||
}
|
||||
|
||||
return record;
|
||||
});
|
||||
|
||||
return this.toRecord(updated);
|
||||
}
|
||||
|
||||
async remove(id: string) {
|
||||
await this.findOne(id);
|
||||
const deleted = await this.prisma.changeEquipmentStatus.delete({
|
||||
where: { id },
|
||||
include: { equipment: true },
|
||||
});
|
||||
|
||||
return this.toRecord(deleted);
|
||||
}
|
||||
|
||||
private toRecord(item: {
|
||||
id: string;
|
||||
equipmentId: string | null;
|
||||
newStatus: EquipmentStatus;
|
||||
number: string | null;
|
||||
date: Date;
|
||||
responsible: string | null;
|
||||
equipment?: { id: string; name: string } | null;
|
||||
}) {
|
||||
return {
|
||||
id: item.id,
|
||||
equipmentId: item.equipmentId,
|
||||
newStatus: item.newStatus,
|
||||
number: item.number,
|
||||
date: item.date.toISOString(),
|
||||
responsible: item.responsible,
|
||||
equipment: item.equipment
|
||||
? {
|
||||
id: item.equipment.id,
|
||||
name: item.equipment.name,
|
||||
}
|
||||
: null,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { EquipmentStatus } from '@prisma/client';
|
||||
import { IsEnum, IsOptional, IsString, IsUUID } from 'class-validator';
|
||||
|
||||
export class CreateChangeEquipmentStatusDto {
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
equipmentId?: string;
|
||||
|
||||
@IsEnum(EquipmentStatus)
|
||||
newStatus!: EquipmentStatus;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
number?: string;
|
||||
|
||||
@IsString()
|
||||
date!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
responsible?: string;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { EquipmentStatus } from '@prisma/client';
|
||||
import { IsEnum, IsOptional, IsString, IsUUID } from 'class-validator';
|
||||
|
||||
export class UpdateChangeEquipmentStatusDto {
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
equipmentId?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsEnum(EquipmentStatus)
|
||||
newStatus?: EquipmentStatus;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
number?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
date?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
responsible?: string;
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { CreateChangeEquipmentStatusDto as CreateEquipmentStatusChangeDto } from '../../change-equipment-status/dto/create-change-equipment-status.dto';
|
||||
@@ -0,0 +1 @@
|
||||
export { UpdateChangeEquipmentStatusDto as UpdateEquipmentStatusChangeDto } from '../../change-equipment-status/dto/update-change-equipment-status.dto';
|
||||
@@ -0,0 +1,55 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
Param,
|
||||
Patch,
|
||||
Post,
|
||||
Query,
|
||||
Res,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import type { Response } from 'express';
|
||||
import { Roles } from '../../auth/decorators/roles.decorator';
|
||||
import { JwtAuthGuard } from '../../auth/guards/jwt-auth.guard';
|
||||
import { RolesGuard } from '../../auth/guards/roles.guard';
|
||||
import { ChangeEquipmentStatusService } from '../change-equipment-status/change-equipment-status.service';
|
||||
import { CreateChangeEquipmentStatusDto } from '../change-equipment-status/dto/create-change-equipment-status.dto';
|
||||
import { UpdateChangeEquipmentStatusDto } from '../change-equipment-status/dto/update-change-equipment-status.dto';
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Controller('status-changes')
|
||||
export class EquipmentStatusChangeController {
|
||||
constructor(private readonly equipmentStatusChangeService: ChangeEquipmentStatusService) {}
|
||||
|
||||
@Roles('viewer', 'editor', 'admin')
|
||||
@Get()
|
||||
findAll(@Query() query: Record<string, unknown>, @Res({ passthrough: true }) response: Response) {
|
||||
return this.equipmentStatusChangeService.findAll(query, response);
|
||||
}
|
||||
|
||||
@Roles('viewer', 'editor', 'admin')
|
||||
@Get(':id')
|
||||
findOne(@Param('id') id: string) {
|
||||
return this.equipmentStatusChangeService.findOne(id);
|
||||
}
|
||||
|
||||
@Roles('editor', 'admin')
|
||||
@Post()
|
||||
create(@Body() dto: CreateChangeEquipmentStatusDto) {
|
||||
return this.equipmentStatusChangeService.create(dto);
|
||||
}
|
||||
|
||||
@Roles('editor', 'admin')
|
||||
@Patch(':id')
|
||||
update(@Param('id') id: string, @Body() dto: UpdateChangeEquipmentStatusDto) {
|
||||
return this.equipmentStatusChangeService.update(id, dto);
|
||||
}
|
||||
|
||||
@Roles('admin')
|
||||
@Delete(':id')
|
||||
remove(@Param('id') id: string) {
|
||||
return this.equipmentStatusChangeService.remove(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AuthModule } from '../../auth/auth.module';
|
||||
import { ChangeEquipmentStatusService } from '../change-equipment-status/change-equipment-status.service';
|
||||
import { EquipmentStatusChangeController } from './equipment-status-change.controller';
|
||||
|
||||
@Module({
|
||||
imports: [AuthModule],
|
||||
controllers: [EquipmentStatusChangeController],
|
||||
providers: [ChangeEquipmentStatusService],
|
||||
})
|
||||
export class EquipmentStatusChangeModule {}
|
||||
@@ -0,0 +1 @@
|
||||
export { ChangeEquipmentStatusService as EquipmentStatusChangeService } from '../change-equipment-status/change-equipment-status.service';
|
||||
21
server/src/modules/equipment/dto/create-equipment.dto.ts
Normal file
21
server/src/modules/equipment/dto/create-equipment.dto.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import { EquipmentStatus } from '@prisma/client';
|
||||
import { IsEnum, IsOptional, IsString } from 'class-validator';
|
||||
|
||||
export class CreateEquipmentDto {
|
||||
@IsString()
|
||||
name!: string;
|
||||
|
||||
@IsString()
|
||||
serialNumber!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
dateOfInspection?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
commissionedAt?: string;
|
||||
|
||||
@IsEnum(EquipmentStatus)
|
||||
status!: EquipmentStatus;
|
||||
}
|
||||
24
server/src/modules/equipment/dto/update-equipment.dto.ts
Normal file
24
server/src/modules/equipment/dto/update-equipment.dto.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { EquipmentStatus } from '@prisma/client';
|
||||
import { IsEnum, IsOptional, IsString } from 'class-validator';
|
||||
|
||||
export class UpdateEquipmentDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
name?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
serialNumber?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
dateOfInspection?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
commissionedAt?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsEnum(EquipmentStatus)
|
||||
status?: EquipmentStatus;
|
||||
}
|
||||
55
server/src/modules/equipment/equipment.controller.ts
Normal file
55
server/src/modules/equipment/equipment.controller.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
Param,
|
||||
Patch,
|
||||
Post,
|
||||
Query,
|
||||
Res,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import type { Response } from 'express';
|
||||
import { Roles } from '../../auth/decorators/roles.decorator';
|
||||
import { JwtAuthGuard } from '../../auth/guards/jwt-auth.guard';
|
||||
import { RolesGuard } from '../../auth/guards/roles.guard';
|
||||
import { CreateEquipmentDto } from './dto/create-equipment.dto';
|
||||
import { UpdateEquipmentDto } from './dto/update-equipment.dto';
|
||||
import { EquipmentService } from './equipment.service';
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Controller('equipment')
|
||||
export class EquipmentController {
|
||||
constructor(private readonly equipmentService: EquipmentService) {}
|
||||
|
||||
@Roles('viewer', 'editor', 'admin')
|
||||
@Get()
|
||||
findAll(@Query() query: Record<string, unknown>, @Res({ passthrough: true }) response: Response) {
|
||||
return this.equipmentService.findAll(query, response);
|
||||
}
|
||||
|
||||
@Roles('viewer', 'editor', 'admin')
|
||||
@Get(':id')
|
||||
findOne(@Param('id') id: string) {
|
||||
return this.equipmentService.findOne(id);
|
||||
}
|
||||
|
||||
@Roles('editor', 'admin')
|
||||
@Post()
|
||||
create(@Body() dto: CreateEquipmentDto) {
|
||||
return this.equipmentService.create(dto);
|
||||
}
|
||||
|
||||
@Roles('editor', 'admin')
|
||||
@Patch(':id')
|
||||
update(@Param('id') id: string, @Body() dto: UpdateEquipmentDto) {
|
||||
return this.equipmentService.update(id, dto);
|
||||
}
|
||||
|
||||
@Roles('admin')
|
||||
@Delete(':id')
|
||||
remove(@Param('id') id: string) {
|
||||
return this.equipmentService.remove(id);
|
||||
}
|
||||
}
|
||||
11
server/src/modules/equipment/equipment.module.ts
Normal file
11
server/src/modules/equipment/equipment.module.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AuthModule } from '../../auth/auth.module';
|
||||
import { EquipmentController } from './equipment.controller';
|
||||
import { EquipmentService } from './equipment.service';
|
||||
|
||||
@Module({
|
||||
imports: [AuthModule],
|
||||
controllers: [EquipmentController],
|
||||
providers: [EquipmentService],
|
||||
})
|
||||
export class EquipmentModule {}
|
||||
119
server/src/modules/equipment/equipment.service.ts
Normal file
119
server/src/modules/equipment/equipment.service.ts
Normal file
@@ -0,0 +1,119 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { EquipmentStatus, Prisma } from '@prisma/client';
|
||||
import { Response } from 'express';
|
||||
import { setListHeaders } from '../../common/http';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import { CreateEquipmentDto } from './dto/create-equipment.dto';
|
||||
import { UpdateEquipmentDto } from './dto/update-equipment.dto';
|
||||
|
||||
@Injectable()
|
||||
export class EquipmentService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async findAll(query: Record<string, unknown>, response: Response) {
|
||||
const start = Number(query._start ?? 0);
|
||||
const end = Number(query._end ?? start + 25);
|
||||
const take = Math.max(end - start, 0);
|
||||
const sortField = typeof query._sort === 'string' ? query._sort : 'id';
|
||||
const sortOrder = query._order === 'DESC' ? 'desc' : 'asc';
|
||||
const q = typeof query.q === 'string' ? query.q.trim() : '';
|
||||
const rawStatus = query.status;
|
||||
const statuses = Array.isArray(rawStatus)
|
||||
? rawStatus.filter((value): value is EquipmentStatus => typeof value === 'string')
|
||||
: typeof rawStatus === 'string'
|
||||
? [rawStatus as EquipmentStatus]
|
||||
: [];
|
||||
|
||||
const where: Prisma.EquipmentWhereInput = {};
|
||||
|
||||
if (q) {
|
||||
where.OR = [
|
||||
{ name: { contains: q, mode: 'insensitive' } },
|
||||
{ serialNumber: { contains: q, mode: 'insensitive' } },
|
||||
];
|
||||
}
|
||||
|
||||
if (statuses.length === 1) {
|
||||
where.status = statuses[0];
|
||||
} else if (statuses.length > 1) {
|
||||
where.status = { in: statuses };
|
||||
}
|
||||
|
||||
const orderByField = sortField === 'id' ? 'id' : sortField;
|
||||
const [total, items] = await this.prisma.$transaction([
|
||||
this.prisma.equipment.count({ where }),
|
||||
this.prisma.equipment.findMany({
|
||||
where,
|
||||
skip: start,
|
||||
take,
|
||||
orderBy: { [orderByField]: sortOrder },
|
||||
}),
|
||||
]);
|
||||
|
||||
setListHeaders(response, total, start, end);
|
||||
return items.map((item) => this.toRecord(item));
|
||||
}
|
||||
|
||||
async findOne(id: string) {
|
||||
const item = await this.prisma.equipment.findUnique({ where: { id } });
|
||||
if (!item) {
|
||||
throw new NotFoundException(`Equipment ${id} not found`);
|
||||
}
|
||||
|
||||
return this.toRecord(item);
|
||||
}
|
||||
|
||||
async create(dto: CreateEquipmentDto) {
|
||||
const created = await this.prisma.equipment.create({
|
||||
data: {
|
||||
name: dto.name,
|
||||
serialNumber: dto.serialNumber,
|
||||
dateOfInspection: dto.dateOfInspection ? new Date(dto.dateOfInspection) : undefined,
|
||||
commissionedAt: dto.commissionedAt ? new Date(dto.commissionedAt) : undefined,
|
||||
status: dto.status,
|
||||
},
|
||||
});
|
||||
|
||||
return this.toRecord(created);
|
||||
}
|
||||
|
||||
async update(id: string, dto: UpdateEquipmentDto) {
|
||||
await this.findOne(id);
|
||||
|
||||
const { id: _id, ...payload } = dto as UpdateEquipmentDto & { id?: string };
|
||||
const updated = await this.prisma.equipment.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...payload,
|
||||
dateOfInspection: dto.dateOfInspection ? new Date(dto.dateOfInspection) : undefined,
|
||||
commissionedAt: dto.commissionedAt ? new Date(dto.commissionedAt) : undefined,
|
||||
},
|
||||
});
|
||||
|
||||
return this.toRecord(updated);
|
||||
}
|
||||
|
||||
async remove(id: string) {
|
||||
await this.findOne(id);
|
||||
const deleted = await this.prisma.equipment.delete({ where: { id } });
|
||||
return this.toRecord(deleted);
|
||||
}
|
||||
|
||||
private toRecord(item: {
|
||||
id: string;
|
||||
name: string;
|
||||
serialNumber: string;
|
||||
dateOfInspection: Date | null;
|
||||
commissionedAt: Date | null;
|
||||
status: EquipmentStatus;
|
||||
}) {
|
||||
return {
|
||||
id: item.id,
|
||||
name: item.name,
|
||||
serialNumber: item.serialNumber,
|
||||
dateOfInspection: item.dateOfInspection?.toISOString() ?? null,
|
||||
commissionedAt: item.commissionedAt?.toISOString() ?? null,
|
||||
status: item.status,
|
||||
};
|
||||
}
|
||||
}
|
||||
9
server/src/prisma/prisma.module.ts
Normal file
9
server/src/prisma/prisma.module.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { PrismaService } from './prisma.service';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [PrismaService],
|
||||
exports: [PrismaService],
|
||||
})
|
||||
export class PrismaModule {}
|
||||
24
server/src/prisma/prisma.service.ts
Normal file
24
server/src/prisma/prisma.service.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { Injectable, OnModuleInit } from '@nestjs/common';
|
||||
import { PrismaPg } from '@prisma/adapter-pg';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { Pool } from 'pg';
|
||||
|
||||
@Injectable()
|
||||
export class PrismaService extends PrismaClient implements OnModuleInit {
|
||||
constructor() {
|
||||
const connectionString = process.env.DATABASE_URL;
|
||||
|
||||
if (!connectionString) {
|
||||
throw new Error('DATABASE_URL is not set');
|
||||
}
|
||||
|
||||
const pool = new Pool({ connectionString });
|
||||
const adapter = new PrismaPg(pool);
|
||||
|
||||
super({ adapter });
|
||||
}
|
||||
|
||||
async onModuleInit() {
|
||||
await this.$connect();
|
||||
}
|
||||
}
|
||||
29
server/test/app.e2e-spec.ts
Normal file
29
server/test/app.e2e-spec.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import request from 'supertest';
|
||||
import { App } from 'supertest/types';
|
||||
import { AppModule } from './../src/app.module';
|
||||
|
||||
describe('AppController (e2e)', () => {
|
||||
let app: INestApplication<App>;
|
||||
|
||||
beforeEach(async () => {
|
||||
const moduleFixture: TestingModule = await Test.createTestingModule({
|
||||
imports: [AppModule],
|
||||
}).compile();
|
||||
|
||||
app = moduleFixture.createNestApplication();
|
||||
await app.init();
|
||||
});
|
||||
|
||||
it('/ (GET)', () => {
|
||||
return request(app.getHttpServer())
|
||||
.get('/')
|
||||
.expect(200)
|
||||
.expect('Hello World!');
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await app.close();
|
||||
});
|
||||
});
|
||||
9
server/test/jest-e2e.json
Normal file
9
server/test/jest-e2e.json
Normal file
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"moduleFileExtensions": ["js", "json", "ts"],
|
||||
"rootDir": ".",
|
||||
"testEnvironment": "node",
|
||||
"testRegex": ".e2e-spec.ts$",
|
||||
"transform": {
|
||||
"^.+\\.(t|j)s$": "ts-jest"
|
||||
}
|
||||
}
|
||||
4
server/tsconfig.build.json
Normal file
4
server/tsconfig.build.json
Normal file
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
|
||||
}
|
||||
25
server/tsconfig.json
Normal file
25
server/tsconfig.json
Normal file
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "nodenext",
|
||||
"moduleResolution": "nodenext",
|
||||
"resolvePackageJsonExports": true,
|
||||
"esModuleInterop": true,
|
||||
"isolatedModules": true,
|
||||
"declaration": true,
|
||||
"removeComments": true,
|
||||
"emitDecoratorMetadata": true,
|
||||
"experimentalDecorators": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"target": "ES2023",
|
||||
"sourceMap": true,
|
||||
"outDir": "./dist",
|
||||
"baseUrl": "./",
|
||||
"incremental": true,
|
||||
"skipLibCheck": true,
|
||||
"strictNullChecks": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"noImplicitAny": false,
|
||||
"strictBindCallApply": false,
|
||||
"noFallthroughCasesInSwitch": false
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user