mirror of
https://github.com/matt-fidd/stratos.git
synced 2026-01-01 17:59:25 +00:00
Added validation and sanitisation for sql queries passed into runQuery
This commit is contained in:
@@ -2,23 +2,51 @@
|
||||
|
||||
const DatabaseConnectionPool = require('./DatabaseConnectionPool');
|
||||
|
||||
const mockRunQuery = jest.fn((sql, params) => {
|
||||
/**
|
||||
* Sanitise and validate an sql query
|
||||
*
|
||||
* @param {string} sql The query to be executed
|
||||
* @param {(Array<string|number>)} Values to replace prepared statement
|
||||
*
|
||||
* @return {string} Sanitised and validated sql query
|
||||
*/
|
||||
function validateQuery(sql, params) {
|
||||
sql = sql.trim();
|
||||
|
||||
if (sql.slice(-1) !== ';')
|
||||
throw new Error('Invalid query, needs trailing ;');
|
||||
throw new Error('Query needs trailing ;');
|
||||
|
||||
// Execute as non-prepared if no params are supplied
|
||||
if (typeof params === 'undefined') {
|
||||
return {
|
||||
const expectedParams = sql.split('?').length - 1;
|
||||
const prepared = expectedParams > 0;
|
||||
|
||||
if (!prepared && typeof params !== 'undefined') {
|
||||
throw new Error('Can not pass in parameters ' +
|
||||
'for a non-prepared statement');
|
||||
} else if (prepared && params.length !== expectedParams) {
|
||||
throw new Error('Number of params does not equal ' +
|
||||
'expected number');
|
||||
}
|
||||
|
||||
return sql;
|
||||
}
|
||||
|
||||
const mockRunQuery = jest.fn((sql, params) => {
|
||||
sql = validateQuery(sql, params);
|
||||
const prepared = sql.includes('?');
|
||||
|
||||
let data;
|
||||
if (!prepared) {
|
||||
data = {
|
||||
sql: sql
|
||||
};
|
||||
} else {
|
||||
data = {
|
||||
sql: sql,
|
||||
params: params
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
sql: sql,
|
||||
params: params
|
||||
};
|
||||
return data;
|
||||
});
|
||||
|
||||
const mockClose = jest.fn();
|
||||
|
||||
Reference in New Issue
Block a user