conductor

CI task system
git clone git://git.finwo.net/app/conductor
Log | Files | Refs | README | LICENSE

params.js (1513B)


      1 // src/lib/db/params.js - bind value normalization shared by every driver
      2 //
      3 // Callers write portable application code and let this file absorb the
      4 // differences between drivers. node:sqlite rejects booleans, undefined and
      5 // Date objects outright; mysql2 and pg accept them but would each apply their
      6 // own timestamp handling. Timestamps are epoch milliseconds everywhere, so
      7 // Date values are flattened here rather than handed to any driver.
      8 
      9 export function normalizeValue(v, key) {
     10   if (v === undefined || v === null) return null;
     11   if (typeof v === 'boolean') return v ? 1 : 0;
     12   if (v instanceof Date) {
     13     if (Number.isNaN(v.getTime())) {
     14       throw new Error(`bind parameter ${key ? `{${key}} ` : ''}is an invalid Date`);
     15     }
     16     return v.getTime();
     17   }
     18   if (typeof v === 'bigint') {
     19     if (v > BigInt(Number.MAX_SAFE_INTEGER) || v < BigInt(Number.MIN_SAFE_INTEGER)) {
     20       throw new Error(`bind parameter ${key ? `{${key}} ` : ''}exceeds the safe integer range: ${v}`);
     21     }
     22     return Number(v);
     23   }
     24   if (typeof v === 'number' || typeof v === 'string') return v;
     25   if (Buffer.isBuffer(v) || v instanceof Uint8Array) return v;
     26 
     27   // Objects and arrays are almost always a forgotten JSON.stringify, or a
     28   // dotted key that should have addressed a leaf. Both are worth catching.
     29   throw new Error(
     30     `bind parameter ${key ? `{${key}} ` : ''}has unsupported type ${
     31       Array.isArray(v) ? 'array' : typeof v
     32     }; serialize it first, or address a nested value with a dotted key`
     33   );
     34 }