preface

For many front-end players, the first time you connect to SQL using Node.js and use it, you will find it tedious and even difficult. Don’t be afraid! TypeORM helps you solve all your problems about operating SQL!

This article is for amway purposes only and does not describe TypeORM usage in detail. Please visit
websiteor
Gitee introduction

1. Look at the effect first

  • increase

    Const insertOne = async (name: string,memo:string) => {try {let tag = new tag (); tag.name = name; tag.memo = memo; await getConnection().manager.save(tag); return true; } catch (err) { return err; }};Copy the code
  • delete

    Const deleteOne = async (entity, id: const deleteOne = async (entity, id: number) => { try { const repository = getRepository(entity); await repository.delete(id); return true; } catch (err) { return err; }};Copy the code
  • change

    Const updateOne = async (entity, id: number, params:) const updateOne = async (entity, id: number, params:) object) => { try { const repository = getRepository(entity); let result = await repository.update(id, params); return true ; } catch (err) { return err; }};Copy the code
  • check

    Const findOne = async (entity, id:number) => {try {const repository = getRepository(entity); const findOne = async (entity, id:number) => {try {const repository = getRepository(entity); let result = await repository.findOne(id); return result; } catch (err) { return err; }}; Const findAll = async (entity, relations:) const findAll = async (entity, relations:) string[] = null) => { try { const repository = getRepository(entity); Return await repository.find({relations, order: {createTime createTime: "DESC"}}); } catch (err) { return err; }}; Export const $_findPaginate = async (entity, pageIndex, pageSize, relations:) string[] = null ) => { try { const repository = getRepository(entity); Return await repository. FindAndCount ({skip: (pageIndex - 1) * pageSize,// skip: (pageIndex - 1) * pageSize,// { createTime: "DESC" } }); } catch (err) { return err; }};Copy the code

Very simple!! Very pure JS writing!! And it is very easy to use encapsulation, except the first method listed above (for personal project reasons not encapsulation), I use the other encapsulation, do not write over and over again SQL concatenation string, just need to call the method can be ~

2. What is TypeORM

  • First, ORM

    Relational Mapping (ORM)The framework is described using metadataObject and relational mappingMetadata is usually in XML format and stored in a special object-mapping file.
  • It means we can passManipulate objects to manipulate the database
  • whileTypeORMAnd, of course, it’s one for Node.jsORMThe framework?

3. How to operate a database by manipulating objects

We must first define a mapping that tells the framework which database we want to change when we operate on this object, otherwise we will change it. So how can this relationship be determined? TypeORM uses the concept of an entity (as I emphasized in my comments in Part 1), which is a class that maps to database tables (or collections when using MongoDB), as shown below

import { Entity, Column, PrimaryGeneratedColumn,CreateDateColumn,UpdateDateColumn } from "typeorm"; // The column used below, don't forget to import oh // a photo entity, @entity () export class Photo {@primaryGeneratedColumn () // an autoincrement and primary key ID: number; @column ({length: 100}) // VARCHAR name: string; @column ("text") // The length is unlimited, the corresponding database is text type description: string; @column () // Do not set anything!! The default setting is NOT NULL! The value of this field must be set when inserting filename: string; @column({default:" default "}) // Memo :string @column("double") // Double type views: number; @Column() isPublished: boolean; @createDatecolumn () // This column is automatically assigned to the current time when it is inserted, CreateTime :string @updateDatecolumn () // This column will be assigned to the current time when inserting and updating updateTime:string @onetomany, @manytomany), please study in the two websites given above. The words in the blog are limited and will not be expanded in detail.Copy the code

Obviously, after we write the above definition, the database will generate a table Photo, and we will write a SQL statement to create the table in JS!

id name description fileName memo views isPublished createTime updateTime
** ** ** ** ** ** ** ** **

4. Operating entities (operating databases)

After we set up the project and created the entity, we can operate the database by manipulating the entity! There are two ways to manipulate entities

  • Use the Entity ManagerEntityManager
  • Use the repositoryRepository

What’s the difference between these two things? Emm, no different. An EntityManager is like a collection of all entity repositories in a single location. Repository is similar to EntityManager, but the Repository operation is limited to entities, so you need to pass in entities to create a Repository! The following

import "reflect-metadata";
import { getManager,getRepository } from "typeorm";
import {Photo} from "./entity/Photo"

let manager = getManager();
let repository = getRepository(Photo);Copy the code

Then you can use these two gadgets to do whatever you want!

After the language

This article only briefly introduces the use of TypeORM, please check the official website for more details. The official document is written in more detail, although it is in English, but it is not difficult to right translate it into Chinese. Have a good life