nestjs
Provides comprehensive NestJS framework patterns with Drizzle ORM integration for building scalable server-side applications. Generates REST/GraphQL…
它会碰到什么
扫了多少8 个文本文件,112 KB
它会碰到什么读凭据
命中总数9 处
命中统计严重 9 · 高 0 · 中 0 · 低 0
逐条看命中(9 条严重或高危)
- 严重
references/drizzle-reference.md:471cred-paths├ 📜 .env
- 严重
references/drizzle-reference.md:538cred-pathsDefines the environment variable for the SQLite Cloud database connection string in the .env file.
- 严重
references/drizzle-reference.md:1231cred-pathsDefines the database connection URL in a `.env` file. For Vercel Postgres, it's crucial to name the variable `POSTGRES_URL`. The value can be obtained from the
- 严重
references/drizzle-reference.md:1239cred-paths### Database Connection URL in .env
- 严重
references/drizzle-reference.md:1243cred-pathsSpecifies the database connection string in the .env file, which Drizzle ORM will use to connect to the database.
- 严重
references/drizzle-reference.md:1724cred-pathsDefines the database file name for Bun:SQLite in the .env file. This variable is used to configure the database connection string for Drizzle ORM.
- 严重
references/reference.md:1389cred-pathsenvFilePath: ['.env.local', '.env'],
- 严重
references/reference.md:1389cred-pathsenvFilePath: ['.env.local', '.env'],
- 严重
references/workflow-optimization.md:21cred-paths2. **Database Setup**: `.env → drizzle.config.ts → schema → migrations → database service → repositories`
这一栏是扫描器报的事实,不是结论。命中多不等于有毒(安全工具、规则库、示例脚本本来就会包含危险写法),命中少也不等于干净。它和你手上的凭据、文件、网络有什么关系,需要你自己看。
技能内容
NestJS Framework with Drizzle ORM
Overview
Provides NestJS patterns with Drizzle ORM for building production-ready server-side applications. Covers CRUD modules, JWT authentication, database operations, migrations, testing, microservices, and GraphQL integration.
When to Use
- Building REST APIs or GraphQL servers with NestJS
- Setting up authentication and authorization with JWT
- Implementing database operations with Drizzle ORM
- Creating microservices with TCP/Redis transport
- Writing unit and integration tests
- Running database migrations with drizzle-kit
Instructions
- Install dependencies:
npm i drizzle-orm pg && npm i -D drizzle-kit tsx - Define schema: Create
src/db/schema.tswith Drizzle table definitions - Create DatabaseService: Inject Drizzle client as a NestJS provider
- Build CRUD module: Controller → Service → Repository pattern
- Add validation: Use class-validator DTOs with ValidationPipe
- Implement guards: Create JWT/Roles guards for route protection
- Write tests: Use
@nestjs/testingwith mocked repositories - Run migrations:
npx drizzle-kit generate→ Verify SQL →npx drizzle-kit migrate
Examples
Complete CRUD Module with Drizzle
// src/db/schema.ts
export const users = pgTable('users', {
id: serial('id').primaryKey(),
name: text('name').notNull(),
email: text('email').notNull().unique(),
createdAt: timestamp('created_at').defaultNow(),
});
// src/users/dto/create-user.dto.ts
export class CreateUserDto {
@IsString() @IsNotEmpty() name: string;
@IsEmail() email: string;
}
// src/users/user.repository.ts
@Injectable()
export class UserRepository {
constructor(private db: DatabaseService) {}
async findAll() {
return this.db.database.select().from(users);
}
async create(data: typeof users.$inferInsert) {
return this.db.database.insert(users).values(data).returning();
}
}
// src/users/users.service.ts
@Injectable()
export class UsersService {
constructor(private repo: UserRepository) {}
async create(dto: CreateUserDto) {
return this.repo.create(dto);
}
}
// src/users/users.controller.ts
@Controller('users')
export class UsersController {
constructor(private service: UsersService) {}
@Post()
create(@Body() dto: CreateUserDto) {
return this.service.create(dto);
}
}
// src/users/users.module.ts
@Module({
controllers: [UsersController],
providers: [UsersService, UserRepository, DatabaseService],
exports: [UsersService],
})
export class UsersModule {}
JWT Authentication Guard
@Injectable()
export class JwtAuthGuard implements CanActivate {
constructor(private jwtService: JwtService) {}
canActivate(context: ExecutionContext) {
const token = context.switchToHttp().getRequest()
.headers.authorization?.split(' ')[1];
if (!token) return false;
try {
const decoded = this.jwtService.verify(token);
context.switchToHttp().getRequest().user = decoded;
return true;
} catch {
return false;
}
}
}
Database Transactions
async transferFunds(fromId: number, toId: number, amount: number) {
return this.db.database.transaction(async (tx) => {
await tx.update(accounts)
.set({ balance: sql`${accounts.balance} - ${amount}` })
.where(eq(accounts.id, fromId));
await tx.update(accounts)
.set({ balance: sql`${accounts.balance} + ${amount}` })
.where(eq(accounts.id, toId));
});
}
Unit Testing with Mocks
describe('UsersService', () => {
let service: UsersService;
let repo: jest.Mocked<UserRepository>;
beforeEach(async () => {
const module = await Test.createTestingModule({
providers: [
UsersService,
{ provide: UserRepository, useValue: { findAll: jest.fn(), create: jest.fn() } },
],
}).compile();
service = module.get(UsersService);
repo = module.get(UserRepository);
});
it('should create user', async () => {
const dto = { name: 'John', email: 'john@example.com' };
repo.create.mockResolvedValue({ id: 1, ...dto, createdAt: new Date() });
expect(await service.create(dto)).toMatchObject(dto);
});
});
Constraints and Warnings
- DTOs required: Always use DTOs with class-validator, never accept raw objects
- Transactions: Keep transactions short; avoid nested transactions
- Guards order: JWT guard must run before Roles guard
- Environment variables: Never hardcode DATABASE_URL or JWT_SECRET
- Migrations: Run
drizzle-kit generateafter schema changes before deploying - Circular dependencies: Use
forwardRef()carefully; prefer module restructuring
Best Practices
- Validate all inputs with global
ValidationPipe - Use transactions for multi-table operations
- Document APIs with OpenAPI/Swagger decorators
References
Advanced patterns and detailed examples available in:
references/reference.md- Core patterns, guards, interceptors, microservices, GraphQLreferences/drizzle-reference.md- Drizzle ORM installation, configuration, queriesreferences/workflow-optimization.md- Development workflows, parallel execution strategies
想直接用这个技能?
本站把开放许可(MIT / Apache 等)的技能按仓库打包整理到网盘,点一下转存到你自己的网盘,不用一个个从 GitHub 拉。许可未声明的技能只给原始仓库链接,不打包。
它属于哪个仓库
星标★ 345
本站分层T2
该仓技能数119
原文件路径
plugins/developer-kit-typescript/skills/nestjs/SKILL.md