From df70c9ef55bd2dc38d136607a949468fbe7ac07e Mon Sep 17 00:00:00 2001 From: substantialcattle5 Date: Tue, 24 Sep 2024 14:26:42 +0530 Subject: [PATCH 1/2] feat: language filtering --- .../20240924073131_clang/migration.sql | 2 + prisma/schema.prisma | 2 + src/blog/blog.controller.ts | 144 +++++---- src/blog/blog.service.ts | 285 ++++++++++-------- src/blog/dto/create-blog.dto.ts | 26 +- 5 files changed, 272 insertions(+), 187 deletions(-) create mode 100644 prisma/migrations/20240924073131_clang/migration.sql diff --git a/prisma/migrations/20240924073131_clang/migration.sql b/prisma/migrations/20240924073131_clang/migration.sql new file mode 100644 index 0000000..c177476 --- /dev/null +++ b/prisma/migrations/20240924073131_clang/migration.sql @@ -0,0 +1,2 @@ +-- AlterTable +ALTER TABLE "Blog" ADD COLUMN "language" TEXT NOT NULL DEFAULT 'english'; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 4fb89f6..b69faab 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -61,6 +61,8 @@ model Blog { userId Int? region String @default("general") + language String @default("english") + @@index([userId]) @@index([title]) } diff --git a/src/blog/blog.controller.ts b/src/blog/blog.controller.ts index ce7053b..0a8fa28 100644 --- a/src/blog/blog.controller.ts +++ b/src/blog/blog.controller.ts @@ -1,68 +1,100 @@ -import { Controller, Get, Post, Put, Delete, Param, Body, Query, Res, UseGuards } from "@nestjs/common"; -import { ApiTags, ApiResponse, ApiOperation, ApiBearerAuth } from "@nestjs/swagger"; -import { BlogService } from "./blog.service"; -import { CreateBlogDto } from "./dto/create-blog.dto"; -import { UpdateBlogDto } from "./dto/update-blog.dto"; -import { JwtGuard } from "../auth/guards/auth.guard"; - +import { + Controller, + Get, + Post, + Put, + Delete, + Param, + Body, + Query, + Res, +} from '@nestjs/common'; +import { ApiTags, ApiResponse, ApiOperation } from '@nestjs/swagger'; +import { BlogService } from './blog.service'; +import { CreateBlogDto } from './dto/create-blog.dto'; +import { UpdateBlogDto } from './dto/update-blog.dto'; @ApiTags('blog') @Controller('blog') export class BlogController { - constructor(private readonly blogService: BlogService) { } + constructor(private readonly blogService: BlogService) {} - @Post() - @ApiOperation({ summary: 'Create a new blog' }) - @ApiResponse({ status: 201, description: 'The blog has been successfully created.' }) - @ApiResponse({ status: 404, description: 'Author not found.' }) - async create(@Body() createBlogDto: CreateBlogDto, @Res() res) { - const result = await this.blogService.create(createBlogDto); - return res.status(result.status).json(result); - } + @Post() + @ApiOperation({ summary: 'Create a new blog' }) + @ApiResponse({ + status: 201, + description: 'The blog has been successfully created.', + }) + @ApiResponse({ status: 404, description: 'Author not found.' }) + async create(@Body() createBlogDto: CreateBlogDto, @Res() res) { + const result = await this.blogService.create(createBlogDto); + return res.status(result.status).json(result); + } + @Get() + @ApiOperation({ summary: 'Find all blogs by region' }) + @ApiResponse({ status: 200, description: 'Blogs retrieved successfully.' }) + @ApiResponse({ + status: 404, + description: 'No blogs found for the specified region.', + }) + async findAllByRegion(@Query('region') region: string, @Res() res) { + const result = await this.blogService.findAll(region); + return res.status(result.status).json(result); + } - @Get() - @ApiOperation({ summary: 'Find all blogs by region' }) - @ApiResponse({ status: 200, description: 'Blogs retrieved successfully.' }) - @ApiResponse({ status: 404, description: 'No blogs found for the specified region.' }) - async findAllByRegion(@Query('region') region: string, @Res() res) { - const result = await this.blogService.findAll(region); - return res.status(result.status).json(result); - } + @Get() + @ApiOperation({ summary: 'Find all blogs by region' }) + @ApiResponse({ status: 200, description: 'Blogs retrieved successfully.' }) + @ApiResponse({ + status: 404, + description: 'No blogs found for the specified region.', + }) + async findAllByLanguage(@Query('language') lang: string, @Res() res) { + const result = await this.blogService.findAll(lang); + return res.status(result.status).json(result); + } - @Get("/all") - @ApiOperation({ summary: 'Find all blogs' }) - @ApiResponse({ status: 200, description: 'Blogs retrieved successfully.' }) - @ApiResponse({ status: 404, description: 'No blogs found for the specified region.' }) - async findAll(@Res() res) { - const result = await this.blogService.findAll(""); - return res.status(result.status).json(result); - } + @Get('/all') + @ApiOperation({ summary: 'Find all blogs' }) + @ApiResponse({ status: 200, description: 'Blogs retrieved successfully.' }) + @ApiResponse({ + status: 404, + description: 'No blogs found for the specified region.', + }) + async findAll(@Res() res) { + const result = await this.blogService.findAll(''); + return res.status(result.status).json(result); + } - @Get(':id') - @ApiOperation({ summary: 'Find a blog by ID' }) - @ApiResponse({ status: 200, description: 'Blog retrieved successfully.' }) - @ApiResponse({ status: 404, description: 'Blog not found.' }) - async findById(@Param('id') id: number, @Res() res) { - const result = await this.blogService.findById(+id); - return res.status(result.status).json(result); - } + @Get(':id') + @ApiOperation({ summary: 'Find a blog by ID' }) + @ApiResponse({ status: 200, description: 'Blog retrieved successfully.' }) + @ApiResponse({ status: 404, description: 'Blog not found.' }) + async findById(@Param('id') id: number, @Res() res) { + const result = await this.blogService.findById(+id); + return res.status(result.status).json(result); + } - @Put(':id') - @ApiOperation({ summary: 'Update a blog by ID' }) - @ApiResponse({ status: 200, description: 'Blog updated successfully.' }) - @ApiResponse({ status: 404, description: 'Blog not found.' }) - async update(@Param('id') id: number, @Body() updateBlogDto: UpdateBlogDto, @Res() res) { - const result = await this.blogService.update(+id, updateBlogDto); - return res.status(result.status).json(result); - } + @Put(':id') + @ApiOperation({ summary: 'Update a blog by ID' }) + @ApiResponse({ status: 200, description: 'Blog updated successfully.' }) + @ApiResponse({ status: 404, description: 'Blog not found.' }) + async update( + @Param('id') id: number, + @Body() updateBlogDto: UpdateBlogDto, + @Res() res, + ) { + const result = await this.blogService.update(+id, updateBlogDto); + return res.status(result.status).json(result); + } - @Delete(':id') - @ApiOperation({ summary: 'Delete a blog by ID' }) - @ApiResponse({ status: 200, description: 'Blog deleted successfully.' }) - @ApiResponse({ status: 404, description: 'Blog not found.' }) - async delete(@Param('id') id: number, @Res() res) { - const result = await this.blogService.delete(+id); - return res.status(result.status).json(result); - } + @Delete(':id') + @ApiOperation({ summary: 'Delete a blog by ID' }) + @ApiResponse({ status: 200, description: 'Blog deleted successfully.' }) + @ApiResponse({ status: 404, description: 'Blog not found.' }) + async delete(@Param('id') id: number, @Res() res) { + const result = await this.blogService.delete(+id); + return res.status(result.status).json(result); + } } diff --git a/src/blog/blog.service.ts b/src/blog/blog.service.ts index 4ccd38f..4268656 100644 --- a/src/blog/blog.service.ts +++ b/src/blog/blog.service.ts @@ -1,134 +1,181 @@ -import { Injectable } from "@nestjs/common"; -import { PrismaService } from "src/prisma/prisma.service"; -import { CreateBlogDto } from "./dto/create-blog.dto"; +import { Injectable } from '@nestjs/common'; +import { PrismaService } from 'src/prisma/prisma.service'; +import { CreateBlogDto } from './dto/create-blog.dto'; import { ApiResponse, ApiTags } from '@nestjs/swagger'; -import { UpdateBlogDto } from "./dto/update-blog.dto"; +import { UpdateBlogDto } from './dto/update-blog.dto'; @Injectable() @ApiTags('blogs') export class BlogService { - constructor(private readonly prismaService: PrismaService) {} - - /** - * Create a new blog entry - * @param createBlogDto - Data transfer object containing blog details - * @returns Created blog entry or error response - */ - @ApiResponse({ status: 201, description: 'The blog has been successfully created.' }) - @ApiResponse({ status: 404, description: 'Author not found.' }) - async create(createBlogDto: CreateBlogDto) { - const { title, region, pic, content, authorId } = createBlogDto; - - // Find the author's name using their ID - const author = await this.prismaService.user.findUnique({ - where: { id: authorId }, - select: { name: true } - }); - - // Check if the author exists - if (!author) { - return { status: 404, message: 'Author not found' }; - } - - // Create a new blog entry - const blog = await this.prismaService.blog.create({ - data: { title, region, picture:pic, content, authorName: author.name } - }); - - return { status: 201, data: blog }; + constructor(private readonly prismaService: PrismaService) {} + + /** + * Create a new blog entry + * @param createBlogDto - Data transfer object containing blog details + * @returns Created blog entry or error response + */ + @ApiResponse({ + status: 201, + description: 'The blog has been successfully created.', + }) + @ApiResponse({ status: 404, description: 'Author not found.' }) + async create(createBlogDto: CreateBlogDto) { + const { title, region, pic, content, authorId, language } = createBlogDto; + + // Find the author's name using their ID + const author = await this.prismaService.user.findUnique({ + where: { id: authorId }, + select: { name: true }, + }); + + // Check if the author exists + if (!author) { + return { status: 404, message: 'Author not found' }; } - /** - * Find all blogs by region - * @param region - Region to filter blogs - * @returns List of blogs or error response - */ - @ApiResponse({ status: 200, description: 'Blogs retrieved successfully.' }) - @ApiResponse({ status: 404, description: 'No blogs found for the specified region.' }) - async findAll(region: string) { - if (region === "") { - return { - status : 200 , - data : await this.prismaService.blog.findMany() - } - } - const blogs = await this.prismaService.blog.findMany({ - where: { region } - }); - - if (!blogs.length) { - return { status: 404, message: 'No blogs found for the specified region' }; - } - - return { status: 200, data: blogs }; + // Create a new blog entry + const blog = await this.prismaService.blog.create({ + data: { + title, + region, + picture: pic, + content, + authorName: author.name, + language, + }, + }); + + return { status: 201, data: blog }; + } + + /** + * Find all blogs by region + * @param region - Region to filter blogs + * @returns List of blogs or error response + */ + @ApiResponse({ status: 200, description: 'Blogs retrieved successfully.' }) + @ApiResponse({ + status: 404, + description: 'No blogs found for the specified region.', + }) + async findAll(region: string) { + if (region === '') { + return { + status: 200, + data: await this.prismaService.blog.findMany(), + }; + } + const blogs = await this.prismaService.blog.findMany({ + where: { region }, + }); + + if (!blogs.length) { + return { + status: 404, + message: 'No blogs found for the specified region', + }; + } + + return { status: 200, data: blogs }; + } + + /** + * Find all blogs by language + * @param language - Language to filter blogs + * @returns List of blogs or error response + */ + @ApiResponse({ status: 200, description: 'Blogs retrieved successfully.' }) + @ApiResponse({ + status: 404, + description: 'No blogs found for the specified region.', + }) + async findAllByLang(language: string) { + if (language === '') { + return { + status: 200, + data: await this.prismaService.blog.findMany(), + }; + } + const blogs = await this.prismaService.blog.findMany({ + where: { language }, + }); + + if (!blogs.length) { + return { + status: 404, + message: 'No blogs found for the specified region', + }; } - /** - * Find a blog by ID - * @param id - ID of the blog to retrieve - * @returns Blog entry or error response - */ - @ApiResponse({ status: 200, description: 'Blog retrieved successfully.' }) - @ApiResponse({ status: 404, description: 'Blog not found.' }) - async findById(id: number) { - const blog = await this.prismaService.blog.findUnique({ - where: { id } - }); - - if (!blog) { - return { status: 404, message: 'Blog not found' }; - } - - return { status: 200, data: blog }; + return { status: 200, data: blogs }; + } + + /** + * Find a blog by ID + * @param id - ID of the blog to retrieve + * @returns Blog entry or error response + */ + @ApiResponse({ status: 200, description: 'Blog retrieved successfully.' }) + @ApiResponse({ status: 404, description: 'Blog not found.' }) + async findById(id: number) { + const blog = await this.prismaService.blog.findUnique({ + where: { id }, + }); + + if (!blog) { + return { status: 404, message: 'Blog not found' }; } - /** - * Update a blog's details - * @param id - ID of the blog to update - * @param updateBlogDto - Data transfer object containing updated blog details - * @returns Updated blog entry or error response - */ - @ApiResponse({ status: 200, description: 'Blog updated successfully.' }) - @ApiResponse({ status: 404, description: 'Blog not found.' }) - async update(id: number, updateBlogDto: UpdateBlogDto) { - const { title, region, pic, content } = updateBlogDto; - - const existingBlog = await this.prismaService.blog.findUnique({ - where: { id } - }); - - if (!existingBlog) { - return { status: 404, message: 'Blog not found' }; - } - - const updatedBlog = await this.prismaService.blog.update({ - where: { id }, - data: { title, region, picture:pic, content } - }); - - return { status: 200, data: updatedBlog }; + return { status: 200, data: blog }; + } + + /** + * Update a blog's details + * @param id - ID of the blog to update + * @param updateBlogDto - Data transfer object containing updated blog details + * @returns Updated blog entry or error response + */ + @ApiResponse({ status: 200, description: 'Blog updated successfully.' }) + @ApiResponse({ status: 404, description: 'Blog not found.' }) + async update(id: number, updateBlogDto: UpdateBlogDto) { + const { title, region, pic, content } = updateBlogDto; + + const existingBlog = await this.prismaService.blog.findUnique({ + where: { id }, + }); + + if (!existingBlog) { + return { status: 404, message: 'Blog not found' }; } - /** - * Delete a blog by ID - * @param id - ID of the blog to delete - * @returns Success message or error response - */ - @ApiResponse({ status: 200, description: 'Blog deleted successfully.' }) - @ApiResponse({ status: 404, description: 'Blog not found.' }) - async delete(id: number) { - const existingBlog = await this.prismaService.blog.findUnique({ - where: { id } - }); - - if (!existingBlog) { - return { status: 404, message: 'Blog not found' }; - } - - await this.prismaService.blog.delete({ - where: { id } - }); - - return { status: 200, message: 'Blog deleted successfully' }; + const updatedBlog = await this.prismaService.blog.update({ + where: { id }, + data: { title, region, picture: pic, content }, + }); + + return { status: 200, data: updatedBlog }; + } + + /** + * Delete a blog by ID + * @param id - ID of the blog to delete + * @returns Success message or error response + */ + @ApiResponse({ status: 200, description: 'Blog deleted successfully.' }) + @ApiResponse({ status: 404, description: 'Blog not found.' }) + async delete(id: number) { + const existingBlog = await this.prismaService.blog.findUnique({ + where: { id }, + }); + + if (!existingBlog) { + return { status: 404, message: 'Blog not found' }; } + + await this.prismaService.blog.delete({ + where: { id }, + }); + + return { status: 200, message: 'Blog deleted successfully' }; + } } diff --git a/src/blog/dto/create-blog.dto.ts b/src/blog/dto/create-blog.dto.ts index 56ded25..8d088cc 100644 --- a/src/blog/dto/create-blog.dto.ts +++ b/src/blog/dto/create-blog.dto.ts @@ -1,19 +1,21 @@ -import { IsInt, IsString } from "class-validator"; +import { IsInt, IsString } from 'class-validator'; export class CreateBlogDto { - @IsString() - title: string; + @IsString() + title: string; - @IsString() - pic: string; + @IsString() + pic: string; - @IsString() - content: string; + @IsString() + content: string; - @IsString() - region: string; + @IsString() + region: string; - @IsInt() - authorId: number; + @IsInt() + authorId: number; -} \ No newline at end of file + @IsString() + language: string; +} From cd912c00bb04181ee4c594c81b91346df3c6284d Mon Sep 17 00:00:00 2001 From: substantialcattle5 Date: Sat, 5 Oct 2024 10:37:19 +0530 Subject: [PATCH 2/2] fix: id update --- .../20240924094053_clang2/migration.sql | 170 ++++++++++++++++++ prisma/schema.prisma | 62 ++++--- prisma/seed.ts | 108 +---------- src/auth/interfaces/otpCache.interface.ts | 2 +- src/auth/interfaces/user.interface.ts | 2 +- src/blog/blog.controller.ts | 12 +- src/blog/blog.service.ts | 6 +- src/blog/dto/create-blog.dto.ts | 2 +- src/main.ts | 11 +- src/quiz/quiz.controller.ts | 2 +- src/quiz/quiz.service.ts | 89 +++++---- src/survey/survey.controller.ts | 8 +- src/survey/survey.service.ts | 148 +++++++-------- src/tasks/tasks.controller.ts | 8 +- src/tasks/tasks.service.ts | 157 ++++++++-------- src/user/user.service.ts | 6 +- 16 files changed, 439 insertions(+), 354 deletions(-) create mode 100644 prisma/migrations/20240924094053_clang2/migration.sql diff --git a/prisma/migrations/20240924094053_clang2/migration.sql b/prisma/migrations/20240924094053_clang2/migration.sql new file mode 100644 index 0000000..85880b1 --- /dev/null +++ b/prisma/migrations/20240924094053_clang2/migration.sql @@ -0,0 +1,170 @@ +/* + Warnings: + + - The primary key for the `Answer` table will be changed. If it partially fails, the table could be left without primary key constraint. + - The `userId` column on the `Answer` table would be dropped and recreated. This will lead to data loss if there is data in the column. + - The primary key for the `Blog` table will be changed. If it partially fails, the table could be left without primary key constraint. + - The `userId` column on the `Blog` table would be dropped and recreated. This will lead to data loss if there is data in the column. + - The primary key for the `MedicalQuery` table will be changed. If it partially fails, the table could be left without primary key constraint. + - The `userId` column on the `MedicalQuery` table would be dropped and recreated. This will lead to data loss if there is data in the column. + - The `surveyId` column on the `Question` table would be dropped and recreated. This will lead to data loss if there is data in the column. + - The `userId` column on the `Quiz` table would be dropped and recreated. This will lead to data loss if there is data in the column. + - The primary key for the `SleepData` table will be changed. If it partially fails, the table could be left without primary key constraint. + - The `userId` column on the `SleepData` table would be dropped and recreated. This will lead to data loss if there is data in the column. + - The primary key for the `Survey` table will be changed. If it partially fails, the table could be left without primary key constraint. + - The `userId` column on the `Survey` table would be dropped and recreated. This will lead to data loss if there is data in the column. + - The primary key for the `Task` table will be changed. If it partially fails, the table could be left without primary key constraint. + - The `userId` column on the `Task` table would be dropped and recreated. This will lead to data loss if there is data in the column. + - The `issuedById` column on the `Task` table would be dropped and recreated. This will lead to data loss if there is data in the column. + - The primary key for the `User` table will be changed. If it partially fails, the table could be left without primary key constraint. + - Changed the type of `id` on the `Answer` table. No cast exists, the column would be dropped and recreated, which cannot be done if there is data, since the column is required. + - Changed the type of `id` on the `Blog` table. No cast exists, the column would be dropped and recreated, which cannot be done if there is data, since the column is required. + - Changed the type of `id` on the `MedicalQuery` table. No cast exists, the column would be dropped and recreated, which cannot be done if there is data, since the column is required. + - Changed the type of `id` on the `SleepData` table. No cast exists, the column would be dropped and recreated, which cannot be done if there is data, since the column is required. + - Changed the type of `id` on the `Survey` table. No cast exists, the column would be dropped and recreated, which cannot be done if there is data, since the column is required. + - Changed the type of `id` on the `Task` table. No cast exists, the column would be dropped and recreated, which cannot be done if there is data, since the column is required. + - Changed the type of `id` on the `User` table. No cast exists, the column would be dropped and recreated, which cannot be done if there is data, since the column is required. + +*/ +-- DropForeignKey +ALTER TABLE "Answer" DROP CONSTRAINT "Answer_userId_fkey"; + +-- DropForeignKey +ALTER TABLE "Blog" DROP CONSTRAINT "Blog_userId_fkey"; + +-- DropForeignKey +ALTER TABLE "MedicalQuery" DROP CONSTRAINT "MedicalQuery_userId_fkey"; + +-- DropForeignKey +ALTER TABLE "Question" DROP CONSTRAINT "Question_surveyId_fkey"; + +-- DropForeignKey +ALTER TABLE "Quiz" DROP CONSTRAINT "Quiz_userId_fkey"; + +-- DropForeignKey +ALTER TABLE "SleepData" DROP CONSTRAINT "SleepData_userId_fkey"; + +-- DropForeignKey +ALTER TABLE "Survey" DROP CONSTRAINT "Survey_userId_fkey"; + +-- DropForeignKey +ALTER TABLE "Task" DROP CONSTRAINT "Task_issuedById_fkey"; + +-- DropForeignKey +ALTER TABLE "Task" DROP CONSTRAINT "Task_userId_fkey"; + +-- AlterTable +ALTER TABLE "Answer" DROP CONSTRAINT "Answer_pkey", +DROP COLUMN "id", +ADD COLUMN "id" UUID NOT NULL, +DROP COLUMN "userId", +ADD COLUMN "userId" UUID, +ADD CONSTRAINT "Answer_pkey" PRIMARY KEY ("id"); + +-- AlterTable +ALTER TABLE "Blog" DROP CONSTRAINT "Blog_pkey", +DROP COLUMN "id", +ADD COLUMN "id" UUID NOT NULL, +DROP COLUMN "userId", +ADD COLUMN "userId" UUID, +ADD CONSTRAINT "Blog_pkey" PRIMARY KEY ("id"); + +-- AlterTable +ALTER TABLE "MedicalQuery" DROP CONSTRAINT "MedicalQuery_pkey", +DROP COLUMN "id", +ADD COLUMN "id" UUID NOT NULL, +DROP COLUMN "userId", +ADD COLUMN "userId" UUID, +ADD CONSTRAINT "MedicalQuery_pkey" PRIMARY KEY ("id"); + +-- AlterTable +ALTER TABLE "Question" DROP COLUMN "surveyId", +ADD COLUMN "surveyId" UUID; + +-- AlterTable +ALTER TABLE "Quiz" DROP COLUMN "userId", +ADD COLUMN "userId" UUID; + +-- AlterTable +ALTER TABLE "SleepData" DROP CONSTRAINT "SleepData_pkey", +DROP COLUMN "id", +ADD COLUMN "id" UUID NOT NULL, +DROP COLUMN "userId", +ADD COLUMN "userId" UUID, +ADD CONSTRAINT "SleepData_pkey" PRIMARY KEY ("id"); + +-- AlterTable +ALTER TABLE "Survey" DROP CONSTRAINT "Survey_pkey", +DROP COLUMN "id", +ADD COLUMN "id" UUID NOT NULL, +DROP COLUMN "userId", +ADD COLUMN "userId" UUID, +ADD CONSTRAINT "Survey_pkey" PRIMARY KEY ("id"); + +-- AlterTable +ALTER TABLE "Task" DROP CONSTRAINT "Task_pkey", +DROP COLUMN "id", +ADD COLUMN "id" UUID NOT NULL, +DROP COLUMN "userId", +ADD COLUMN "userId" UUID, +DROP COLUMN "issuedById", +ADD COLUMN "issuedById" UUID, +ADD CONSTRAINT "Task_pkey" PRIMARY KEY ("id"); + +-- AlterTable +ALTER TABLE "User" DROP CONSTRAINT "User_pkey", +ADD COLUMN "language" TEXT NOT NULL DEFAULT 'english', +DROP COLUMN "id", +ADD COLUMN "id" UUID NOT NULL, +ADD CONSTRAINT "User_pkey" PRIMARY KEY ("id"); + +-- CreateIndex +CREATE INDEX "Answer_userId_idx" ON "Answer"("userId"); + +-- CreateIndex +CREATE INDEX "Blog_userId_idx" ON "Blog"("userId"); + +-- CreateIndex +CREATE INDEX "MedicalQuery_userId_idx" ON "MedicalQuery"("userId"); + +-- CreateIndex +CREATE INDEX "Question_surveyId_idx" ON "Question"("surveyId"); + +-- CreateIndex +CREATE INDEX "SleepData_userId_idx" ON "SleepData"("userId"); + +-- CreateIndex +CREATE INDEX "Survey_userId_idx" ON "Survey"("userId"); + +-- CreateIndex +CREATE INDEX "Task_userId_idx" ON "Task"("userId"); + +-- CreateIndex +CREATE INDEX "Task_issuedById_idx" ON "Task"("issuedById"); + +-- AddForeignKey +ALTER TABLE "Blog" ADD CONSTRAINT "Blog_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "Task" ADD CONSTRAINT "Task_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "Task" ADD CONSTRAINT "Task_issuedById_fkey" FOREIGN KEY ("issuedById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "SleepData" ADD CONSTRAINT "SleepData_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "Survey" ADD CONSTRAINT "Survey_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "Quiz" ADD CONSTRAINT "Quiz_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "Question" ADD CONSTRAINT "Question_surveyId_fkey" FOREIGN KEY ("surveyId") REFERENCES "Survey"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "Answer" ADD CONSTRAINT "Answer_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "MedicalQuery" ADD CONSTRAINT "MedicalQuery_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index b69faab..e6c540d 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -9,18 +9,21 @@ datasource db { // User model represents the application users model User { - id Int @id @default(autoincrement()) - name String @db.VarChar(100) - age Int - birthday DateTime - location String @db.VarChar(255) - gender Gender - email String @unique @db.VarChar(255) - contact String @db.VarChar(20) - picture String @db.VarChar(255) - position Position - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt + id String @id @default(uuid()) @db.Uuid + name String @db.VarChar(100) + age Int + birthday DateTime + language String @default("english") + location String @db.VarChar(255) + gender Gender + email String @unique @db.VarChar(255) + contact String @db.VarChar(20) + picture String @db.VarChar(255) + position Position + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + // Relations blogs Blog[] tasks Task[] @relation("UserTasks") issuedTasks Task[] @relation("IssuedTasks") @@ -50,7 +53,7 @@ enum Position { // Blog model represents blog posts authored by users model Blog { - id Int @id @default(autoincrement()) + id String @id @default(uuid()) @db.Uuid title String @db.VarChar(255) picture String @db.VarChar(255) content String @db.Text @@ -58,7 +61,7 @@ model Blog { updatedAt DateTime @updatedAt authorName String @db.VarChar(100) user User? @relation(fields: [userId], references: [id], onDelete: Cascade) - userId Int? + userId String? @db.Uuid region String @default("general") language String @default("english") @@ -69,16 +72,16 @@ model Blog { // Task model represents tasks associated with users model Task { - id Int @id @default(autoincrement()) + id String @id @default(uuid()) @db.Uuid date DateTime taskName String @db.VarChar(255) status TaskStatus createdAt DateTime @default(now()) updatedAt DateTime @updatedAt user User? @relation(name: "UserTasks", fields: [userId], references: [id], onDelete: Cascade) - userId Int? + userId String? @db.Uuid issuedBy User? @relation(name: "IssuedTasks", fields: [issuedById], references: [id], onDelete: SetNull) - issuedById Int? + issuedById String? @db.Uuid @@index([userId]) @@index([issuedById]) @@ -93,7 +96,7 @@ enum TaskStatus { // SleepData model represents sleep data associated with users model SleepData { - id Int @id @default(autoincrement()) + id String @id @default(uuid()) @db.Uuid date DateTime sleepStart DateTime sleepEnd DateTime @@ -101,7 +104,7 @@ model SleepData { createdAt DateTime @default(now()) updatedAt DateTime @updatedAt user User? @relation(fields: [userId], references: [id], onDelete: Cascade) - userId Int? + userId String? @db.Uuid @@index([userId]) } @@ -115,32 +118,33 @@ enum SleepType { // Survey model represents surveys created by users model Survey { - id Int @id @default(autoincrement()) + id String @id @default(uuid()) @db.Uuid topic String @default("question") @db.VarChar(255) description String @db.Text createdAt DateTime @default(now()) updatedAt DateTime @updatedAt user User? @relation(fields: [userId], references: [id], onDelete: Cascade) - userId Int? + userId String? @db.Uuid questions Question[] @@index([userId]) @@index([topic]) } +// Quiz model represents quizzes created by users model Quiz { id Int @id @default(autoincrement()) topic String @default("periods") @db.VarChar(255) createdAt DateTime @default(now()) updatedAt DateTime @updatedAt questions Question[] - userId Int? + userId String? @db.Uuid user User? @relation(fields: [userId], references: [id]) @@index([topic]) } -// Question model represents questions in surveys +// Question model represents questions in surveys or quizzes model Question { id Int @id @default(autoincrement()) text String @db.Text @@ -153,7 +157,7 @@ model Question { updatedAt DateTime @updatedAt survey Survey? @relation(fields: [surveyId], references: [id], onDelete: Cascade) - surveyId Int? + surveyId String? @db.Uuid Quiz Quiz? @relation(fields: [quizId], references: [id]) quizId Int? @@ -168,14 +172,14 @@ enum QuestionType { BOOLEAN } -// Answer model represents answers to survey questions +// Answer model represents answers to survey or quiz questions model Answer { - id Int @id @default(autoincrement()) + id String @id @default(uuid()) @db.Uuid response String @db.Text createdAt DateTime @default(now()) updatedAt DateTime @updatedAt user User? @relation(fields: [userId], references: [id], onDelete: Cascade) - userId Int? + userId String? @db.Uuid question Question? @relation(fields: [questionId], references: [id], onDelete: Cascade) questionId Int? @@ -185,14 +189,14 @@ model Answer { // MedicalQuery model represents medical queries made by users model MedicalQuery { - id Int @id @default(autoincrement()) + id String @id @default(uuid()) @db.Uuid query String @db.Text response String @db.Text status QueryStatus createdAt DateTime @default(now()) updatedAt DateTime @updatedAt user User? @relation(fields: [userId], references: [id], onDelete: Cascade) - userId Int? + userId String? @db.Uuid @@index([userId]) } diff --git a/prisma/seed.ts b/prisma/seed.ts index 8f45146..4cd7406 100644 --- a/prisma/seed.ts +++ b/prisma/seed.ts @@ -1,4 +1,4 @@ -import { PrismaClient, Gender, Position, TaskStatus, SleepType, QuestionType, QueryStatus } from '@prisma/client'; +import { PrismaClient, Gender, Position } from '@prisma/client'; import { faker } from '@faker-js/faker'; const prisma = new PrismaClient(); @@ -11,114 +11,20 @@ async function main() { for (let i = 0; i < 10; i++) { const user = await prisma.user.create({ data: { - name: faker.name.fullName(), - age: faker.datatype.number({ min: 18, max: 70 }), - birthday: faker.date.past(50, new Date('2000-01-01')), - location: faker.address.city(), + name: faker.person.fullName(), + age: faker.number.int({ min: 18, max: 70 }), + birthday: faker.date.birthdate(), + location: faker.location.city(), gender: faker.helpers.arrayElement(Object.values(Gender)), email: faker.internet.email(), - contact: faker.phone.number('##########'), + contact: faker.phone.number(), picture: faker.image.avatar(), position: faker.helpers.arrayElement(Object.values(Position)), + language: faker.helpers.arrayElement(['english', 'tamil', 'hindi']), }, }); users.push(user); } - - // Generate blogs - for (const user of users) { - for (let i = 0; i < 3; i++) { - await prisma.blog.create({ - data: { - title: faker.lorem.sentence(), - picture: faker.image.imageUrl(), - content: faker.lorem.paragraphs(3), - authorName: user.name, - userId: user.id, - region: faker.helpers.arrayElement(['general', 'tech', 'health', 'travel']), - }, - }); - } - } - - // Generate tasks - for (const user of users) { - for (let i = 0; i < 3; i++) { - await prisma.task.create({ - data: { - date: faker.date.future(), - taskName: faker.lorem.words(3), - status: faker.helpers.arrayElement(Object.values(TaskStatus)), - userId: user.id, - issuedById: faker.helpers.arrayElement(users).id, - }, - }); - } - } - - // Generate sleep data - for (const user of users) { - for (let i = 0; i < 3; i++) { - await prisma.sleepData.create({ - data: { - date: faker.date.past(), - sleepStart: faker.date.past(), - sleepEnd: faker.date.past(), - sleepType: faker.helpers.arrayElement(Object.values(SleepType)), - userId: user.id, - }, - }); - } - } - - // Generate surveys and questions - for (const user of users) { - for (let i = 0; i < 2; i++) { - const survey = await prisma.survey.create({ - data: { - topic: faker.lorem.words(3), - description: faker.lorem.paragraphs(2), - userId: user.id, - }, - }); - - for (let j = 0; j < 5; j++) { - const question = await prisma.question.create({ - data: { - text: faker.lorem.sentence(), - type: faker.helpers.arrayElement(Object.values(QuestionType)), - correctAnswer: faker.lorem.sentence(), - surveyId: survey.id, - }, - }); - - // Generate answers - for (const user of users) { - await prisma.answer.create({ - data: { - response: faker.lorem.sentence(), - userId: user.id, - questionId: question.id, - }, - }); - } - } - } - } - - // Generate medical queries - for (const user of users) { - for (let i = 0; i < 1; i++) { - await prisma.medicalQuery.create({ - data: { - query: faker.lorem.paragraph(), - response: faker.lorem.paragraph(), - status: faker.helpers.arrayElement(Object.values(QueryStatus)), - userId: user.id, - }, - }); - } - } } main() diff --git a/src/auth/interfaces/otpCache.interface.ts b/src/auth/interfaces/otpCache.interface.ts index 273ed34..8eec30d 100644 --- a/src/auth/interfaces/otpCache.interface.ts +++ b/src/auth/interfaces/otpCache.interface.ts @@ -1,6 +1,6 @@ export interface otpCache { otp: number; user: { - id: number; + id: string; }; } \ No newline at end of file diff --git a/src/auth/interfaces/user.interface.ts b/src/auth/interfaces/user.interface.ts index 03a05b4..661352d 100644 --- a/src/auth/interfaces/user.interface.ts +++ b/src/auth/interfaces/user.interface.ts @@ -1,4 +1,4 @@ export interface UserInterface { - id: number ; + id: string ; position?: string; } \ No newline at end of file diff --git a/src/blog/blog.controller.ts b/src/blog/blog.controller.ts index 0a8fa28..a873246 100644 --- a/src/blog/blog.controller.ts +++ b/src/blog/blog.controller.ts @@ -71,8 +71,8 @@ export class BlogController { @ApiOperation({ summary: 'Find a blog by ID' }) @ApiResponse({ status: 200, description: 'Blog retrieved successfully.' }) @ApiResponse({ status: 404, description: 'Blog not found.' }) - async findById(@Param('id') id: number, @Res() res) { - const result = await this.blogService.findById(+id); + async findById(@Param('id') id: string, @Res() res) { + const result = await this.blogService.findById(id); return res.status(result.status).json(result); } @@ -81,11 +81,11 @@ export class BlogController { @ApiResponse({ status: 200, description: 'Blog updated successfully.' }) @ApiResponse({ status: 404, description: 'Blog not found.' }) async update( - @Param('id') id: number, + @Param('id') id: string, @Body() updateBlogDto: UpdateBlogDto, @Res() res, ) { - const result = await this.blogService.update(+id, updateBlogDto); + const result = await this.blogService.update(id, updateBlogDto); return res.status(result.status).json(result); } @@ -93,8 +93,8 @@ export class BlogController { @ApiOperation({ summary: 'Delete a blog by ID' }) @ApiResponse({ status: 200, description: 'Blog deleted successfully.' }) @ApiResponse({ status: 404, description: 'Blog not found.' }) - async delete(@Param('id') id: number, @Res() res) { - const result = await this.blogService.delete(+id); + async delete(@Param('id') id: string, @Res() res) { + const result = await this.blogService.delete(id); return res.status(result.status).json(result); } } diff --git a/src/blog/blog.service.ts b/src/blog/blog.service.ts index 4268656..88f3caa 100644 --- a/src/blog/blog.service.ts +++ b/src/blog/blog.service.ts @@ -117,7 +117,7 @@ export class BlogService { */ @ApiResponse({ status: 200, description: 'Blog retrieved successfully.' }) @ApiResponse({ status: 404, description: 'Blog not found.' }) - async findById(id: number) { + async findById(id: string) { const blog = await this.prismaService.blog.findUnique({ where: { id }, }); @@ -137,7 +137,7 @@ export class BlogService { */ @ApiResponse({ status: 200, description: 'Blog updated successfully.' }) @ApiResponse({ status: 404, description: 'Blog not found.' }) - async update(id: number, updateBlogDto: UpdateBlogDto) { + async update(id: string, updateBlogDto: UpdateBlogDto) { const { title, region, pic, content } = updateBlogDto; const existingBlog = await this.prismaService.blog.findUnique({ @@ -163,7 +163,7 @@ export class BlogService { */ @ApiResponse({ status: 200, description: 'Blog deleted successfully.' }) @ApiResponse({ status: 404, description: 'Blog not found.' }) - async delete(id: number) { + async delete(id: string) { const existingBlog = await this.prismaService.blog.findUnique({ where: { id }, }); diff --git a/src/blog/dto/create-blog.dto.ts b/src/blog/dto/create-blog.dto.ts index 8d088cc..24d00e0 100644 --- a/src/blog/dto/create-blog.dto.ts +++ b/src/blog/dto/create-blog.dto.ts @@ -14,7 +14,7 @@ export class CreateBlogDto { region: string; @IsInt() - authorId: number; + authorId: string; @IsString() language: string; diff --git a/src/main.ts b/src/main.ts index fada5ef..6c7df9c 100644 --- a/src/main.ts +++ b/src/main.ts @@ -6,17 +6,20 @@ import { AllExceptionsFilter } from './custom-exception/custom-exception.filter' async function bootstrap() { const app = await NestFactory.create(AppModule, { - cors: true + cors: true, }); app.use(cookieParser()); // Swagger docs with authentication const config = new DocumentBuilder() - .setTitle('GooglexYug') - .setDescription('The googlexyug API description') + .setTitle('Athena Backend ') + .setDescription('The Athena API description') .setVersion('1.0') .addTag('app') - .addBearerAuth({ type: 'http', bearerFormat: "JWT", scheme: "bearer", in: "header" }, "access-token") + .addBearerAuth( + { type: 'http', bearerFormat: 'JWT', scheme: 'bearer', in: 'header' }, + 'access-token', + ) .build(); const document = SwaggerModule.createDocument(app, config); diff --git a/src/quiz/quiz.controller.ts b/src/quiz/quiz.controller.ts index 9e83d93..5e6909c 100644 --- a/src/quiz/quiz.controller.ts +++ b/src/quiz/quiz.controller.ts @@ -17,7 +17,7 @@ export class QuizController { // @UseGuards(JwtGuard) @Post() create(@Body() createQuizDto: CreateQuizDto) { - const userId = 1 ; + const userId = `1` ; return this.quizService.create(userId, createQuizDto); } diff --git a/src/quiz/quiz.service.ts b/src/quiz/quiz.service.ts index f9d20bd..ba9d4e6 100644 --- a/src/quiz/quiz.service.ts +++ b/src/quiz/quiz.service.ts @@ -5,43 +5,44 @@ import { Prisma } from '@prisma/client'; @Injectable() export class QuizService { - - constructor(private readonly prismaService: PrismaService) { } - async create(userId: number, createQuizDto: CreateQuizDto) { + constructor(private readonly prismaService: PrismaService) {} + async create(userId: string, createQuizDto: CreateQuizDto) { const { questions, topic } = createQuizDto; try { const result = await this.prismaService.$transaction(async (prisma) => { const quiz = await prisma.quiz.create({ data: { topic, - userId - } + userId, + }, }); - await Promise.all(questions.map(question => { - return prisma.question.create({ - data: { - correctAnswer: question.correctAnswer, - text: question.text, - options: question.options, - type: question.type, - quizId: quiz.id - } - }); - })); + await Promise.all( + questions.map((question) => { + return prisma.question.create({ + data: { + correctAnswer: question.correctAnswer, + text: question.text, + options: question.options, + type: question.type, + quizId: quiz.id, + }, + }); + }), + ); return quiz; }); return result; } catch (error) { - throw (error); + throw error; } } async findAll(topic: string) { try { - if (topic === "") { + if (topic === '') { const quizzesFull = await this.prismaService.quiz.findMany({ include: { questions: { @@ -49,17 +50,17 @@ export class QuizService { text: true, type: true, correctAnswer: true, - options: true - } - } - } + options: true, + }, + }, + }, }); - return quizzesFull.map(quiz => ({ + return quizzesFull.map((quiz) => ({ topic: quiz.topic, created: quiz.createdAt, - questions: quiz.questions - })) + questions: quiz.questions, + })); } const quizzes = await this.prismaService.quiz.findMany({ @@ -70,19 +71,19 @@ export class QuizService { text: true, type: true, correctAnswer: true, - options: true - } - } - } + options: true, + }, + }, + }, }); - return quizzes.map(quiz => ({ + return quizzes.map((quiz) => ({ topic: quiz.topic, created: quiz.createdAt, - questions: quiz.questions + questions: quiz.questions, })); } catch (error) { - throw (error); + throw error; } } @@ -91,29 +92,27 @@ export class QuizService { const quiz = await this.prismaService.quiz.findUniqueOrThrow({ where: { id }, include: { - questions: true - } + questions: true, + }, }); return quiz; } catch (error) { - throw (error); + throw error; } } async findTopics() { try { - const quizTopics = await this.prismaService.quiz.findMany( - { - select: { - topic: true - }, - distinct: ['topic'] - } - ); + const quizTopics = await this.prismaService.quiz.findMany({ + select: { + topic: true, + }, + distinct: ['topic'], + }); return quizTopics.flatMap((quizTopic) => quizTopic.topic); } catch (error) { - throw error + throw error; } } // async update(id: number, updateQuizDto: UpdateQuizDto) { @@ -141,7 +140,7 @@ export class QuizService { return deletedQuiz; } catch (error) { - throw (error); + throw error; } } } diff --git a/src/survey/survey.controller.ts b/src/survey/survey.controller.ts index ba91c9c..e5322af 100644 --- a/src/survey/survey.controller.ts +++ b/src/survey/survey.controller.ts @@ -18,7 +18,7 @@ export class SurveyController { @ApiOperation({ summary: "Create a new survey" }) @ApiResponse({ status: 201, description: 'The survey has been successfully created.' }) create(@Body() createSurveyDto: CreateSurveyDto) { - const userId = 1; + const userId = `1`; return this.surveyService.create(createSurveyDto, userId); } @@ -41,7 +41,7 @@ export class SurveyController { @ApiOperation({ summary: "Find a specific survey" }) @ApiResponse({ status: 200, description: 'Survey retrieved successfully.' }) findOne(@Param('id') id: string) { - return this.surveyService.findOne(+id); + return this.surveyService.findOne(id); } @@ -49,7 +49,7 @@ export class SurveyController { @ApiOperation({ summary: "Remove a specific survey" }) @ApiResponse({ status: 200, description: 'Survey removed successfully.' }) remove(@Param('id') id: string) { - return this.surveyService.remove(+id); + return this.surveyService.remove(id); } @Get('inferences') @@ -73,6 +73,6 @@ export class SurveyController { @Get('/response/:id') @ApiOperation({ summary: "Response to a survey based on id" }) async ReponseBasedOnId(@Param('id') surveyId: string) { - return await this.surveyService.surveyResponseBasedOnId(+surveyId); + return await this.surveyService.surveyResponseBasedOnId(surveyId); } } diff --git a/src/survey/survey.service.ts b/src/survey/survey.service.ts index 588a2c5..cf154e3 100644 --- a/src/survey/survey.service.ts +++ b/src/survey/survey.service.ts @@ -1,13 +1,13 @@ import { HttpException, Injectable, NotFoundException } from '@nestjs/common'; import { CreateSurveyDto } from './dto/create-survey.dto'; import { PrismaService } from 'src/prisma/prisma.service'; -import { QuestionType } from "@prisma/client" +import { QuestionType } from '@prisma/client'; import { SurveyResponseDto } from './dto/survey-response.dto'; @Injectable() export class SurveyService { - constructor(private readonly prismaService: PrismaService) { } + constructor(private readonly prismaService: PrismaService) {} - async create(createSurveyDto: CreateSurveyDto, userId: number) { + async create(createSurveyDto: CreateSurveyDto, userId: string) { try { const { topic, description, questions } = createSurveyDto; const result = await this.prismaService.$transaction(async (prisma) => { @@ -15,33 +15,33 @@ export class SurveyService { data: { description, topic, - userId - } - }) - await Promise.all(questions.map( - (question) => { + userId, + }, + }); + await Promise.all( + questions.map((question) => { return prisma.question.create({ data: { - correctAnswer: "what your heart desires", + correctAnswer: 'what your heart desires', text: question.text, type: question.type as QuestionType, options: question.options, - surveyId: survey.id - } - }) - } - )) - }) + surveyId: survey.id, + }, + }); + }), + ); + }); return result; } catch (error) { - throw (error) + throw error; } } async findAll(topic: string) { try { - if (topic === "") { + if (topic === '') { return await this.prismaService.survey.findMany({ select: { id: true, @@ -53,14 +53,14 @@ export class SurveyService { text: true, type: true, id: true, - } - } - } + }, + }, + }, }); } return await this.prismaService.survey.findMany({ where: { - topic + topic, }, select: { id: true, @@ -72,16 +72,16 @@ export class SurveyService { text: true, type: true, id: true, - } - } - } + }, + }, + }, }); } catch (error) { - throw (error) + throw error; } } - async findOne(id: number) { + async findOne(id: string) { try { const survey = await this.prismaService.survey.findUnique({ where: { id }, @@ -93,12 +93,11 @@ export class SurveyService { return survey; } catch (error) { - throw (error) + throw error; } } - - async remove(id: number) { + async remove(id: string) { try { const survey = await this.prismaService.survey.findUnique({ where: { id }, @@ -114,9 +113,8 @@ export class SurveyService { return `Survey removed successfully`; } catch (error) { - throw error + throw error; } - } async getInferences(topic: string) { @@ -132,41 +130,43 @@ export class SurveyService { const answers = surveys.map((survey) => survey.description); - const response = { data: answers, status: 201 } + const response = { data: answers, status: 201 }; //? const response = await this.httpService.post('https://api.gemini.com/inferences', { answers }).toPromise(); if (response.status !== 200) { - throw new HttpException('Failed to get inferences from Gemini API', response.status); + throw new HttpException( + 'Failed to get inferences from Gemini API', + response.status, + ); } return response.data; } - async surveyResponse(surveyResponse: SurveyResponseDto, userId: number) { + async surveyResponse(surveyResponse: SurveyResponseDto, userId: string) { const { answers } = surveyResponse; try { - await Promise.all(answers.map( - (answer) => { + await Promise.all( + answers.map((answer) => { return this.prismaService.answer.create({ data: { response: answer.response, questionId: answer.questionId, - userId - } - }) - } - )) - } - catch (error) { - throw (error) + userId, + }, + }); + }), + ); + } catch (error) { + throw error; } } - async surveyResponseBasedOnId(id: number) { + async surveyResponseBasedOnId(id: string) { try { - const repsonses = await this.prismaService.survey.findUniqueOrThrow({ + const repsonses = await this.prismaService.survey.findUniqueOrThrow({ where: { - id + id, }, select: { description: true, @@ -177,38 +177,40 @@ export class SurveyService { include: { user: { select: { - gender: true, age: true, location: true - } - } - } + gender: true, + age: true, + location: true, + }, + }, + }, }, id: true, options: true, text: true, - } - } - } - }) + }, + }, + }, + }); return { - "description" : repsonses.description, - "topic" : repsonses.topic, - "questions" : repsonses.questions.map((res) => { - return { - "text" : res.text, - "options" : res.options, - "answers" : res.answers.map((ans) => { - return { - "response" : ans.response, - "age" : ans.user.age, - "gender" : ans.user.gender, - "location" : ans.user.location - } - }) - } - }) - } + description: repsonses.description, + topic: repsonses.topic, + questions: repsonses.questions.map((res) => { + return { + text: res.text, + options: res.options, + answers: res.answers.map((ans) => { + return { + response: ans.response, + age: ans.user.age, + gender: ans.user.gender, + location: ans.user.location, + }; + }), + }; + }), + }; } catch (error) { - throw (error) + throw error; } } } diff --git a/src/tasks/tasks.controller.ts b/src/tasks/tasks.controller.ts index 550bf75..072467b 100644 --- a/src/tasks/tasks.controller.ts +++ b/src/tasks/tasks.controller.ts @@ -35,7 +35,7 @@ export class TasksController { @ApiParam({ name: 'id', type: Number, required: true }) async findAll(@Param('id') userId: string) { - const result = await this.tasksService.findAll(+userId); + const result = await this.tasksService.findAll(userId); return result; } @@ -45,7 +45,7 @@ export class TasksController { @ApiResponse({ status: 200, description: 'Task retrieved successfully.' }) @ApiParam({ name: 'id', type: Number, description: 'The ID of the task', required: true }) async findOne(@Param('id') id: string) { - const result = await this.tasksService.findOne(+id); + const result = await this.tasksService.findOne(id); return result; } @@ -55,7 +55,7 @@ export class TasksController { @ApiResponse({ status: 200, description: 'Task updated successfully.' }) @ApiParam({ name: 'id', type: Number, description: 'The ID of the task', required: true }) async update(@Param('id') id: string, @Body() updateTaskDto: UpdateTaskDto, @User() user: UserInterface) { - const result = await this.tasksService.update(+id, updateTaskDto,user.id); + const result = await this.tasksService.update(id, updateTaskDto,user.id); return result; } @@ -65,7 +65,7 @@ export class TasksController { @ApiResponse({ status: 200, description: 'Task removed successfully.' }) @ApiParam({ name: 'id', type: Number, description: 'The ID of the task', required: true }) async remove(@Param('id') id: string) { - const result = await this.tasksService.remove(+id); + const result = await this.tasksService.remove(id); return result; } } diff --git a/src/tasks/tasks.service.ts b/src/tasks/tasks.service.ts index 76249ae..135f28c 100644 --- a/src/tasks/tasks.service.ts +++ b/src/tasks/tasks.service.ts @@ -1,38 +1,41 @@ -import { Injectable, NotFoundException, InternalServerErrorException } from '@nestjs/common'; +import { + Injectable, + NotFoundException, + InternalServerErrorException, +} from '@nestjs/common'; import { CreateTaskDto } from './dto/create-task.dto'; import { UpdateTaskDto } from './dto/update-task.dto'; import { PrismaService } from 'src/prisma/prisma.service'; @Injectable() export class TasksService { - constructor(private readonly prismaService: PrismaService) { } + constructor(private readonly prismaService: PrismaService) {} /** * Asynchronously creates a new task. - * + * * This function creates a task with the given details, associates it with the users * identified by their email and ID, and sets the task status to UPCOMING. - * + * * @param {CreateTaskDto} createTaskDto - The data transfer object containing task details. * @param {number} userId - The ID of the user issuing the task. * @returns The newly created task object. * @throws {InternalServerErrorException,HttpException,BadRequestException} If there is an error during task creation. */ - async create(createTaskDto: CreateTaskDto, userId: number) { + async create(createTaskDto: CreateTaskDto, userId: string) { const { IssuedToEmail, date, taskName } = createTaskDto; const issuedTo = await this.prismaService.user.findUniqueOrThrow({ where: { - email: IssuedToEmail - } + email: IssuedToEmail, + }, }); const issuedBy = await this.prismaService.user.findUniqueOrThrow({ where: { - id: userId - } + id: userId, + }, }); - try { const result = await this.prismaService.task.create({ data: { @@ -40,32 +43,32 @@ export class TasksService { taskName, issuedById: issuedBy.id, userId: issuedTo.id, - status: 'UPCOMING' - } + status: 'UPCOMING', + }, }); return result; } catch (error) { - throw (error) + throw error; } } /** -* Asynchronously finds all tasks associated with a user. -* -* This function retrieves all tasks where the user is either the issuer or the assignee. -* It differentiates the tasks issued by the user from those issued to the user. -* -* @param {number} userId - The id of the user whose tasks are to be found. -* @returns An object containing two arrays: 'issuedToTheUser' and 'issuedByTheUser'. -* @throws {NotFoundException,HttpException,BadRequestException} If the user with the given id is not found. -*/ - async findAll(userId: number) { + * Asynchronously finds all tasks associated with a user. + * + * This function retrieves all tasks where the user is either the issuer or the assignee. + * It differentiates the tasks issued by the user from those issued to the user. + * + * @param {number} userId - The id of the user whose tasks are to be found. + * @returns An object containing two arrays: 'issuedToTheUser' and 'issuedByTheUser'. + * @throws {NotFoundException,HttpException,BadRequestException} If the user with the given id is not found. + */ + async findAll(userId: string) { try { const user = await this.prismaService.user.findUnique({ where: { - id: userId - } + id: userId, + }, }); if (!user) { @@ -76,73 +79,71 @@ export class TasksService { where: { OR: [ { - issuedById: user.id + issuedById: user.id, }, { - userId: user.id - } - ] - } + userId: user.id, + }, + ], + }, }); return { - issuedToTheUser: tasks.filter(task => task.issuedById == user.id), - issuedByTheUser: tasks.filter(task => task.userId == user.id) + issuedToTheUser: tasks.filter((task) => task.issuedById == user.id), + issuedByTheUser: tasks.filter((task) => task.userId == user.id), }; - } - catch (error) { - throw (error) + } catch (error) { + throw error; } } /** - * Asynchronously finds a single task by its ID. - * - * This function retrieves a task based on the provided ID. If no task is found, - * it throws an exception. - * - * @param {number} id - The ID of the task to be retrieved. - * @returns The task object if found. - * @throws {NotFoundException,HttpException,BadRequestException} If no task with the given ID is found. - */ - async findOne(id: number) { + * Asynchronously finds a single task by its ID. + * + * This function retrieves a task based on the provided ID. If no task is found, + * it throws an exception. + * + * @param {number} id - The ID of the task to be retrieved. + * @returns The task object if found. + * @throws {NotFoundException,HttpException,BadRequestException} If no task with the given ID is found. + */ + async findOne(id: string) { try { const task = await this.prismaService.task.findUnique({ where: { - id - } + id, + }, }); if (!task) { throw new NotFoundException('Task not available'); } return task; } catch (error) { - throw (error) + throw error; } - } /** - * Asynchronously updates an existing task. - * - * This function updates a task with the given ID using the provided task details. - * If no task is found with the ID, it throws an exception. The function also sets - * the 'updatedAt' field to the current date and time. - * - * @param {number} id - The ID of the task to be updated. - * @param {UpdateTaskDto} updateTaskDto - The data transfer object containing updated task details. - * @returns The updated task object. - * @throws {NotFoundException} If no task with the given ID is found. - * @throws {InternalServerErrorException} If there is an error during task update. - */ - async update(id: number, updateTaskDto: UpdateTaskDto, userId: number) { + * Asynchronously updates an existing task. + * + * This function updates a task with the given ID using the provided task details. + * If no task is found with the ID, it throws an exception. The function also sets + * the 'updatedAt' field to the current date and time. + * + * @param {number} id - The ID of the task to be updated. + * @param {UpdateTaskDto} updateTaskDto - The data transfer object containing updated task details. + * @returns The updated task object. + * @throws {NotFoundException} If no task with the given ID is found. + * @throws {InternalServerErrorException} If there is an error during task update. + */ + async update(id: string, updateTaskDto: UpdateTaskDto, userId: string) { const { IssuedToEmail, date, taskName, status } = updateTaskDto; const task = await this.prismaService.task.findUnique({ where: { id, - userId - } + userId, + }, }); if (!task) { @@ -152,14 +153,14 @@ export class TasksService { try { const updatedTask = await this.prismaService.task.update({ where: { - id + id, }, data: { taskName, date, updatedAt: new Date(), status, - } + }, }); return updatedTask; @@ -169,17 +170,17 @@ export class TasksService { } /** - * Asynchronously removes a task by its ID. - * - * This function deletes a task based on the provided ID. If no task is found, - * it throws an exception. Upon successful deletion, it returns a confirmation message. - * - * @param {number} id - The ID of the task to be removed. - * @returns A confirmation message indicating successful removal. - * @throws {NotFoundException} If no task with the given ID is found. - * @throws {InternalServerErrorException} If there is an error during task removal. - */ - async remove(id: number) { + * Asynchronously removes a task by its ID. + * + * This function deletes a task based on the provided ID. If no task is found, + * it throws an exception. Upon successful deletion, it returns a confirmation message. + * + * @param {number} id - The ID of the task to be removed. + * @returns A confirmation message indicating successful removal. + * @throws {NotFoundException} If no task with the given ID is found. + * @throws {InternalServerErrorException} If there is an error during task removal. + */ + async remove(id: string) { const task = await this.prismaService.task.findUnique({ where: { id }, }); @@ -195,7 +196,7 @@ export class TasksService { return `Task #${id} removed successfully`; } catch (error) { - throw (error) + throw error; } } } diff --git a/src/user/user.service.ts b/src/user/user.service.ts index 3641ffa..4e4671a 100644 --- a/src/user/user.service.ts +++ b/src/user/user.service.ts @@ -40,7 +40,7 @@ export class UserService { } - async findOne(userId: number) { + async findOne(userId: string) { try { const user = await this.prismaService.user.findUnique({ where: { id: userId }, @@ -55,7 +55,7 @@ export class UserService { } - async update(id: number, updateUserDto: UpdateUserDto) { + async update(id: string, updateUserDto: UpdateUserDto) { try { util.checkUpdateDto(updateUserDto); const user = await this.prismaService.user.update({ @@ -68,7 +68,7 @@ export class UserService { } } - async remove(id: number) { + async remove(id: string) { try { const user = await this.prismaService.user.delete({ where: { id },