Coder Social home page Coder Social logo

tony133 / nestjs-mysql Goto Github PK

View Code? Open in Web Editor NEW
13.0 4.0 3.0 2.11 MB

Mysql module for Nest framework (node.js) ๐Ÿ˜ป

License: MIT License

JavaScript 3.08% Shell 0.44% TypeScript 96.49%
javascript mysql mysql2 nestjs-mysql typescript nest-mysql nest-module nestjs nest

nestjs-mysql's Introduction

Nest Logo

A progressive Node.js framework for building efficient and scalable server-side applications.

NPM Version Package License NPM Downloads CircleCI Coverage Discord Backers on Open Collective Sponsors on Open Collective Support us

Description

MySQL module for Nest framework (node.js) ๐Ÿ˜ป

Installation

First install the module via yarn or npm or pnpm and do not forget to install the driver package as well:

    $ npm i --save nest-mysql mysql2

or

    $ yarn add nest-mysql mysql2

or

    $ pnpm add nest-mysql mysql2

Table of Contents

Usage

MySqlModule

MySqlModule is the primary entry point for this package and can be used synchronously

@Module({
  imports: [
    MysqlModule.forRoot({
        host: 'localhost',
        database: 'test2',
        password: 'root',
        user: 'root',
        port: 3306,      
    }),
  ],
})

or asynchronously

@Module({
  imports: [
    MysqlModule.forRootAsync({
      useFactory: () => ({
        host: 'localhost',
        database: 'test',
        password: 'root',
        user: 'root',
        port: 3306,      
      }),
    }),
  ],
})

Example of use

UsersService:

import { Injectable } from '@nestjs/common';
import { InjectClient } from 'nest-mysql';
import { Connection } from 'mysql2';
import { User } from '../interfaces/user.interface';

@Injectable()
export class UsersService {
  constructor(@InjectClient() private readonly connection: Connection) {}

  async findAll(): Promise<User[]> {
    const users = await this.connection.query('SELECT * FROM users');
    const results = Object.assign([{}], users[0]);

    return results;
  }
}

UsersController:

import { Controller, Get } from '@nestjs/common';
import { UsersService } from './users.service';
import { User } from '../interfaces/user.interface';

@Controller()
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @Get()
  async getAllUsers(): Promise<User[]> {
    return await this.usersService.findAll();
  }
}

Multi Connections Database

@Module({
  imports: [
    MysqlModule.forRootAsync(
      {
        useFactory: () => ({
          host: 'localhost',
          database: 'test1',
          password: 'root',
          user: 'root',
          port: 3306,      
        }),
      },
      'db1Connection',
    ),
    MysqlModule.forRootAsync(
      {
        useFactory: () => ({
          host: 'localhost',
          database: 'test2',
          password: 'root',
          user: 'root',
          port: 3307,      
        }),
      },
      'db2Connection',
    ),
  ],
  controllers: [],
  providers: [],
})
export class AppModule {}

Usage example with Multi Connection

PostService:

import { Pool } from 'mysql2';
import { InjectConnection } from 'nest-mysql';
import { CreatePostDto } from './dto/create-post.dto';
import { Post } from '../interfaces/post.interface';

@Injectable()
export class PostService {
  constructor(
    @InjectConnection('db2Connection')
    private dbConnection: Pool,
  ) {}

  public async findAll(): Promise<Post[]> {
    const posts = await this.dbConnection.query('SELECT * FROM posts');
    const results = Object.assign([{}], posts[0]);

    return results;
  }

  public async create(createPostDto: CreatePostDto): Promise<Post[]> {
    try {
      const post = await this.dbConnection.query(
        'INSERT INTO posts (title, description) VALUES (?, ?)',
        [createPostDto.title, createPostDto.description],
      );
      return post;
    } catch (err) {
      throw new HttpException(err, HttpStatus.BAD_REQUEST);
    }
  }
}

UsersService:

