$ npm install sqlite3
$ npm install typeorm
$ npm install @nestjs/typeorm
ormconfig.json
{ "type": "sqlite", "database": "data/database.sqlite3", "entities": [ "dist/entities/**/*.entity.js" ], "migrations": [ "dist/migrations/**/*.js" ] }
app.moudle.ts
import { Module } from '@nestjs/common'; import { AppController } from './app.controller'; import { AppService } from './app.service'; import { TypeOrmModule } from '@nestjs/typeorm'; @Module({ imports: [TypeOrmModule.forRoot()], controllers: [AppController], providers: [AppService], }) export class AppModule {}
src/entities/mydata.entity.ts
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm'; @Entity() export class Mydata { @PrimaryGeneratedColumn() id: number @Column({length: 20}) name: string @Column({length: 100}) pass: string @Column({length: 100, nullable:true}) mail: string @Column() age:number }
### migration
$ npm run build
$ npx typeorm migration:generate -n mydata_migration -d src/migrations
$ npm run build
$ npx typeorm migration:run
$ npx nest generate module mydata
$ npx nest generate service mydata
$ npx nest generate controller mydata
mydata.module.ts
import { Module } from '@nestjs/common'; import { MydataService } from './mydata.service'; import { MydataController } from './mydata.controller'; import { Mydata } from '../entities/mydata.entity' import { TypeOrmModule } from '@nestjs/typeorm' @Module({ imports: [TypeOrmModule.forFeature([Mydata])], providers: [MydataService], controllers: [MydataController] }) export class MydataModule {}
app.module.ts
import { Module } from '@nestjs/common'; import { AppController } from './app.controller'; import { AppService } from './app.service'; import { TypeOrmModule } from '@nestjs/typeorm'; import { MydataModule } from './mydata/mydata.module'; @Module({ imports: [TypeOrmModule.forRoot(), MydataModule], controllers: [AppController], providers: [AppService], }) export class AppModule {}
mydata.service.ts
import { Injectable } from '@nestjs/common'; import { Repository } from 'typeorm' import { InjectRepository } from '@nestjs/typeorm' import { Mydata } from '../entities/mydata.entity' @Injectable() export class MydataService { constructor( @InjectRepository(Mydata) private readonly mydataRepository: Repository<Mydata> ) {} getAll():Promise<Mydata[]>{ return this.mydataRepository.find() } }
mydata.controller.ts
import { Controller } from '@nestjs/common'; import { MydataService } from './mydata.service' @Controller('mydata') export class MydataController { constructor(private readonly mydataService: MydataService){} @Get('/') root():Promise<any[]>{ return this.mydataService.getAll() } }
…