Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Record won't save to database with Nestjs and TypeOrm (querying works)

Tags:

typeorm

nestjs

When I post a request, it doesn't save my entity to the database and doesn't report any errors or warnings.

Controller:

@Controller('recipes')

export class RecipesController {
  constructor(private readonly recipeService: RecipesService) {}
  @Get()
  async findAll(): Promise<Recipe[]> {
    return this.recipeService.findAll();
  }

  @Post()
  async create(@Body() createRecipeDto: Recipe) {
    this.recipeService.create(createRecipeDto);
  }
}

Service:

@Injectable()
export class RecipesService {
    constructor(@InjectRepository(Recipe) private readonly recipeRepository: Repository<Recipe>) {}

    async create(recipe: Recipe) {
        const d = await this.recipeRepository.create(recipe);
        console.log("d:", d);
    }

    async findAll() {
        return await this.recipeRepository.find();
    }
}

Entity:

@Entity()
export class Recipe {
  @PrimaryGeneratedColumn()
  id: number;

  //   @IsString()
  @Column()
  name: string;

  //   @IsString()
  @Column('text')
  description?: string;

  //   @IsString()
  @Column()
  image: string;

  //   @IsArray()
  ingredients: string[];

  //   @IsArray()
  instructions: string[];

  //   @IsString()
  @Column()
  prepTime?: string;

  //   @IsString()
  @Column()
  cookTime?: string;

  //   @IsString()
  @Column()
  yield?: string;

  //   @IsNumber()
  @Column('int')
  rating?: number;

  //   @IsArray()
  keywords?: string[];

  //   @IsArray()
  categories: string[];

  //   @IsString()
  @Column()
  cuisine?: string;

  //   @IsBoolean()
  @Column('boolean')
  draft?: boolean;
}

My request using Postman:

curl -X POST \
  http://localhost:3000/recipes \
  -H 'Content-Type: application/json' \
  -H 'Postman-Token: f23b5d42-1c40-4dae-b9b8-b32b733f38b4' \
  -H 'cache-control: no-cache' \
  -d '{
    "name":"recipe5",
    "description": "desc",
    "image": "http://..",
    "ingredients": ["-"],
    "instructions": ["1"],
    "prepTime": "1:20",
    "cookTime": "1:00",
    "yield": "8 servings",
    "rating": 4,
    "keywords": ["1"],
    "categories": ["cat1", "cat2"],
    "cuisine": "American",
    "draft": false
}'

It returns 201. My GET call only returns the entry I created manually.

like image 819
Gezim Avatar asked Dec 14 '22 12:12

Gezim


1 Answers

I found the issue!

TypeOrm's Repository.create doesn't actually save the entity to storage. To do that you have to call Repository.save.

This change in my service fixed my issue:

From:

const d = await this.recipeRepository.create(recipe);

to:

const d = await this.recipeRepository.save(recipe);
like image 77
Gezim Avatar answered Dec 31 '22 08:12

Gezim