import { Pool } from 'mysql2';
import { InjectConnection } from 'nest-mysql';
import { CreateUserDto } from './dto/create-user.dto';
import { User } from '../interfaces/user.interface';

@Injectable()
export class UsersService {
  constructor(
    @InjectConnection('db1Connection')
    private dbConnection: Pool,
  ) {}

  public async findAll(): Promise<User[]> {
    const users = await this.dbConnection.query('SELECT * FROM users');
    const results = Object.assign([{}], users[0]);

    return results;
  }

  public async create(createUserDto: CreateUserDto): Promise<User[]> {
    try {
      const user = await this.dbConnection.query(
        'INSERT INTO users (firstName, lastName)  VALUES (?, ?)',
        [createUserDto.firstName, createUserDto.lastName],
      );
      return user;
    } catch (err) {
      throw new HttpException(err, HttpStatus.BAD_REQUEST);
    }
  }
}

For more information on node-mysql see here

Contribute

Feel free to help this library, I'm quite busy with also another Nestjs packages, but the community will appreciate the effort of improving this library. Make sure you follow the guidelines

Stay in touch

License

MIT licensed

nestjs-mysql's People

Contributors

dependabot[bot] avatar renovate[bot] avatar tony133 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

nestjs-mysql's Issues

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/codeql-analysis.yml
  • actions/checkout v4
  • github/codeql-action v3
  • github/codeql-action v3
  • github/codeql-action v3
.github/workflows/nodejs-environment.yml
  • actions/checkout v4
  • actions/setup-node v4
  • actions/checkout v4
  • actions/setup-node v4
  • actions/setup-node v4
npm
package.json
  • @commitlint/cli 19.3.0
  • @commitlint/config-angular 19.3.0
  • @nestjs/common 10.3.10
  • @nestjs/config 3.2.3
  • @nestjs/core 10.3.10
  • @nestjs/platform-fastify ^10.3.7
  • @nestjs/testing 10.3.10
  • @types/jest 29.5.12
  • @types/node 20.14.13
  • @types/supertest 6.0.2
  • @typescript-eslint/eslint-plugin 7.18.0
  • @typescript-eslint/parser 7.18.0
  • eslint 8.57.0
  • eslint-config-prettier 9.1.0
  • eslint-plugin-import 2.29.1
  • husky 9.1.4
  • jest 29.7.0
  • mysql2 3.11.0
  • prettier 3.3.3
  • reflect-metadata 0.2.2
  • release-it 17.6.0
  • rxjs 7.8.1
  • supertest ^7.0.0
  • ts-jest 29.2.4
  • ts-node 10.9.2
  • tsconfig-paths 4.2.0
  • typescript 5.5.4
  • @nestjs/common ^7.0.0 || ^8.0.0 || ^9.0.0 || ^10.0.0
  • @nestjs/core ^7.0.0 || ^8.0.0 || ^9.0.0 || ^10.0.0
  • mysql2 ^2.3.3 || ^3.0.0
  • reflect-metadata ^0.1.13 || ^0.2.0
  • rxjs ^6.6.3 || ^7.2.0

  • Check this box to trigger a request for Renovate to run again on this repository

Calling stored procedures with variables and then selecting causes parsing errors from MySQL side?

I used a simple calcUserRep procedure with user_id In parameter and reputation Out parameter.

The code in service.ts is also very straightforward, it takes string from dto and runs it as query:

async postSql(dto: SqlPost): Promise<string> {
    const data = await this.connection.query(dto.query);
    return JSON.stringify(Object.assign([{}], data));
  }

However, a single query with CALL and SELECT operators throws error in MySQL:
The query: CALL calcUserRep(1, @rep); SELECT @rep;
The error: Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT @rep' at line 1
Inside MySQL Workbench under the same user the query works perfectly.

I also tried running two separate this.connection.query() methods, but seems like MySQL doesn't remember variables between the two.

Is this made by design or this is a bug? And how I can workaround this?

My software: nestjs-mysql 0.0.14, nest 10.3.8

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.