@@ -101,31 +101,42 @@ const parse = (query: ParseOpts): Buffer => {
101
101
return writer . flush ( code . parse )
102
102
}
103
103
104
+ type ValueMapper = ( param : any , index : number ) => any
105
+
104
106
type BindOpts = {
105
107
portal ?: string
106
108
binary ?: boolean
107
109
statement ?: string
108
110
values ?: any [ ]
109
111
// optional map from JS value to postgres value per parameter
110
- valueMap ?: ( param : any ) => any
112
+ valueMapper ?: ValueMapper
111
113
}
112
114
113
115
const paramWriter = new Writer ( )
114
116
115
- const writeValues = function ( values : any [ ] , valueMap ?: ( val : any ) => any ) : void {
117
+ // make this a const enum so typescript will inline the value
118
+ const enum ParamType {
119
+ STRING = 0 ,
120
+ BINARY = 1 ,
121
+ }
122
+
123
+ const writeValues = function ( values : any [ ] , valueMapper ?: ValueMapper ) : void {
116
124
for ( let i = 0 ; i < values . length ; i ++ ) {
117
- var val = values [ i ]
118
- if ( val === null || typeof val === 'undefined' ) {
119
- writer . addInt16 ( 0 )
125
+ const mappedVal = valueMapper ? valueMapper ( values [ i ] , i ) : values [ i ]
126
+ if ( mappedVal == null ) {
127
+ // add the param type (string) to the writer
128
+ writer . addInt16 ( ParamType . STRING )
129
+ // write -1 to the param writer to indicate null
120
130
paramWriter . addInt32 ( - 1 )
121
- } else if ( val instanceof Buffer ) {
122
- writer . addInt16 ( 1 )
123
- const mappedVal = valueMap ? valueMap ( val ) : val
131
+ } else if ( mappedVal instanceof Buffer ) {
132
+ // add the param type (binary) to the writer
133
+ writer . addInt16 ( ParamType . BINARY )
134
+ // add the buffer to the param writer
124
135
paramWriter . addInt32 ( mappedVal . length )
125
136
paramWriter . add ( mappedVal )
126
137
} else {
127
- writer . addInt16 ( 0 )
128
- const mappedVal = valueMap ? valueMap ( val ) : val
138
+ // add the param type (string) to the writer
139
+ writer . addInt16 ( ParamType . STRING )
129
140
paramWriter . addInt32 ( Buffer . byteLength ( mappedVal ) )
130
141
paramWriter . addString ( mappedVal )
131
142
}
@@ -143,17 +154,13 @@ const bind = (config: BindOpts = {}): Buffer => {
143
154
writer . addCString ( portal ) . addCString ( statement )
144
155
writer . addInt16 ( len )
145
156
146
- writeValues ( values , config . valueMap )
157
+ writeValues ( values , config . valueMapper )
147
158
148
159
writer . addInt16 ( len )
149
160
writer . add ( paramWriter . flush ( ) )
150
161
151
- if ( binary ) {
152
- writer . addInt16 ( 1 ) // format codes to use binary
153
- writer . addInt16 ( 1 )
154
- } else {
155
- writer . addInt16 ( 0 ) // format codes to use text
156
- }
162
+ // format code
163
+ writer . addInt16 ( binary ? ParamType . BINARY : ParamType . STRING )
157
164
return writer . flush ( code . bind )
158
165
}
159
166
0 commit comments