Skip to content

Commit

Permalink
Merge pull request #9 from fga-eps-mds/feat(#122)/ordenacao-jornadas
Browse files Browse the repository at this point in the history
paulohgontijoo authored Sep 2, 2024
2 parents 1b68101 + 6a0c109 commit f23b8b4
Showing 28 changed files with 1,349 additions and 334 deletions.
46 changes: 46 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions src/app.module.ts
Original file line number Diff line number Diff line change
@@ -6,6 +6,7 @@ import { ContentModule } from './content/content.module';
import * as Joi from 'joi';
import { JourneyModule } from './journey/journey.module';
import { TrailModule } from './trail/trail.module';
import { PointModule } from './start_point/point.module';

@Module({
imports: [
@@ -27,6 +28,7 @@ import { TrailModule } from './trail/trail.module';
ContentModule,
JourneyModule,
TrailModule,
PointModule,
],
controllers: [],
providers: [],
16 changes: 15 additions & 1 deletion src/content/content.controller.ts
Original file line number Diff line number Diff line change
@@ -7,12 +7,15 @@ import {
Param,
Body,
NotFoundException,
Logger,
} from '@nestjs/common';
import { ContentService } from './content.service';
import { Content } from './content.schema';
import { UpdateContentsOrderDto } from './dtos/update-content-order.dto';

@Controller('contents')
export class ContentController {
private readonly logger = new Logger(ContentController.name);
constructor(private readonly contentService: ContentService) {}

@Post()
@@ -39,7 +42,7 @@ export class ContentController {
}

@Get('trail/:id')
async findContentsByTrailId(@Param('id') id: string) {
async findContentsByTrailId(@Param('id') id: string): Promise<Content[]> {
return this.contentService.findContentsByTrailId(id);
}

@@ -55,4 +58,15 @@ export class ContentController {
async deleteContent(@Param('id') id: string): Promise<void> {
return this.contentService.deleteContent(id);
}

@Patch('update-content-order')
async updateTrailOrder(@Body() contentsDto: UpdateContentsOrderDto) {
this.logger.log(
`Updating trail order for the list: ${JSON.stringify(contentsDto.contents)}`,
);
const result = await this.contentService.updateContentOrder(
contentsDto.contents,
);
return result;
}
}
1 change: 1 addition & 0 deletions src/content/content.schema.ts
Original file line number Diff line number Diff line change
@@ -9,6 +9,7 @@ export const ContentSchema = new mongoose.Schema(
ref: 'Trail',
required: true,
},
order: { type: Number, default: 0 },
},
{ timestamps: true, collection: 'contents' },
);
37 changes: 28 additions & 9 deletions src/content/content.service.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { Injectable, Logger, NotFoundException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Model, Types } from 'mongoose';
import { Content } from './content.schema';
import { Trail } from '../trail/trail.schema';
import { TrailService } from '../trail/trail.service';
import { ContentInterface } from './dtos/update-content-order.dto';

@Injectable()
export class ContentService {
private readonly logger = new Logger(ContentService.name);

constructor(
@InjectModel('Content') private readonly contentModel: Model<Content>,
@InjectModel('Trail') private readonly trailModel: Model<Trail>,
@@ -23,10 +26,13 @@ export class ContentService {
throw new NotFoundException(`Trail with ID ${trailId} not found`);
}

const contentCount = trailExists.contents.length + 1;

const newContent = new this.contentModel({
title,
content,
trail: trailId,
order: contentCount,
});

await this.trailService.addContentToTrail(
@@ -37,6 +43,15 @@ export class ContentService {
return newContent.save();
}

async findContentsByTrailId(trailId: string): Promise<Content[]> {
this.logger.log(`Finding contents by trail ID: ${trailId}`);
const trail = await this.trailModel.findById(trailId).exec();
if (!trail) {
throw new NotFoundException(`Trail with ID ${trailId} not found`);
}
return this.contentModel.find({ trail: trailId }).exec();
}

async findContentById(id: string): Promise<Content> {
const content = await this.contentModel.findById(id).exec();
if (!content) {
@@ -69,12 +84,16 @@ export class ContentService {
}
}

async findContentsByTrailId(trailId: string): Promise<Content[]> {
const trail = await this.trailModel.findById(trailId).exec();
if (!trail) {
throw new NotFoundException(`Trail with ID ${trailId} not found`);
}
return await this.contentModel.find({ trail: trailId }).exec();
async updateContentOrder(contents: ContentInterface[]) {
const bulkOperations = contents.map((content) => ({
updateOne: {
filter: { _id: new Types.ObjectId(content._id) },
update: { $set: { order: content.order } },
},
}));

const result = await this.contentModel.bulkWrite(bulkOperations);
console.log(`Bulk update result: ${JSON.stringify(result)}`);
return result;
}

}
14 changes: 14 additions & 0 deletions src/content/dtos/update-content-order.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
export interface ContentInterface {
_id: string;
title?: string;
content?: string;
trail?: string;
order?: number;
createdAt?: string;
updatedAt?: string;
__v?: string;
}

export class UpdateContentsOrderDto {
contents: ContentInterface[];
}
3 changes: 2 additions & 1 deletion src/journey/dtos/create-journey.dto.ts
Original file line number Diff line number Diff line change
@@ -4,10 +4,11 @@ export class CreateJourneyDto {
@IsString()
title: string;

@IsOptional()
@IsString()
description: string;

@IsOptional()
@IsMongoId()
user?: string;
pointId?: string;
}
16 changes: 16 additions & 0 deletions src/journey/dtos/updateJourneyOrder.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
export interface JourneyInterface {
_id: string;
title?: string;
point?: string;
createdAt?: string;
updatedAt?: string;
__v?: string;
trails?: string[];
description?: string;
user?: string;
order: number;
}

export class UpdateJourneysOrderDto {
journeys: JourneyInterface[];
}
37 changes: 21 additions & 16 deletions src/journey/journey.controller.ts
Original file line number Diff line number Diff line change
@@ -5,42 +5,38 @@ import {
Body,
Param,
Put,
Req,
UnauthorizedException,
Delete,
Patch,
NotFoundException,
Logger,
} from '@nestjs/common';
import { JourneyService } from './journey.service';
import { Request } from 'express';
import { CreateJourneyDto } from './dtos/create-journey.dto';
import { UpdateJourneysOrderDto } from './dtos/updateJourneyOrder';

@Controller('journeys')
export class JourneyController {
private readonly logger = new Logger(JourneyController.name);
constructor(private readonly journeyService: JourneyService) {}

@Post()
async create(
@Body() createJourneyDto: CreateJourneyDto,
@Req() req: Request,
) {
const authHeader = req.headers.authorization as string;
const token = authHeader?.split(' ')[1];
async create(@Body() body: CreateJourneyDto) {
const pointId = body.pointId;

if (!token) {
throw new UnauthorizedException('Token not found');
if (!pointId) {
throw new NotFoundException('Point ID not provided in body');
}

return this.journeyService.create(createJourneyDto, token);
return this.journeyService.create(body, pointId);
}

@Get()
async findAll() {
return this.journeyService.findAll();
}

@Get('user/:id')
async findByUser(@Param('id') userId: string) {
return this.journeyService.findByUserId(userId);
@Get('point/:id')
async findByPointId(@Param('id') pointId: string) {
return this.journeyService.findByPointId(pointId);
}

@Get(':id')
@@ -68,4 +64,13 @@ export class JourneyController {
) {
return this.journeyService.addTrailToJourney(id, body.trailId);
}

@Patch('update-journeys-order')
async updateTrailOrder(@Body() journeysDto: UpdateJourneysOrderDto) {
this.logger.log(
`Updating trail order for the list: ${JSON.stringify(journeysDto.journeys)}`,
);
const result = await this.journeyService.updateOrder(journeysDto.journeys);
return result;
}
}
4 changes: 3 additions & 1 deletion src/journey/journey.module.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
import { Module } from '@nestjs/common';
import { forwardRef, Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { JourneySchema } from './journey.schema';
import { JourneyService } from './journey.service';
import { HttpModule } from '@nestjs/axios';
import { JourneyController } from './journey.controller';
import { PointModule } from 'src/start_point/point.module';

@Module({
imports: [
HttpModule,
MongooseModule.forFeature([{ name: 'Journey', schema: JourneySchema }]),
forwardRef(() => PointModule),
],
providers: [JourneyService],
controllers: [JourneyController],
10 changes: 6 additions & 4 deletions src/journey/journey.schema.ts
Original file line number Diff line number Diff line change
@@ -3,16 +3,18 @@ import * as mongoose from 'mongoose';
export const JourneySchema = new mongoose.Schema(
{
title: { type: String, required: true },
description: { type: String, required: true },
user: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
description: { type: String },
point: { type: mongoose.Schema.Types.ObjectId, ref: 'Point' },
trails: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Trail' }],
order: { type: Number, default: 0 },
},
{ timestamps: true, collection: 'journeys' },
);

export interface Journey extends mongoose.Document {
title: string;
description: string;
user: mongoose.Schema.Types.ObjectId;
description?: string;
point: mongoose.Schema.Types.ObjectId;
trails?: mongoose.Types.ObjectId[];
order: { type: number; default: 0 };
}
Loading

0 comments on commit f23b8b4

Please sign in to comment.