nest.js + TypeORM + PostgreSQL
议程:
使用 Nest.JS 构建一个 rest api。
后端架构:
[](https://res.cloudinary.com/practicaldev/image/fetch/s--rzM6d1Sw--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev- to-uploads.s3.amazonaws.com/i/ttobvwwzubdvz8kx8xdh.png)
使用的技术:
-
Node.js --- 平台 。
-
NestJS --- 服务器 。
-
TypeORM --- orm 。
-
PostgreSQL --- 数据库 。
什么是 Node.js :
[](https://res.cloudinary.com/practicaldev/image/fetch/s--PL5JRGJV--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to- uploads.s3.amazonaws.com/i/xqmcjh8b48rgdbnottw3.jpg)
NodeJS 是一个 Javascript 运行时(包含运行 javascript 的所有内容),用于构建服务器端应用程序。
什么是 NestJs :
[](https://res.cloudinary.com/practicaldev/image/fetch/s--Aeppe_wK--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://images.ctfassets.net /1es3ne0caaid/3XE9gJHMZakYUy0gKAsQ2M/986b5ddd64ea0ff1a344cde15b442a40/nest-logo.png)
Nest 是一个用于构建高效且可扩展的 NodeJs 服务器端应用程序的框架。
什么是TypeORM:
TypeORM 是一个对象关系映射器,其任务基本上是使用面向对象编程生成对象,虚拟映射到数据库。
什么是PostgreSQL:
PostgreSQL 是用于构建可扩展和高可用性应用程序的对象关系数据库管理系统。
- 安装@nestjs/cli 包。并创建一个新项目
$ npm i -g @nestjs/cli
$ nest new project-name
进入全屏模式 退出全屏模式
在一个普通的nestJS项目中:
-
main.ts 包含 bootstraping 代码。
-
.spec 文件包含测试文件。
-
nestjs 使用模块来组织应用程序结构。
-
控制器包含应用程序的路由规则。
-
服务包含应用程序的业务逻辑。
$ npm run start
curl localhost:3000
进入全屏模式 退出全屏模式
设置数据库:
$sudo -U postgres
$psql
$create database conduit
$create user conduit with encrypted password conduit
$grant all privileges on database conduit to conduit
进入全屏模式 退出全屏模式
- 文件结构:
src
|- app.controller.ts
|- app.controller.spec.ts
|- app.module.ts
|- app.service.ts
|- main.ts
进入全屏模式 退出全屏模式
创建一个connection
到数据库。
$ touch app.dbconfig.ts
import {TypeOrmModuleOptions} from "typeorm";
export function createTypeOrmProdConfig(): TypeOrmModuleOptions{
return({
type: "postgres",
username: "conduit",
password: "conduit",
database: "conduit"
entities: [join(__dirname, '**', '*.entity.{ts, js}')],
synchronize: true,
logging: true,
logger: "advanced-console",
});
}
进入全屏模式 退出全屏模式
- 接下来我们必须为我们的数据库创建
entities
。并将个体实体放到createConnection
函数中的实体数组中。
$ mkdir src/entities
$cd entities
$nano Article.ts
@Entity()
export class Article {
@PrimaryColumn({length: 40})
slug: string
@Column({length: 40})
title?: string
@Column({length: 100, nullable:true})
description: string
@Column({type: 'text'})
body: string
进入全屏模式 退出全屏模式
为文章路由生成模块、服务、控制器:
nest g mo article module
nest g co article module
nest g s article module
进入全屏模式 退出全屏模式
$ cd module/article
$ nano module.article.ts
imports : [Typeormmodue.forFeature([Article])]
- 导航到文章服务文件。
@InjectRepository(Article) private readonly articleRepo: Repository<Article>,
async getAllArticles(): Promise<Article[]> {
return await this.articleRepo.find();
}
进入全屏模式 退出全屏模式
- 导航到物品控制器文件。
constructor(private readonly articlesService: ArticlesService) {}
@Get()
async getAllArticles(): Promise<Article[]> {
return await this.articlesService.getAllArticles();
}
进入全屏模式 退出全屏模式
然后最后在应用程序根模块中。
imports :[TypeOrmModule.forroot([Article])]
$npm start
谢谢你的阅读🔥
更多推荐
所有评论(0)