发布请求时,它不会将我的实体保存到数据库中,也不会报告任何错误或警告。
控制器:
@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);
}
}
服务:
@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()
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;
}
我使用邮递员的请求
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
}'
返回201。 我的GET调用仅返回我手动创建的条目。
答案 0 :(得分:3)
我发现了问题!
TypeOrm的Repository.create实际上并未将实体保存到存储中。为此,您必须致电Repository.save
。
此服务更改解决了我的问题:
发件人:
const d = await this.recipeRepository.create(recipe);
收件人:
const d = await this.recipeRepository.save(recipe);