Skip to main content

Custom Service

To create a custom query service to add your own methods to you can extend the MongooseQueryService.

todo-item.service.ts
import { Model } from 'mongoose'
import { QueryService } from '@ptc-org/nestjs-query-core';
import { InjectModel } from '@nestjs/mongoose';
import { MongooseQueryService } from '@ptc-org/nestjs-query-mongoose';
import { TodoItemEntity } from './entity/todo-item.entity';

@QueryService(TodoItemEntity)
export class TodoItemService extends MongooseQueryService<TodoItemEntity> {
constructor(@InjectModel(TodoItemEntity.name) model: Model<TodoItemEntity>) {
super(model);
}

async markAllAsCompleted(): Promise<number> {
const entities = await this.query({ filter: { completed: { is: true } } });

const { updatedCount } = await this.updateMany(
{ completed: true }, // update
{ id: { in: entities.map((e) => e.id) } }, // filter
);
// do some other business logic
return updatedCount;
}
}

To use the custom service in the auto-generated resolver you can specify the ServiceClass option.

todo-item.module.ts
import { NestjsQueryGraphQLModule } from '@ptc-org/nestjs-query-graphql';
import { NestjsQueryMongooseModule } from '@ptc-org/nestjs-query-mongoose';
import { Module } from '@nestjs/common';
import { TodoItemDTO } from './dto/todo-item.dto';
import { TodoItemEntity } from './todo-item.entity';
import { TodoItemService } from './todo-item.service';

@Module({
imports: [
NestjsQueryGraphQLModule.forFeature({
imports: [
NestjsQueryMongooseModule.forFeature([
{ document: TodoItemEntity, name: TodoItemEntity.name, schema: TodoItemEntitySchema },
]),
],
services: [TodoItemService],
resolvers: [
{
DTOClass: TodoItemDTO,
ServiceClass: TodoItemService,
},
],
}),
],
})
export class TodoItemModule {}