shAkur
shAkur

Reputation: 1002

Nestjs override base service method

I have the following method inside a base service:

crud-base.service.ts

export class CrudBaseService {
  constructor(protected repo: MongoRepository<any>) {}
  
  async create(data) {
    // do stuff
  }
}

Here I want to be able to create my custom create method so I name my method the same as the one from base service

items.service.ts

@Injectable()
export class ItemsService extends CrudBaseService {
  constructor(
    @InjectRepository(Item)
    private itemsRepository: MongoRepository<Item>,
  ) {
    super(itemsRepository);
  }
}

async create(data) {
    // overriding base service method
}

Gives me the following error:

TS2416: Property 'create' in type 'ItemsService' is not assignable to the same property in base type 'CrudBaseService'

Upvotes: 0

Views: 3655

Answers (2)

Omar Montoya
Omar Montoya

Reputation: 1

Make sure that your new service is returning the same type data as the base service. For example:

export abstract class BaseEntityService {
    create(createDTO: any) {
        return this.repository.save(createDTO);
    }
 }

Let's say that the call from above is returning an async call async<any>, your service has to return exactly an async call. You can also return an any type (in your base service) like this and avoid that compiler error:

create(createDTO: any): any {
}

Upvotes: 0

hendra
hendra

Reputation: 2651

The signature of both functions must be the same, that means parameters and return type must be the same. You should make this explicit.

export class CrudBaseService {
  constructor(protected repo: MongoRepository<any>) {}
  
  async create(data: YourType): Promise<YourReturnType> {
    // do stuff
  }
}


@Injectable()
export class ItemsService extends CrudBaseService {
  constructor(
    @InjectRepository(Item)
    private itemsRepository: MongoRepository<Item>,
  ) {
    super(itemsRepository);
  }
}

// this should work
async create(data: YourType): Promise<YourReturnType> {
    // overriding base service method
}

Upvotes: 2

Related Questions