uncledent / mongoose-cursor-pagination-plugin

Cursor pagination plugin for mongoose
8 stars 1 forks source link

Example with a @nestjs/mongoose api? #11

Open bneigher opened 1 year ago

bneigher commented 1 year ago

From the instructions, it's not exactly clear how to use this with a dependency injection based codebase.. For example:

the model

import { v4 as uuidv4 } from 'uuid'
import { Document, ObjectId, SchemaTypes } from 'mongoose'
import { MongoPaging } from 'mongoose-cursor-pagination-plugin'
import { Field, ObjectType } from '@nestjs/graphql'
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'

export type VehicleDocument = VehicleModel & Document

@ObjectType()
@Schema({
  timestamps: true,
})
export class VehicleModel {
  @Field(() => String)
  _id: ObjectId

  @Prop({ required: true, type: String })
  @Field()
  make: string

  @Prop({ required: true, type: String })
  @Field()
  model: string

  @Prop({ type: Boolean, default: () => false })
  @Field()
  isDeleted: boolean
}

export const VehicleSchema = SchemaFactory.createForClass(VehicleModel)
VehicleSchema.plugin(MongoPaging.mongoosePlugin)

the module

import { Module } from '@nestjs/common'
import { MongooseModule } from '@nestjs/mongoose'
import { VehicleSchema } from './vehicle.model' // ABOVE
import { VehicleService } from './vehicle.service'
import { VehicleResolver } from './vehicle.resolver'

@Module({
  imports: [
    MongooseModule.forFeature([{ name: 'Vehicle', schema: VehicleSchema }])
  ],
  providers: [VehicleService, VehicleResolver],
  exports: [VehicleService],
})
export class VehicleModule {}

the service

import { Model } from 'mongoose'
import { InjectModel } from '@nestjs/mongoose'
import { Injectable } from '@nestjs/common'
import { VehicleDocument } from './vehicle.model' // ABOVE model
import { VehicleInput, VehiclesInput, VehicleCreateInput } from './dto'

@Injectable()
export class VehicleService {
  constructor(
    @InjectModel('Vehicle')
    private readonly vehicleModel: Model<VehicleDocument>,
  ) {}

  async getVehicles(input: VehiclesInput) {
    const vehicles = await this.vehicleModel.paginate() // paginate not on the vehicleModel 
    return vehicles
  }
}

anyone able to lend some advice?

grantmcdade commented 1 year ago

We have the following types defined

export interface PaginatedModel<T extends Document> extends Model<T> {
  paginate(paginantionOptions: any, populate?: any): Promise<PaginationResult<T>>;
}

and

export interface PaginationResult<T> {
  hasPrevious?: string;
  previous?: string;
  hasNext?: string;
  next?: string;
  results: T[];
}

Then where you declare the type inside your service use:

private readonly vehicleModel: PaginatedModel<VehicleDocument>

I hope this helps, the main project is no longer in development as I just noticed this by chance.