Nest.js + Typeorm: Basic use

Source: Internet
Author: User
Tags export class findone

Objective

The nest is a node. JS framework that is compatible with typescript and JavaScript. This article uses some of the basic modules of nest to build a simple Web backend curd application. Typeorm is a relatively mature object-relational mapper, written by Typescript. Nest and Typeorm, you can view the official documentation.

Project Building

Using the CLI to build project:

NPM i-g @nestjs/cli nest New Nest-app

This creates a Nest-app project that, when created, contains the following core files in the SRC folder:

Src├──app.controller.ts├──app.module.ts└──main.ts

Main.ts asks the project startup file, the default listener port 3000, the root module app.module.ts, the route instance app.controller.ts.

Now run the project by executing the following command:

NPM Run Start

After startup, enter localhost:3000 in the browser to see Hello World.

Use of Typeorm

Install Typeorm:

NPM Install--save @nestjs/typeorm typeorm MySQL

Typeorm supports a variety of databases, and this project uses MySQL.

Create entity employee and company, file directory:

Entities├──employee.entity.ts├──company.entity.ts

  

Import {Entity, Column, Primarygeneratedcolumn, Manytoone, jointable} from ' Typeorm './company.entity '@ Entity () Export class Employee {    @PrimaryGeneratedColumn ()    id:number    @Column ()    name:string    @ Column ()    age:number    @Column ()    address:string    true  })    @JoinTable ()    Company:company}

Company.entity.ts:

Import {Entity, Column, Primarygeneratedcolumn, onetomany} from ' Typeorm'./employee.entity '@Entity () Export class Company {    @PrimaryGeneratedColumn ()    id:number    @Column ()    name:string    = Employee, employee = employee.company)    employees:employee[]}

In the typeorm are all through the adorner to specify the object mapping relationship, this project entity currently uses only the primary key, data columns, a one-to-many relationship and other basic functions, in defining the relationship between entity objects, the relationship must be clear, this example uses CASCADE, Can be used to cascade delete CASCADE save operations. Note: cascading deletes and cascading saves take effect only at Save () and are not valid at insert ().

Create an employee module
Employee├──employee.controller.ts├──employee.module.ts└──employee.service.ts

Employee.service.ts:

Import {injectable} from ' @nestjs/common '; import {Employee} from‘.. /entities/employee.entity 'Import {injectrepository} from' @nestjs/typeorm '; import {Repository} from' Typeorm '; import {company} from‘.. /entities/company.entity '@Injectable () export class EmployeeService {constructor (@InjectRepository Employee) Private readonly Employeerep Ository:repository<Employee>{} root (): string {return' Hello world! '; } async Create (): Promise<string>{Let employee=NewEmployee (); Let Company=NewCompany (); Company.name= ' ASC '; Employee.Name= ' Novak '; Employee.age= 20; Employee.address= ' Shanghai '; Employee.company=Company ; return  This. Employeerepository.save (Employee). Then (res= {                return' Create Employee ... done '            })            .Catch(Err = {                returnerr}); } async FindOne (name:string): Promise<Employee> {        returnAwait This. Employeerepository.findone ({name:name}); }}
Import {Get, controller,param} from ' @nestjs/common '; import {EmployeeService} from './employee.service '; import {Emplo Yee} from ' entities/employee.entity ';
@Controller (' Employee ') export class Employeecontroller {constructor (private readonly EmployeeService: EmployeeService) {}
@Get () root (): string{Console.log (123) return this.employeeService.root ();
@Get (' findone/:name ') async FindOne (@Param () params):P romise<employee>{console.log (params.name); return This.employeeService.findOne (Params.name); }
@Get (' create ') async Create ():P romise<string>{console.log (' 1323 ') return This.employeeService.create ();}}

Employee.module.ts:

Import {Module} from ' @nestjs/common' @nestjs/typeorm './employee.controller'. Employee.service ". /entities/employee.entity '@Module ({    imports: [Typeormmodule.forfeature ([employee])],    providers: [ EmployeeService],    controllers: [Employeecontroller]}) Export class Employeemodule {  }
In Employee.module.ts, Typeormmodule.forfeature () is used to dynamically get the module object. The basic route configuration is used in Employee.controller.ts.
module injection, database connection information configuration

Inject the employee module in the root directory:

Import {Module} from ' @nestjs/common'./app.controller './app.service '@nestjs/typeorm './employee/employee.module '@Module ({  imports: [    typeormmodule.forroot (),    Employeemodule  ],  controllers: [AppController],  providers: [Appservice],}) Export class Appmodule {} 

As you can see, there are many ways to use Typeormmodule.forroot () in imports to dynamically return Typeormmodule,typeormmodule to connect to a database, you can use a configuration file, or you can Forroot () In the options parameter information, this example uses the configuration file to add the Ormconfig.json file in the SRC directory:

{    "type": "MySQL",    "host": "localhost",    "port": 3306,    " Username ":" root ",    " password ":" Root ",    " database ":" Nest-app ",    " Entities ": [" Src/**/**.entity{.ts,.js} "],    true  }

At this point a basic service program with employee creation and query functionality has been built, browser input: Localhost:3000/employee/create Look at the effect of it.

SOURCE GitHub

Welcome small partners to exchange more! ^_^

Nest.js + Typeorm: Basic use

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.