1- import { createPool , PoolConnection } from "mysql" ;
1+ import { createPool } from "mysql" ;
22import {
33 DB_HOST ,
44 DB_USERNAME ,
55 DB_PORT ,
66 DB_PASSWORD ,
77 DB_DATABASE
88} from "../config" ;
9+ import { User } from "../interfaces/tables/user" ;
10+ import { BackupCode } from "../interfaces/tables/backup-codes" ;
11+ import { Email } from "../interfaces/tables/emails" ;
12+ import { Membership } from "../interfaces/tables/memberships" ;
13+ import { Organization } from "../interfaces/tables/organization" ;
914
1015export const pool = createPool ( {
1116 host : DB_HOST ,
@@ -17,15 +22,43 @@ export const pool = createPool({
1722
1823export const query = (
1924 queryString : string ,
20- values ?: ( string | number | boolean | Date ) [ ]
25+ values ?: ( string | number | boolean | Date | undefined ) [ ]
2126) =>
2227 new Promise ( ( resolve , reject ) => {
2328 pool . getConnection ( ( error , connection ) => {
2429 if ( error ) return reject ( error ) ;
30+ if ( values ) values = cleanValues ( values ) ;
2531 connection . query ( queryString , values , ( error , result ) => {
2632 connection . destroy ( ) ;
2733 if ( error ) return reject ( error ) ;
2834 resolve ( result ) ;
2935 } ) ;
3036 } ) ;
3137 } ) ;
38+
39+ export const tableValues = (
40+ object : User | BackupCode | Email | Membership | Organization
41+ ) => {
42+ const values = Object . keys ( object )
43+ . map ( ( ) => "?" )
44+ . join ( ", " ) ;
45+ const query = `(${ Object . keys ( object ) . join ( ", " ) } ) VALUES (${ values } )` ;
46+ return query ;
47+ } ;
48+
49+ export const cleanValues = (
50+ values : ( string | number | boolean | Date | undefined ) [ ]
51+ ) => {
52+ values = values . map ( value => {
53+ // Convert true to 1, false to 0
54+ if ( typeof value === "boolean" ) value = ! ! value ;
55+ // Convert Date to mysql datetime
56+ if ( typeof value === "object" && typeof value . getMonth === "function" )
57+ value = value
58+ . toISOString ( )
59+ . slice ( 0 , 19 )
60+ . replace ( "T" , " " ) ;
61+ return value ;
62+ } ) ;
63+ return values ;
64+ } ;
0 commit comments