Created
March 4, 2021 09:30
-
-
Save piglovesyou/7df51982c6896b3e157f227377ffdb8e to your computer and use it in GitHub Desktop.
Node MySQL initialization snippet
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import mysql, { Connection } from "mysql"; | |
import { DB_HOST, DB_PASSWORD } from "./env"; | |
const databaseName = "xxx"; | |
const databaseUser = "xxx"; | |
const databasePort = 1234; | |
export const getConn: () => Connection = (() => { | |
let conn: Connection; | |
process.on("exit", () => { | |
if (conn) conn.destroy(); | |
}); | |
return () => { | |
if (conn) return conn; | |
conn = mysql.createConnection({ | |
host: DB_HOST, | |
database: databaseName, | |
user: databaseUser, | |
port: databasePort, | |
password: DB_PASSWORD, | |
}); | |
conn.connect(); | |
return conn; | |
}; | |
})(); | |
export async function query<ResultType = any>( | |
sqlFraments: TemplateStringsArray, | |
...values: any[] | |
): Promise<ResultType> { | |
const conn = getConn(); | |
return new Promise((resolve, reject) => { | |
conn.query(sqlFraments.join("?"), values, (err, result) => { | |
if (err) return reject(err); | |
resolve(result); | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment