colossal-table-38461
02/21/2023, 11:04 AMlate-planet-4481
02/23/2023, 2:37 PMjs
const sql = require('mssql')
static customerDb = {
user: 'userNameHere',
password: 'passwordHere',
server: 'serverNameHere', // You can use 'localhost\\instance' to connect to named instance
database: 'dbNameHere',
}
module.exports = (statement, config) => {
return new Promise(async function (resolve, reject) {
console.log('***')
console.log(statement)
console.log('***')
const connectToDb = async (config) => {
try {
const pool = await sql.connect(config)
console.log('Connected to database')
return pool
} catch (err) {
console.log('Error connecting to database: ', err)
}
}
const execute = async (pool, query) => {
try {
const result = await pool.request().query(query)
console.log(result)
return result
} catch (err) {
console.log('Error executing query: ', err)
}
}
const closeDb = async (pool) => {
try {
await pool.close()
console.log('Connection closed')
} catch (err) {
console.log('Error closing connection: ', err)
}
}
const pool = await connectToDb(config)
const result = await execute(pool, statement)
await closeDb(pool)
resolve(result)
})
}late-planet-4481
02/23/2023, 2:37 PMplugins/index.js (or import it from a neighboring file, up to you):
js
const execSqlStatement = require('./db_exec_sql_statement')
function fetchCustomerId(email) {
const statement = `select customer_id from customer where email_address = '${email}'`
return new Promise((resolve) => {
execSqlStatement(statement, customerDb).then((result) => {
resolve(result.recordset[0].customer_id)
})
})
}
module.exports = (on) => {
on('task', {
fetchCustomerId,
})
}
And lastly, the usage in a test:
js
cy.task('fetchCustomerId', 'mrt@example.com').then((customerId) => {
cy.log(customerId)
}colossal-table-38461
02/25/2023, 7:12 AM