这是我参与11月更文挑战的第18天,活动详情查看:2021最后一次更文挑战
数据库
typeorm
首先要安装依赖
npm install --save @nestjs/typeorm typeorm mysql2
然后再app.module.ts里面引入
引入方式
方式1
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'mysql',
host: 'localhost',
port: 3306,
username: 'root',
password: 'root',
database: 'test',
entities: [],
synchronize: true,
}),
],
})
export class AppModule {}
复制代码
方式2
根目录新建ormconfig.json,这样就不必把配置对象传给forRoot
{
"type": "mysql",
"host": "localhost",
"port": 3306,
"username": "root",
"password": "root",
"database": "test",
"entities": ["dist/**/*.entity{.ts,.js}"],
"synchronize": true
}
复制代码
这里有个地方需要注释的是
静态全局路径(例如 dist//*.entity{ .ts,.js} )不适用于 Webpack 热重载。**
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
@Module({
imports: [TypeOrmModule.forRoot()],
})
export class AppModule {}
复制代码
prisma
- npm install prisma --save-dev
npx prisma init
此命令创建一个prisma包含以下内容的新目录:
- schema.prisma: 指定您的数据库连接并包含数据库架构
- .env:一个dotenv文件,通常用于将您的数据库凭据存储在一组环境变量中
datasource db {
provider = "sqlite" // 数据库类型
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
// model 是定义你数据模型,这里只是举个例子
model User {
id Int @default(autoincrement()) @id
email String @unique
name String?
posts Post[]
}
model Post {
id Int @default(autoincrement()) @id
title String
content String?
published Boolean? @default(false)
author User? @relation(fields: [authorId], references: [id])
authorId Int?
}
复制代码
// .env文件
DATABASE_URL="mysql://root:password@localhost:3306/tablename"
复制代码
用 Prisma 模型后,您可以生成 SQL 迁移文件并针对数据库运行它们。在终端中运行以下命令:
npx prisma migrate dev --name init
安装并生成 Prisma 客户端#
npm install @prisma/client
创建prisma.service.ts文件,并添加其下代码
import { INestApplication, Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';
@Injectable()
export class PrismaService extends PrismaClient
implements OnModuleInit {
async onModuleInit() {
await this.$connect();
}
async enableShutdownHooks(app: INestApplication) {
this.$on('beforeExit', async () => {
await app.close();
});
}
}
复制代码
该onModuleInit是可选的-如果你离开它,Prisma的会懒洋洋地连接在其第一次调用数据库。我们不理会onModuleDestroy,因为 Prisma 有它自己的关闭钩子,它会破坏连接。有关更多信息enableShutdownHooks,请参阅问题enableShutdownHooks
接下来根据你情况编写service代码
例如,创建一个名为的新文件user.service.ts并向其中添加以下代码:
import { Injectable } from '@nestjs/common';
import { PrismaService } from './prisma.service';
import {
User,
Prisma
} from '@prisma/client';
@Injectable()
export class UserService {
constructor(private prisma: PrismaService) {}
async user(userWhereUniqueInput: Prisma.UserWhereUniqueInput): Promise<User | null> {
return this.prisma.user.findUnique({
where: userWhereUniqueInput,
});
}
async users(params: {
skip?: number;
take?: number;
cursor?: Prisma.UserWhereUniqueInput;
where?: Prisma.UserWhereInput;
orderBy?: Prisma.UserOrderByInput;
}): Promise<User[]> {
const { skip, take, cursor, where, orderBy } = params;
return this.prisma.user.findMany({
skip,
take,
cursor,
where,
orderBy,
});
}
async createUser(data: Prisma.UserCreateInput): Promise<User> {
return this.prisma.user.create({
data,
});
}
async updateUser(params: {
where: Prisma.UserWhereUniqueInput;
data: Prisma.UserUpdateInput;
}): Promise<User> {
const { where, data } = params;
return this.prisma.user.update({
data,
where,
});
}
async deleteUser(where: Prisma.UserWhereUniqueInput): Promise<User> {
return this.prisma.user.delete({
where,
});
}
}
复制代码
然后再controller里面调用即可