Skip to content
Snippets Groups Projects
Commit ab81cd0c authored by Ivan Alglave's avatar Ivan Alglave
Browse files

CRUD for groups / GET as Observable

parent 35a9e597
No related branches found
No related tags found
1 merge request!2Crud groups
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { mongodb } from './config';
import { GroupsModule } from './groups/groups.module';
@Module({
imports: [MongooseModule.forRoot(mongodb.uri)],
controllers: [],
providers: [],
imports: [GroupsModule, MongooseModule.forRoot(mongodb.uri)],
})
export class AppModule {}
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { from, map, Observable } from 'rxjs';
import { CreateGroupDto } from '../dto/create-group.dto';
import { UpdateGroupDto } from '../dto/update-group.dto';
import { Group } from '../schemas/group.schema';
@Injectable()
export class GroupsDao {
constructor(
@InjectModel(Group.name)
private readonly _groupModel: Model<Group>,
) {}
find = (): Observable<Group[]> =>
from(this._groupModel.find({})).pipe(map((groups) => [].concat(groups)));
findById = (id: string): Observable<Group | void> =>
from(this._groupModel.findById(id));
save = (group: CreateGroupDto): Observable<Group> =>
from(new this._groupModel(group).save());
findByIdAndUpdate = (
id: string,
group: UpdateGroupDto,
): Observable<Group | void> =>
from(
this._groupModel.findByIdAndUpdate(id, group, {
new: true,
runValidators: true,
}),
);
findByIdAndRemove = (id: string): Observable<Group | void> =>
from(this._groupModel.findByIdAndRemove(id));
}
import { IsBoolean, IsString, IsNotEmpty, IsMongoId } from 'class-validator';
export class CreateGroupDto {
@IsString()
@IsNotEmpty()
id: string;
@IsBoolean()
final: boolean;
@IsMongoId()
@IsNotEmpty()
parent: any;
}
import { IsBoolean, IsString, IsNotEmpty, IsMongoId } from 'class-validator';
export class UpdateGroupDto {
@IsString()
@IsNotEmpty()
id: string;
@IsBoolean()
final: boolean;
@IsMongoId()
@IsNotEmpty()
parent: string;
}
import { Group } from '../schemas/group.schema';
export class GroupEntity {
_id: string;
id: string;
final: boolean;
responsibles: string[];
secretaries: string[];
students: string[];
parent: string;
constructor(partial: Partial<Group>) {
Object.assign(this, partial);
}
}
import {
Controller,
Get,
Post,
Put,
Delete,
Param,
Body,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { CreateGroupDto } from './dto/create-group.dto';
import { UpdateGroupDto } from './dto/update-group.dto';
import { GroupEntity } from './entities/group.entity';
import { GroupsService } from './groups.service';
@Controller('groups')
export class GroupsController {
constructor(private readonly _groupsService: GroupsService) {}
@Get()
findAll(): Observable<GroupEntity[] | void> {
return this._groupsService.findAll();
}
@Get(':id')
findOne(@Param() params: { id: string }): Observable<GroupEntity> {
return this._groupsService.findOne(params.id);
}
@Post()
create(@Body() createGroupDto: CreateGroupDto): Observable<GroupEntity> {
return this._groupsService.create(createGroupDto);
}
@Put(':id')
update(
@Param() params: { id: string },
@Body() updateGroupDto: UpdateGroupDto,
): Observable<GroupEntity> {
return this._groupsService.update(params.id, updateGroupDto);
}
@Delete(':id')
delete(@Param() params: { id: string }): Observable<void> {
return this._groupsService.delete(params.id);
}
}
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { GroupsDao } from './dao/groups.dao';
import { GroupsController } from './groups.controller';
import { GroupsService } from './groups.service';
import { Group, GroupSchema } from './schemas/group.schema';
@Module({
imports: [
MongooseModule.forFeature([{ name: Group.name, schema: GroupSchema }]),
],
controllers: [GroupsController],
providers: [GroupsService, GroupsDao],
})
export class GroupsModule {}
import {
Injectable,
UnprocessableEntityException,
NotFoundException,
ConflictException,
} from '@nestjs/common';
import {
Observable,
of,
filter,
map,
mergeMap,
defaultIfEmpty,
catchError,
throwError,
} from 'rxjs';
import { GroupsDao } from './dao/groups.dao';
import { CreateGroupDto } from './dto/create-group.dto';
import { UpdateGroupDto } from './dto/update-group.dto';
import { GroupEntity } from './entities/group.entity';
@Injectable()
export class GroupsService {
constructor(private readonly _groupsDao: GroupsDao) {}
findAll = (): Observable<GroupEntity[] | void> =>
this._groupsDao.find().pipe(
filter(Boolean),
map((groups) => (groups || []).map((group) => new GroupEntity(group))),
defaultIfEmpty(undefined),
);
findOne = (id: string): Observable<GroupEntity> =>
this._groupsDao.findById(id).pipe(
catchError((e) =>
throwError(() => new UnprocessableEntityException(e.message)),
),
mergeMap((group) =>
!!group
? of(new GroupEntity(group))
: throwError(
() => new NotFoundException(`Group with id ${id} not found`),
),
),
);
create = (group: CreateGroupDto): Observable<GroupEntity> =>
this._prepareNewGroup(group).pipe(
mergeMap((newPreparedGroup: CreateGroupDto) =>
this._groupsDao.save(newPreparedGroup),
),
catchError((e) =>
e.code === 11000
? throwError(
() =>
new ConflictException(
`Group with id ${group.id} already exists`,
),
)
: throwError(() => new UnprocessableEntityException(e.message)),
),
map((groupCreated) => new GroupEntity(groupCreated)),
);
update = (id: string, group: UpdateGroupDto): Observable<GroupEntity> =>
this._groupsDao.findByIdAndUpdate(id, group).pipe(
catchError((e) =>
e.code === 11000
? throwError(
() =>
new ConflictException(
`Group with id ${group.id} already exists`,
),
)
: throwError(() => new UnprocessableEntityException(e.message)),
),
mergeMap((groupUpdated) =>
!!groupUpdated
? of(new GroupEntity(groupUpdated))
: throwError(
() => new NotFoundException(`Group with id '${id}' not found`),
),
),
);
delete = (id: string): Observable<void> =>
this._groupsDao.findByIdAndRemove(id).pipe(
catchError((e) =>
throwError(() => new UnprocessableEntityException(e.message)),
),
mergeMap((groupDeleted) =>
!!groupDeleted
? of(undefined)
: throwError(
() => new NotFoundException(`Group with id '${id}' not found`),
),
),
);
private _prepareNewGroup = (
group: CreateGroupDto,
): Observable<CreateGroupDto> =>
of({
...group,
responsibles: [],
secretaries: [],
students: [],
});
}
export type Group = {
_id: any;
id: string;
final: boolean;
responsibles: string[];
secretaries: string[];
students: string[];
subgroups: string[];
parent: string;
};
import * as mongoose from 'mongoose';
import { Document } from 'mongoose';
import { Prop, raw, Schema, SchemaFactory } from '@nestjs/mongoose';
export type GroupDocument = Group & Document;
@Schema({
toJSON: {
virtuals: true,
transform: (doc: any, ret: any) => {
delete ret._id;
},
},
})
export class Group {
@Prop({
type: mongoose.Schema.Types.ObjectId,
auto: true,
})
_id: any;
@Prop({
type: String,
required: true,
trim: true,
})
id: string;
@Prop({
type: Boolean,
required: true,
trim: true,
})
final: boolean;
@Prop({
type: [mongoose.Schema.Types.ObjectId],
required: true,
trim: true,
})
responsibles: string[];
@Prop({
type: [mongoose.Schema.Types.ObjectId],
required: true,
trim: true,
})
secretaries: string[];
@Prop({
type: [mongoose.Schema.Types.ObjectId],
required: true,
trim: true,
})
students: string[];
@Prop({
type: mongoose.Schema.Types.ObjectId,
required: true,
trim: true,
})
parent: string;
}
export const GroupSchema = SchemaFactory.createForClass(Group);
GroupSchema.index({ id: 1 }, { unique: true });
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment