UNPKG

mysql-with-kysely

Version:
88 lines (87 loc) 3.79 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.isDuplicatedError = exports.mysql = void 0; const time_1 = require("@kanziw/time"); const logging_1 = require("./logging"); const query_1 = require("./query"); const mysql = (pool) => { const subscribers = []; const withConnection = (fn) => __awaiter(void 0, void 0, void 0, function* () { const connection = yield pool.getConnection(); return fn(connection).finally(() => connection.release()); }); const query = (0, query_1.queryWithSubscribers)(subscribers); return { ping({ timeoutMs = 3000 } = {}) { return __awaiter(this, void 0, void 0, function* () { const { promise, cancel } = (0, time_1.cancellableDelay)(timeoutMs); const isSuccess = yield Promise.race([ withConnection((connection) => connection.ping()) .then(() => true) .catch(() => false) .finally(() => cancel()), promise.then(() => false), ]); if (!isSuccess) { throw new Error('MySQL ping failed'); } }); }, query(kyselyQb) { return __awaiter(this, void 0, void 0, function* () { return withConnection((connection) => query(connection).query(kyselyQb)); }); }, execute(kyselyQb) { return __awaiter(this, void 0, void 0, function* () { return withConnection((connection) => query(connection).execute(kyselyQb)); }); }, truncate(tableName) { return __awaiter(this, void 0, void 0, function* () { return withConnection(connection => { const sql = `truncate table ${tableName}`; return (0, logging_1.withSqlQueryMetricPublish)(sql, [], subscribers, () => __awaiter(this, void 0, void 0, function* () { yield connection.execute(sql); })); }); }); }, withTransaction(fn) { return __awaiter(this, void 0, void 0, function* () { return withConnection((connection) => __awaiter(this, void 0, void 0, function* () { yield connection.beginTransaction(); try { const result = yield fn(query(connection)); yield connection.commit(); return result; } catch (err) { yield connection.rollback(); throw err; } })); }); }, subscribe(subscriber) { subscribers.push(subscriber); }, }; }; exports.mysql = mysql; const isDuplicatedError = (err) => { if (!(err instanceof Error)) { return false; } return err.errno === 1062; }; exports.isDuplicatedError = isDuplicatedError;