Skip to content

Commit 20fd310

Browse files
committed
Normalize uniqueness errors (could use some refactoring)
1 parent 94a7cd2 commit 20fd310

File tree

2 files changed

+25
-3
lines changed

2 files changed

+25
-3
lines changed

lib/connections/spawn.js

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,8 +87,30 @@ module.exports = function spawnConnection (connectionObject, fn, cb__spawnConnec
8787

8888
// Handle errors passed back from our adapter logic.
8989
if (err) {
90+
var formattedErr;
91+
92+
93+
// Check for uniqueness constraint violations:
94+
if (err.code === 'ER_DUP_ENTRY') {
95+
96+
// Manually parse the MySQL error response and extract the relevant bits,
97+
// then build the formatted properties that will be passed directly to
98+
// WLValidationError in Waterline core.
99+
var matches = err.message.match(/Duplicate entry '(.*)' for key '(.*?)'$/);
100+
if (matches && matches.length) {
101+
formattedErr = {};
102+
formattedErr.code = 'E_UNIQUE';
103+
formattedErr.invalidAttributes = {};
104+
formattedErr.invalidAttributes[matches[2]] = [{
105+
value: matches[1],
106+
rule: 'unique'
107+
}];
108+
}
109+
}
110+
111+
// Release the connection, then pass control back to Waterline core.
90112
connectionObject.connection.releaseConnection(liveConnection, function sendBackError ( /* thisErrDoesntMatter */ ) {
91-
cb__spawnConnection(err);
113+
cb__spawnConnection(formattedErr || err);
92114
});
93115
return;
94116
}

lib/sql.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -499,8 +499,8 @@ function sqlTypeCast(attr) {
499499
return 'TIME';
500500

501501
default:
502-
console.error("Unregistered type given: " + type);
503-
return "TEXT";
502+
console.error('Unregistered type given: ' + type);
503+
return 'TEXT';
504504
}
505505
}
506506

0 commit comments

Comments
 (0)