Skip to content

Commit

Permalink
feat: add DuplicateEntryError
Browse files Browse the repository at this point in the history
  • Loading branch information
gajus committed Mar 27, 2017
1 parent 42c568e commit 9c875f6
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 7 deletions.
10 changes: 10 additions & 0 deletions src/errors.js
Expand Up @@ -16,3 +16,13 @@ export class NotFoundError extends ExtendableError {
}

export class DataIntegrityError extends ExtendableError {}

export class DuplicateEntryError extends ExtendableError {
code: string;

constructor (message: string) {
super(message);

this.code = 'ER_DUP_ENTRY';
}
}
28 changes: 21 additions & 7 deletions src/index.js
Expand Up @@ -9,6 +9,7 @@ import {
} from 'mysql2/promise';
import {
DataIntegrityError,
DuplicateEntryError,
NotFoundError
} from './errors';
import type {
Expand All @@ -26,25 +27,38 @@ export type {

export {
DataIntegrityError,
DuplicateEntryError,
NotFoundError
};

const debug = createDebug('mightyql');

export const query: InternalQueryType = async (connection, sql, values) => {
const formattedSql = SqlString.format(sql, values);
try {
const formattedSql = SqlString.format(sql, values);

debug('query', formattedSql);
debug('query', formattedSql);

const start = process.hrtime();
const start = process.hrtime();

const result = await connection.query(formattedSql);
const result = await connection.query(formattedSql);

const end = process.hrtime(start);
const end = process.hrtime(start);

debug('query execution time', prettyHrtime(end));
debug('query execution time', prettyHrtime(end));

return result;
if (Array.isArray(result[0])) {
debug('query returned %d row(s)', result[0].length);
}

return result;
} catch (error) {
if (error.code === 'ER_DUP_ENTRY') {
throw new DuplicateEntryError(error.message);
}

throw error;
}
};

export const insert: InternalQueryInsertType = async (connection, sql, values) => {
Expand Down

0 comments on commit 9c875f6

Please sign in to comment.