课程名称:NestJS 入门到实战 前端必学服务端新趋势
课程章节: 第1章
课程讲师:Brian
课程内容
热加载
https://docs.nestjs.com/recipes/hot-reload
npm i --save-dev webpack-node-externals run-script-webpack-plugin webpack
创建 webpack-hmr.config.js
const nodeExternals = require('webpack-node-externals');
const { RunScriptWebpackPlugin } = require('run-script-webpack-plugin');
module.exports = function (options, webpack) {
return {
...options,
entry: ['webpack/hot/poll?100', options.entry],
externals: [
nodeExternals({
allowlist: ['webpack/hot/poll?100'],
}),
],
plugins: [
...options.plugins,
new webpack.HotModuleReplacementPlugin(),
new webpack.WatchIgnorePlugin({
paths: [/\.js$/, /\.d\.ts$/],
}),
new RunScriptWebpackPlugin({ name: options.output.filename, autoRestart: false }),
],
};
};在 main.ts 添加
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
// 下面这个
if (module.hot) {
module.hot.accept();
module.hot.dispose(() => app.close());
}
}
bootstrap();此时 hot会报错 需要安装
npm i -D @types/webpack-env
然后设置
"start:dev": "nest build --webpack --webpackPath webpack-hmr.config.js --watch"
执行 npm run start:debug 可以进行断点调试
typeorm
TypeOrm
typeorm是个mysql的对象关系映射器,是用typescript编写的,在nest下运行非常好。
使用typeorm,必须先安装必须的依赖关系:
npm install @nestjs/typeorm typeorm mysql -S
forRoot() 方法接受来自 TypeOrm 包的 createConnection() 的相同配置对象,也可以创建 ormconfig.json 配置文件配置连接参数。
@Entity() 定义一个新类来创建一个实体
@PrimaryGeneratedColumn() 自动递增的主键
@Column() 列类型
// typescript -> 数据库 关联关系 Mapping
@OneToMany(() => Logs, (logs) => logs.user)
logs: Logs[];
@Injectable
将类定义为提供者
@InjectRepository() 另一方面是 @Inject() 的扩展,它采用当前传递的实体/存储库并使用一些逻辑来创建新的注入令牌.通常,此逻辑是 Repository 有时会添加 connection.此令牌与从 TypeormModule.forFeature() 为同一实体创建的令牌匹配.(旁注:如果传递的实体是存储库,则令牌只是 带有可选连接(如果不是默认连接).
@Injectable()
export class UserService {
constructor(
@InjectRepository(User) private readonly userRepository:
Repository<User>
){}
findAll(){
return this.userRepository.find()
}
find(username: string) {
return this.userRepository.findOne({where: {username}})
}
async create(user: User) {
const userTmp = await this.userRepository.create(user)
return this.userRepository.save(userTmp)
}
update(id: number, user:Partial<User>) {
return this.userRepository.update(id, user)
}
remove(id:number){
return this.userRepository.delete(id)
}
}共同學習,寫下你的評論
評論加載中...
作者其他優質文章




