Could someone please explain why the appController is functioning correctly while the itemsController, imported from a module, is not?
I have been learning NestJS and followed the documentation as instructed. The appController is working fine with its uncommented endpoint.
import {Controller, Get} from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor() {}
// @Get()
// getHome():string {
// return 'Hello world!';
// }
}
The itemsController.ts - functions correctly if I swap it for appController.ts
import {Controller, Get, HttpException, HttpStatus, Param, Post, Res} from "@nestjs/common";
import {Response} from "express";
import {ItemsService} from "./items.service";
import {ItemDto} from "./dto/item.dto";
@Controller()
export class ItemsController {
constructor(private readonly itemsService: ItemsService) {}
@Get()
getAll(@Res({passthrough: true}) res: Response):string | object {
const items = this.itemsService.getAll();
if(!!items.length) {
res.status(HttpStatus.OK);
return new HttpException({
items: items
}, HttpStatus.OK).getResponse();
}
res.status(HttpStatus.INTERNAL_SERVER_ERROR);
return new HttpException({
items: 'Items length: ' + items.length,
status: HttpStatus.INTERNAL_SERVER_ERROR
}, HttpStatus.INTERNAL_SERVER_ERROR).getResponse();
}
@Post()
create(@Param() params):ItemDto {
return this.itemsService.create(params);
}
}
My Jest tests are also passing successfully:
import { Test } from '@nestjs/testing';
import { ItemsController } from './items/items.controller';
import { ItemsService } from './items/items.service';
import * as request from 'supertest';
import { INestApplication } from "@nestjs/common";
describe('ItemsModule', () => {
let itemsController: ItemsController;
let itemsService: ItemsService;
let app: INestApplication;
beforeEach(async () => {
const moduleRef = await Test.createTestingModule({
controllers: [ItemsController],
providers: [ItemsService],
}).compile();
itemsService = moduleRef.get<ItemsService>(ItemsService);
itemsController = moduleRef.get<ItemsController>(ItemsController);
app = moduleRef.createNestApplication();
await app.init();
});
describe('End-points', () => {
it('/GET Status 200', () => {
return request(app.getHttpServer())
.get('/')
.expect(200)
.expect({
"items": [
{
id: '0',
title: '',
message: ''
}
]
});
});
it('/GET Status 500', () => {
return request(app.getHttpServer())
.get('/')
.expect(500)
.expect({
items: 'Items length: 0',
status: 500
});
});
});
});
I have uploaded all the code on Github. You can view it here