mysqltypescriptnestjsnestjs-swagger

Nestjsx/crud API not working properly on existing tables


I build my Nextjs project with nestjsx to create Restful API.

My customer.controller.ts

import { Controller } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { Crud, CrudController } from '@nestjsx/crud';

import { CustomersService } from './customers.service';
import { Customer } from './entities/customer.entity';

@Crud({
  model: {
    type: Customer,
  },
})
@ApiTags('Customer')
@Controller('customers')
export class CustomersController implements CrudController<Customer> {
  constructor(public service: CustomersService) {}
}

My customer.service.ts

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { TypeOrmCrudService } from '@nestjsx/crud-typeorm';

import { Customer } from './entities/customer.entity';

@Injectable()
export class CustomersService extends TypeOrmCrudService<Customer> {
  constructor(@InjectRepository(Customer) repo) {
    super(repo);
  }
}

My customers.controller.ts

import { Controller } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { Crud, CrudController } from '@nestjsx/crud';

import { CustomersService } from './customers.service';
import { Customer } from './entities/customer.entity';

@Crud({
  model: {
    type: Customer,
  },
})
@ApiTags('Customer')
@Controller('customers')
export class CustomersController implements CrudController<Customer> {
  constructor(public service: CustomersService) {}
}

customer.entity.ts

import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
} from 'typeorm';

@Entity('tbl_Customers')
export class Customer {
  @PrimaryGeneratedColumn({ type: 'int' })
  CustomerID!: number;

  @Column({ type: 'nvarchar', length: 50 })
  CustomerName!: string;

  @Column({ type: 'nvarchar', length: 50 })
  BillingAddressLine1!: string;

  @Column({ type: 'nvarchar', length: 50 })
  BillingAddressLine2: string | null = null;

  @Column({ type: 'nvarchar', length: 50 })
  City!: string;

  @Column({ type: 'nvarchar', length: 8 })
  PostalCode!: string;
}

Only Get /customers working, other API endpoints will return:

Error: Invalid column name 'undefined'.

I follow every step from the nestjsx doc to setup but cannot find the bug. I also tried setup dto to replace entity in the controller setting, but get the same error. My project connects to MySQL and the connection is working.


Solution

  • After hours of searching, the solution is to add

    params: {
        CustomerId: {
          field: 'CustomerID',
          type: 'number',
          primary: true,
        },
      },
    

    in the controller as primary key is not default id.