|
| 1 | +// see https://chatgpt.com/share/68c2df30-1f30-800e-94de-38fbbcdc88bd |
| 2 | +// Basically this ensures input Date objects are formated as iso strings, |
| 3 | +// so they are interpreted as UTC time properly. The root cause is that |
| 4 | +// our database schema uses "timestamp without timezone" everywhere, and |
| 5 | +// it would be painful to migrate everything. ANY query using |
| 6 | +// pool.query('...', params) |
| 7 | +// that potentially has Date's in params should pass the params through normalizeParams. |
| 8 | +// This is taken care of automatically in getPool and the db class. |
| 9 | + |
| 10 | +import type { Pool, QueryConfig } from "pg"; |
| 11 | + |
| 12 | +function normalizeValue(v: any): any { |
| 13 | + if (v instanceof Date) return v.toISOString(); |
| 14 | + if (Array.isArray(v)) return v.map(normalizeValue); |
| 15 | + return v; |
| 16 | +} |
| 17 | + |
| 18 | +export function normalizeValues(values?: any[]): any[] | undefined { |
| 19 | + return Array.isArray(values) ? values.map(normalizeValue) : values; |
| 20 | +} |
| 21 | + |
| 22 | +function normalizeQueryArgs(args: any[]): any[] { |
| 23 | + // Forms: |
| 24 | + // 1) query(text) |
| 25 | + // 2) query(text, values) |
| 26 | + // 3) query(text, values, callback) |
| 27 | + // 4) query(config) |
| 28 | + // 5) query(config, callback) |
| 29 | + if (typeof args[0] === "string") { |
| 30 | + if (Array.isArray(args[1])) { |
| 31 | + const v = normalizeValues(args[1]); |
| 32 | + if (args.length === 2) return [args[0], v]; |
| 33 | + // callback in position 2 |
| 34 | + return [args[0], v, args[2]]; |
| 35 | + } |
| 36 | + // only text (or text, callback) |
| 37 | + return args; |
| 38 | + } else { |
| 39 | + // config object path |
| 40 | + const cfg: QueryConfig = { ...args[0] }; |
| 41 | + if ("values" in cfg && Array.isArray(cfg.values)) { |
| 42 | + cfg.values = normalizeValues(cfg.values)!; |
| 43 | + } |
| 44 | + if (args.length === 1) return [cfg]; |
| 45 | + return [cfg, args[1]]; // callback passthrough |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +export function patchPoolForUtc(pool: Pool): Pool { |
| 50 | + if ((pool as any).__utcNormalized) return pool; |
| 51 | + |
| 52 | + // Patch pool.query |
| 53 | + const origPoolQuery = pool.query.bind(pool); |
| 54 | + (pool as any).query = function (...args: any[]) { |
| 55 | + return origPoolQuery(...normalizeQueryArgs(args)); |
| 56 | + } as typeof pool.query; |
| 57 | + |
| 58 | + pool.on("connect", (client) => { |
| 59 | + if ((client as any).__utcNormalized) return; |
| 60 | + const origQuery = client.query.bind(client); |
| 61 | + client.query = function (...args: any[]) { |
| 62 | + return origQuery(...normalizeQueryArgs(args)); |
| 63 | + } as typeof client.query; |
| 64 | + (client as any).__utcNormalized = true; |
| 65 | + }); |
| 66 | + |
| 67 | + (pool as any).__utcNormalized = true; |
| 68 | + return pool; |
| 69 | +} |
0 commit comments