types / mysql2

Typings for https://github.com/sidorares/node-mysql2
ISC License
41 stars 23 forks source link

exec type for queries incorrect #54

Closed hvolschenk closed 2 years ago

hvolschenk commented 2 years ago

I am using exec to execute stored procedures, but the return type is not accurate.

Stored procedure:

DELIMITER //
CREATE PROCEDURE `user_get_by_username`(
  IN in_username VARCHAR(25)
)
BEGIN
  SELECT `id`, `username` FROM `user` WHERE `username` = in_username;
END //
DELIMITER ;

Code

import { RowDataPacket } from 'mysql2';

import configuration from '../configuration';

export interface User extends RowDataPacket {
  id: number;
  username: string;
}

databaseConnection = mysql.createConnection({
  database: configuration.mySQL.database(),
  host: configuration.mySQL.host(),
  password: configuration.mySQL.password(),
  user: configuration.mySQL.username(),
});

const userGetByUsername = ({ username }: { username: string }) =>
  new Promise<User | null>((resolve, reject) => {
    databaseConnection.execute<User[][]>(
      { sql: 'CALL user_get_by_username(?)', values: [username] },
      (error, response) => {
        console.log('response', response);
        if (error) {
          reject(
            new Error(`Failed to get user '${username}': ${error.message}`)
          );
        } else {
          resolve(response[0].length > 0 ? response[0][0] : null);
        }
      }
    );
  });

The issue is that execute does not return User[][], but instead it returns [User[], ResultSetHeader], and I cannot use the following as it does not work:

databaseConnection.execute<[User[], ResultSetHeader]>(