MKC
MKC

Reputation: 188

What is the proper way to integrate MySQL in Sveltekit?

I am struggling with integrating node-mysql2 into Sveltekit. As soon as the connection goes idle I get an 'ECONNRESET' error and my application freezes until the page is reloaded.

Below is my db.ts file located in src/lib. I import this into each server call that requires it and utilise the 'query' function.

Can anyone shed some light onto why I am running into this issue? Or is there a better way to do it?

import { DB_HOST, DB_USER, DB_PASSWORD } from '$env/static/private';
import DataBase from 'mysql2';


const pool = DataBase.createPool({
  host: DB_HOST,
  user: DB_USER,
  password: DB_PASSWORD,
  database: DB_NAME,
  waitForConnections: true,
  connectionLimit: 10,
  maxIdle: 10,
  idleTimeout: 600000,
  connectTimeout: 30000,
  queueLimit: 0,
  enableKeepAlive: true,
  keepAliveInitialDelay: 0,
  namedPlaceholders: true,
}).promise();


const query = async function (sql:string, vals:any = undefined) {
  
  try {
    const conn = await pool.getConnection();
    const [result] = await conn.query(sql, vals);
    conn.release();
    
    return result;

  } catch(e) {
    console.log(e);
  }
    
};

export default query;

Upvotes: 0

Views: 33

Answers (0)

Related Questions