preface

A framework discovered yesterday, which is billed as the Nodejs version of Spring (Java).

Development mode has ng6 both visual sense, which has ng experience for partners, inexplicable friendly..

It is suitable for tasting new products. Currently there is 1W+ STAR, and I think version 6 will be more stable.

This series will be based on the development progress of a real project, climbing a pit while hydrology;

website | NestJS Iteration Plan (roadmap)

  • 2018-12-7: Mysql 8 link report authentication problem

    The remote database is 5.7, backed up and switched to mysql8, because mysql8 has upgraded its security mechanism and can not connect directly as before.

    We need to modify it to support it

    
    # Login/switch database/update our password/refresh permissions with a new mechanism
    -> mysql -u root
    -> use mysql
    -> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '123456';
    -> flush privileges;
    
    Copy the code

rendering

failure

There are several reasons for this failure;

  • The configuration information of the database is inconsistent with the actual database data to be linked (e.g. database name, e.g. username and password).
  • The port for tunnel forwarding is occupied by other local services, such as mysql locally started (default 3306).
    • Either change the port mapping or shut down the local database
  • mysql 8+You need to modify the privilege authentication
  • tsGrammar mistakes

successful

code

db.ts(src/config)

Tip: If you want to use __dirname, make sure the configuration file is in the root directory, otherwise use a relative path, otherwise you won’t find the entity

Synchronize is synchronization to a database, for example, to build a table (depending on the entity)


import { join } from 'path';
const EntityRecursivePath = join('.. '.'/**/*.entity{.ts,.js}');
export const MySqlConfig: any = {
  type: 'mysql',
  host: 'localhost',
  port: 3306,
  username: 'root',
  password: '! =basestagging**',
  database: 'shengxi_v2',
  entities: [EntityRecursivePath],
  synchronize: true};Copy the code

app.module.ts

The UsersModule contains the associated services and entities


import { Module, NestModule, MiddlewareFunction } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';

// User module, register, login, update personal information
import { UsersModule } from './modules/users/users.module';

// Database ORM
import { TypeOrmModule } from '@nestjs/typeorm';
import { MySqlConfig } from './config/db';

@Module({
  imports: [TypeOrmModule.forRoot(MySqlConfig), UsersModule],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule implements NestModule {
  // Consumer can be attached to middleware or something
  configure(consumer: MiddlewareFunction): void {
    consumer
      .apply(null)
      .with('AppModule')
      .forRoutes('/'); }}Copy the code

users.entity.ts


import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';

// Entity decorator provides an option to configure the associated table name, engine, etc
// The class name is the table name

@Entity({
  name: 'sx_admin',})export class Users {
  @PrimaryGeneratedColumn() id: number;

  / / user name
  @Column('varchar', { length: 100 })
  admin_name: string;

  // User password
  @Column('varchar', { length: 255 }) admin_passwd: string;

  // Create time
  @Column('timestamp') created_at: number;
  // Update time
  @Column('timestamp') updated_at: number;
  // Whether to enable it
  @Column('int') admin_status: number;
}


Copy the code

The remaining position is to inject the entity and ORM Repository into the Services;

Then go to controller and inject the service call… It returns a Promise

Tips and warm tips

SSH Tunnel Forwarding (SSH Tunnel)

Remote database we generally do not expose external ports directly connected, security risks are too high;

Generally, the SSH tunnel (a common access mode) is used.

Log in to the authentication server using SSH and then forward the local port to the remote port

  • sshCommand forwarding

SSH command explanation (official manual): English, write very detailed;

We mainly used the following parameters

-l: indicates port forwarding

-c: compresses and transmits data

-f: background running

-n: the remote command is not executed

conventionalalias

# This command will run in the background
alias mstunnel=ssh -L 3306:localhost:3306  [email protected] -NCf

Replace -l with -r for remote transfer
Copy the code

parameter-passingalias

Shell aliases do not support passing arguments. You can only pass them as function and then assign values to alias

You can set a number of placeholders, successively increasing (such as port, domain name into external incoming what, depending on your preferences)


# ssh tunnel
function sst(){
  ssh -L 3306:localhost:3306  root@The $1 -NCf
}
alias sst=sst

Copy the code

Closing a session (SSH Tunnel)

Step by step depends on lsof,kill

  • Find the corresponding process PID,lsof -i tcp:22Query who is using port 22,ssh tunnelThe default gotcp)
  • kill -9 pid-9 terminates the process

If want one pace reachs the designated position, will together with the help of a few commands, awk, xargs and pipe (|)

# means
Select * from TCP where port 22 is used
Print the second column of the second row (the first row is the column name)
# stdin to arguments to kill
lsof -i tcp:22 | awk 'NR==2 { print $2}' |xargs   kill9 -# can also be written as an expression
kill -9 $(lsof -i tcp:22 | awk 'NR==2 { print $2}')


To shut down multiple processes referencing this port, NR! If the value is 1, kill can kill multiple processes
Use function to pass aliases.


Copy the code

If SSH is not configured to send periodic signals, the session is automatically stopped after a period of time (packet_write_wait:).

At this point we can either configure or we can rewrite the alias and use -o ServerAliveInterval=60 to keep the connection

ssh -o ServerAliveInterval=60 -L  3306:localhost:3306  [email protected] -NCf
Copy the code

If you go IPV6, take -6

  • NPM module posture

You can install SSH2 and link the database after the Promise is successful.

This is not considered, because the actual server is directly connected to the internal tunnel, we also use more in the development process

conclusion

Grammar to escape

  • If usejsfile

For the current version, we still need to consider the commonJS notation.

I have isolated the configuration file of the database link and cannot use export default

You can’t import with… (REST) means of decoupling. Otherwise, syntax errors will be reported

  • tsfile

Feel free to use the ES6+ syntax

If there is something wrong, please leave a message and correct it in time. Thank you for reading